babylon.max.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437
  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 = Tmp.Vector3[0];
  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 = Tmp.Vector3[1];
  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.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. 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));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. 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]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. 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);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. 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);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. 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);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * 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
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. 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);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. 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)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. 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;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. 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)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. // Temporary pre-allocated objects for engine internal use
  2955. // usage in any internal function :
  2956. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2957. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2958. var Tmp = (function () {
  2959. function Tmp() {
  2960. }
  2961. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2962. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2963. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  2964. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2965. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2966. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2967. Matrix.Zero(), Matrix.Zero(),
  2968. Matrix.Zero(), Matrix.Zero(),
  2969. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2970. return Tmp;
  2971. })();
  2972. BABYLON.Tmp = Tmp;
  2973. })(BABYLON || (BABYLON = {}));
  2974. var BABYLON;
  2975. (function (BABYLON) {
  2976. var Database = (function () {
  2977. function Database(urlToScene, callbackManifestChecked) {
  2978. // Handling various flavors of prefixed version of IndexedDB
  2979. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2980. this.callbackManifestChecked = callbackManifestChecked;
  2981. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2982. this.db = null;
  2983. this.enableSceneOffline = false;
  2984. this.enableTexturesOffline = false;
  2985. this.manifestVersionFound = 0;
  2986. this.mustUpdateRessources = false;
  2987. this.hasReachedQuota = false;
  2988. if (!Database.IDBStorageEnabled) {
  2989. this.callbackManifestChecked(true);
  2990. }
  2991. else {
  2992. this.checkManifestFile();
  2993. }
  2994. }
  2995. Database.prototype.checkManifestFile = function () {
  2996. var _this = this;
  2997. function noManifestFile() {
  2998. that.enableSceneOffline = false;
  2999. that.enableTexturesOffline = false;
  3000. that.callbackManifestChecked(false);
  3001. }
  3002. var that = this;
  3003. var timeStampUsed = false;
  3004. var manifestURL = this.currentSceneUrl + ".manifest";
  3005. var xhr = new XMLHttpRequest();
  3006. if (navigator.onLine) {
  3007. // Adding a timestamp to by-pass browsers' cache
  3008. timeStampUsed = true;
  3009. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3010. }
  3011. xhr.open("GET", manifestURL, true);
  3012. xhr.addEventListener("load", function () {
  3013. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3014. try {
  3015. var manifestFile = JSON.parse(xhr.response);
  3016. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3017. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3018. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3019. _this.manifestVersionFound = manifestFile.version;
  3020. }
  3021. if (_this.callbackManifestChecked) {
  3022. _this.callbackManifestChecked(true);
  3023. }
  3024. }
  3025. catch (ex) {
  3026. noManifestFile();
  3027. }
  3028. }
  3029. else {
  3030. noManifestFile();
  3031. }
  3032. }, false);
  3033. xhr.addEventListener("error", function (event) {
  3034. if (timeStampUsed) {
  3035. timeStampUsed = false;
  3036. // Let's retry without the timeStamp
  3037. // It could fail when coupled with HTML5 Offline API
  3038. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3039. xhr.open("GET", retryManifestURL, true);
  3040. xhr.send();
  3041. }
  3042. else {
  3043. noManifestFile();
  3044. }
  3045. }, false);
  3046. try {
  3047. xhr.send();
  3048. }
  3049. catch (ex) {
  3050. BABYLON.Tools.Error("Error on XHR send request.");
  3051. that.callbackManifestChecked(false);
  3052. }
  3053. };
  3054. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3055. var _this = this;
  3056. function handleError() {
  3057. that.isSupported = false;
  3058. if (errorCallback)
  3059. errorCallback();
  3060. }
  3061. var that = this;
  3062. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3063. // Your browser doesn't support IndexedDB
  3064. this.isSupported = false;
  3065. if (errorCallback)
  3066. errorCallback();
  3067. }
  3068. else {
  3069. // If the DB hasn't been opened or created yet
  3070. if (!this.db) {
  3071. this.hasReachedQuota = false;
  3072. this.isSupported = true;
  3073. var request = this.idbFactory.open("babylonjs", 1);
  3074. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3075. request.onerror = function (event) {
  3076. handleError();
  3077. };
  3078. // executes when a version change transaction cannot complete due to other active transactions
  3079. request.onblocked = function (event) {
  3080. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3081. handleError();
  3082. };
  3083. // DB has been opened successfully
  3084. request.onsuccess = function (event) {
  3085. _this.db = request.result;
  3086. successCallback();
  3087. };
  3088. // Initialization of the DB. Creating Scenes & Textures stores
  3089. request.onupgradeneeded = function (event) {
  3090. _this.db = (event.target).result;
  3091. try {
  3092. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3093. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3094. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3095. }
  3096. catch (ex) {
  3097. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3098. handleError();
  3099. }
  3100. };
  3101. }
  3102. else {
  3103. if (successCallback)
  3104. successCallback();
  3105. }
  3106. }
  3107. };
  3108. Database.prototype.loadImageFromDB = function (url, image) {
  3109. var _this = this;
  3110. var completeURL = Database.ReturnFullUrlLocation(url);
  3111. var saveAndLoadImage = function () {
  3112. if (!_this.hasReachedQuota && _this.db !== null) {
  3113. // the texture is not yet in the DB, let's try to save it
  3114. _this._saveImageIntoDBAsync(completeURL, image);
  3115. }
  3116. else {
  3117. image.src = url;
  3118. }
  3119. };
  3120. if (!this.mustUpdateRessources) {
  3121. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3122. }
  3123. else {
  3124. saveAndLoadImage();
  3125. }
  3126. };
  3127. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3128. if (this.isSupported && this.db !== null) {
  3129. var texture;
  3130. var transaction = this.db.transaction(["textures"]);
  3131. transaction.onabort = function (event) {
  3132. image.src = url;
  3133. };
  3134. transaction.oncomplete = function (event) {
  3135. var blobTextureURL;
  3136. if (texture) {
  3137. var URL = window.URL || window.webkitURL;
  3138. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3139. image.onerror = function () {
  3140. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3141. image.src = url;
  3142. };
  3143. image.src = blobTextureURL;
  3144. }
  3145. else {
  3146. notInDBCallback();
  3147. }
  3148. };
  3149. var getRequest = transaction.objectStore("textures").get(url);
  3150. getRequest.onsuccess = function (event) {
  3151. texture = (event.target).result;
  3152. };
  3153. getRequest.onerror = function (event) {
  3154. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3155. image.src = url;
  3156. };
  3157. }
  3158. else {
  3159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3160. image.src = url;
  3161. }
  3162. };
  3163. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3164. var _this = this;
  3165. if (this.isSupported) {
  3166. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3167. var generateBlobUrl = function () {
  3168. var blobTextureURL;
  3169. if (blob) {
  3170. var URL = window.URL || window.webkitURL;
  3171. try {
  3172. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3173. }
  3174. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3175. catch (ex) {
  3176. blobTextureURL = URL.createObjectURL(blob);
  3177. }
  3178. }
  3179. image.src = blobTextureURL;
  3180. };
  3181. if (Database.IsUASupportingBlobStorage) {
  3182. var xhr = new XMLHttpRequest(), blob;
  3183. xhr.open("GET", url, true);
  3184. xhr.responseType = "blob";
  3185. xhr.addEventListener("load", function () {
  3186. if (xhr.status === 200) {
  3187. // Blob as response (XHR2)
  3188. blob = xhr.response;
  3189. var transaction = _this.db.transaction(["textures"], "readwrite");
  3190. // the transaction could abort because of a QuotaExceededError error
  3191. transaction.onabort = function (event) {
  3192. try {
  3193. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3194. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3195. this.hasReachedQuota = true;
  3196. }
  3197. }
  3198. catch (ex) { }
  3199. generateBlobUrl();
  3200. };
  3201. transaction.oncomplete = function (event) {
  3202. generateBlobUrl();
  3203. };
  3204. var newTexture = { textureUrl: url, data: blob };
  3205. try {
  3206. // Put the blob into the dabase
  3207. var addRequest = transaction.objectStore("textures").put(newTexture);
  3208. addRequest.onsuccess = function (event) {
  3209. };
  3210. addRequest.onerror = function (event) {
  3211. generateBlobUrl();
  3212. };
  3213. }
  3214. catch (ex) {
  3215. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3216. if (ex.code === 25) {
  3217. Database.IsUASupportingBlobStorage = false;
  3218. }
  3219. image.src = url;
  3220. }
  3221. }
  3222. else {
  3223. image.src = url;
  3224. }
  3225. }, false);
  3226. xhr.addEventListener("error", function (event) {
  3227. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3228. image.src = url;
  3229. }, false);
  3230. xhr.send();
  3231. }
  3232. else {
  3233. image.src = url;
  3234. }
  3235. }
  3236. else {
  3237. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3238. image.src = url;
  3239. }
  3240. };
  3241. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3242. var _this = this;
  3243. var updateVersion = function (event) {
  3244. // the version is not yet in the DB or we need to update it
  3245. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3246. };
  3247. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3248. };
  3249. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3250. var _this = this;
  3251. if (this.isSupported) {
  3252. var version;
  3253. try {
  3254. var transaction = this.db.transaction(["versions"]);
  3255. transaction.oncomplete = function (event) {
  3256. if (version) {
  3257. // If the version in the JSON file is > than the version in DB
  3258. if (_this.manifestVersionFound > version.data) {
  3259. _this.mustUpdateRessources = true;
  3260. updateInDBCallback();
  3261. }
  3262. else {
  3263. callback(version.data);
  3264. }
  3265. }
  3266. else {
  3267. _this.mustUpdateRessources = true;
  3268. updateInDBCallback();
  3269. }
  3270. };
  3271. transaction.onabort = function (event) {
  3272. callback(-1);
  3273. };
  3274. var getRequest = transaction.objectStore("versions").get(url);
  3275. getRequest.onsuccess = function (event) {
  3276. version = (event.target).result;
  3277. };
  3278. getRequest.onerror = function (event) {
  3279. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3280. callback(-1);
  3281. };
  3282. }
  3283. catch (ex) {
  3284. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3285. callback(-1);
  3286. }
  3287. }
  3288. else {
  3289. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3290. callback(-1);
  3291. }
  3292. };
  3293. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3294. var _this = this;
  3295. if (this.isSupported && !this.hasReachedQuota) {
  3296. try {
  3297. // Open a transaction to the database
  3298. var transaction = this.db.transaction(["versions"], "readwrite");
  3299. // the transaction could abort because of a QuotaExceededError error
  3300. transaction.onabort = function (event) {
  3301. try {
  3302. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3303. _this.hasReachedQuota = true;
  3304. }
  3305. }
  3306. catch (ex) { }
  3307. callback(-1);
  3308. };
  3309. transaction.oncomplete = function (event) {
  3310. callback(_this.manifestVersionFound);
  3311. };
  3312. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3313. // Put the scene into the database
  3314. var addRequest = transaction.objectStore("versions").put(newVersion);
  3315. addRequest.onsuccess = function (event) {
  3316. };
  3317. addRequest.onerror = function (event) {
  3318. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3319. };
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3323. callback(-1);
  3324. }
  3325. }
  3326. else {
  3327. callback(-1);
  3328. }
  3329. };
  3330. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3331. var _this = this;
  3332. var completeUrl = Database.ReturnFullUrlLocation(url);
  3333. var saveAndLoadFile = function (event) {
  3334. // the scene is not yet in the DB, let's try to save it
  3335. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3336. };
  3337. this._checkVersionFromDB(completeUrl, function (version) {
  3338. if (version !== -1) {
  3339. if (!_this.mustUpdateRessources) {
  3340. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3341. }
  3342. else {
  3343. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3344. }
  3345. }
  3346. else {
  3347. errorCallback();
  3348. }
  3349. });
  3350. };
  3351. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3352. if (this.isSupported) {
  3353. var targetStore;
  3354. if (url.indexOf(".babylon") !== -1) {
  3355. targetStore = "scenes";
  3356. }
  3357. else {
  3358. targetStore = "textures";
  3359. }
  3360. var file;
  3361. var transaction = this.db.transaction([targetStore]);
  3362. transaction.oncomplete = function (event) {
  3363. if (file) {
  3364. callback(file.data);
  3365. }
  3366. else {
  3367. notInDBCallback();
  3368. }
  3369. };
  3370. transaction.onabort = function (event) {
  3371. notInDBCallback();
  3372. };
  3373. var getRequest = transaction.objectStore(targetStore).get(url);
  3374. getRequest.onsuccess = function (event) {
  3375. file = (event.target).result;
  3376. };
  3377. getRequest.onerror = function (event) {
  3378. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3379. notInDBCallback();
  3380. };
  3381. }
  3382. else {
  3383. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3384. callback();
  3385. }
  3386. };
  3387. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3388. var _this = this;
  3389. if (this.isSupported) {
  3390. var targetStore;
  3391. if (url.indexOf(".babylon") !== -1) {
  3392. targetStore = "scenes";
  3393. }
  3394. else {
  3395. targetStore = "textures";
  3396. }
  3397. // Create XHR
  3398. var xhr = new XMLHttpRequest(), fileData;
  3399. xhr.open("GET", url, true);
  3400. if (useArrayBuffer) {
  3401. xhr.responseType = "arraybuffer";
  3402. }
  3403. xhr.onprogress = progressCallback;
  3404. xhr.addEventListener("load", function () {
  3405. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3406. // Blob as response (XHR2)
  3407. //fileData = xhr.responseText;
  3408. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3409. if (!_this.hasReachedQuota) {
  3410. // Open a transaction to the database
  3411. var transaction = _this.db.transaction([targetStore], "readwrite");
  3412. // the transaction could abort because of a QuotaExceededError error
  3413. transaction.onabort = function (event) {
  3414. try {
  3415. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3416. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3417. this.hasReachedQuota = true;
  3418. }
  3419. }
  3420. catch (ex) { }
  3421. callback(fileData);
  3422. };
  3423. transaction.oncomplete = function (event) {
  3424. callback(fileData);
  3425. };
  3426. var newFile;
  3427. if (targetStore === "scenes") {
  3428. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3429. }
  3430. else {
  3431. newFile = { textureUrl: url, data: fileData };
  3432. }
  3433. try {
  3434. // Put the scene into the database
  3435. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3436. addRequest.onsuccess = function (event) {
  3437. };
  3438. addRequest.onerror = function (event) {
  3439. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3440. };
  3441. }
  3442. catch (ex) {
  3443. callback(fileData);
  3444. }
  3445. }
  3446. else {
  3447. callback(fileData);
  3448. }
  3449. }
  3450. else {
  3451. callback();
  3452. }
  3453. }, false);
  3454. xhr.addEventListener("error", function (event) {
  3455. BABYLON.Tools.Error("error on XHR request.");
  3456. callback();
  3457. }, false);
  3458. xhr.send();
  3459. }
  3460. else {
  3461. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3462. callback();
  3463. }
  3464. };
  3465. Database.IsUASupportingBlobStorage = true;
  3466. Database.IDBStorageEnabled = true;
  3467. Database.parseURL = function (url) {
  3468. var a = document.createElement('a');
  3469. a.href = url;
  3470. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3471. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3472. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3473. return absLocation;
  3474. };
  3475. Database.ReturnFullUrlLocation = function (url) {
  3476. if (url.indexOf("http:/") === -1) {
  3477. return (Database.parseURL(window.location.href) + url);
  3478. }
  3479. else {
  3480. return url;
  3481. }
  3482. };
  3483. return Database;
  3484. })();
  3485. BABYLON.Database = Database;
  3486. })(BABYLON || (BABYLON = {}));
  3487. var BABYLON;
  3488. (function (BABYLON) {
  3489. var Internals;
  3490. (function (Internals) {
  3491. /*
  3492. * Based on jsTGALoader - Javascript loader for TGA file
  3493. * By Vincent Thibault
  3494. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3495. */
  3496. var TGATools = (function () {
  3497. function TGATools() {
  3498. }
  3499. TGATools.GetTGAHeader = function (data) {
  3500. var offset = 0;
  3501. var header = {
  3502. id_length: data[offset++],
  3503. colormap_type: data[offset++],
  3504. image_type: data[offset++],
  3505. colormap_index: data[offset++] | data[offset++] << 8,
  3506. colormap_length: data[offset++] | data[offset++] << 8,
  3507. colormap_size: data[offset++],
  3508. origin: [
  3509. data[offset++] | data[offset++] << 8,
  3510. data[offset++] | data[offset++] << 8
  3511. ],
  3512. width: data[offset++] | data[offset++] << 8,
  3513. height: data[offset++] | data[offset++] << 8,
  3514. pixel_size: data[offset++],
  3515. flags: data[offset++]
  3516. };
  3517. return header;
  3518. };
  3519. TGATools.UploadContent = function (gl, data) {
  3520. // Not enough data to contain header ?
  3521. if (data.length < 19) {
  3522. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3523. return;
  3524. }
  3525. // Read Header
  3526. var offset = 18;
  3527. var header = TGATools.GetTGAHeader(data);
  3528. // Assume it's a valid Targa file.
  3529. if (header.id_length + offset > data.length) {
  3530. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3531. return;
  3532. }
  3533. // Skip not needed data
  3534. offset += header.id_length;
  3535. var use_rle = false;
  3536. var use_pal = false;
  3537. var use_rgb = false;
  3538. var use_grey = false;
  3539. // Get some informations.
  3540. switch (header.image_type) {
  3541. case TGATools._TYPE_RLE_INDEXED:
  3542. use_rle = true;
  3543. case TGATools._TYPE_INDEXED:
  3544. use_pal = true;
  3545. break;
  3546. case TGATools._TYPE_RLE_RGB:
  3547. use_rle = true;
  3548. case TGATools._TYPE_RGB:
  3549. use_rgb = true;
  3550. break;
  3551. case TGATools._TYPE_RLE_GREY:
  3552. use_rle = true;
  3553. case TGATools._TYPE_GREY:
  3554. use_grey = true;
  3555. break;
  3556. }
  3557. var pixel_data;
  3558. var numAlphaBits = header.flags & 0xf;
  3559. var pixel_size = header.pixel_size >> 3;
  3560. var pixel_total = header.width * header.height * pixel_size;
  3561. // Read palettes
  3562. var palettes;
  3563. if (use_pal) {
  3564. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3565. }
  3566. // Read LRE
  3567. if (use_rle) {
  3568. pixel_data = new Uint8Array(pixel_total);
  3569. var c, count, i;
  3570. var localOffset = 0;
  3571. var pixels = new Uint8Array(pixel_size);
  3572. while (offset < pixel_total && localOffset < pixel_total) {
  3573. c = data[offset++];
  3574. count = (c & 0x7f) + 1;
  3575. // RLE pixels
  3576. if (c & 0x80) {
  3577. // Bind pixel tmp array
  3578. for (i = 0; i < pixel_size; ++i) {
  3579. pixels[i] = data[offset++];
  3580. }
  3581. // Copy pixel array
  3582. for (i = 0; i < count; ++i) {
  3583. pixel_data.set(pixels, localOffset + i * pixel_size);
  3584. }
  3585. localOffset += pixel_size * count;
  3586. }
  3587. else {
  3588. count *= pixel_size;
  3589. for (i = 0; i < count; ++i) {
  3590. pixel_data[localOffset + i] = data[offset++];
  3591. }
  3592. localOffset += count;
  3593. }
  3594. }
  3595. }
  3596. else {
  3597. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3598. }
  3599. // Load to texture
  3600. var x_start, y_start, x_step, y_step, y_end, x_end;
  3601. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3602. default:
  3603. case TGATools._ORIGIN_UL:
  3604. x_start = 0;
  3605. x_step = 1;
  3606. x_end = header.width;
  3607. y_start = 0;
  3608. y_step = 1;
  3609. y_end = header.height;
  3610. break;
  3611. case TGATools._ORIGIN_BL:
  3612. x_start = 0;
  3613. x_step = 1;
  3614. x_end = header.width;
  3615. y_start = header.height - 1;
  3616. y_step = -1;
  3617. y_end = -1;
  3618. break;
  3619. case TGATools._ORIGIN_UR:
  3620. x_start = header.width - 1;
  3621. x_step = -1;
  3622. x_end = -1;
  3623. y_start = 0;
  3624. y_step = 1;
  3625. y_end = header.height;
  3626. break;
  3627. case TGATools._ORIGIN_BR:
  3628. x_start = header.width - 1;
  3629. x_step = -1;
  3630. x_end = -1;
  3631. y_start = header.height - 1;
  3632. y_step = -1;
  3633. y_end = -1;
  3634. break;
  3635. }
  3636. // Load the specify method
  3637. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3638. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3639. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3640. };
  3641. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3642. var image = pixel_data, colormap = palettes;
  3643. var width = header.width, height = header.height;
  3644. var color, i = 0, x, y;
  3645. var imageData = new Uint8Array(width * height * 4);
  3646. for (y = y_start; y !== y_end; y += y_step) {
  3647. for (x = x_start; x !== x_end; x += x_step, i++) {
  3648. color = image[i];
  3649. imageData[(x + width * y) * 4 + 3] = 255;
  3650. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3651. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3652. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3653. }
  3654. }
  3655. return imageData;
  3656. };
  3657. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3658. var image = pixel_data;
  3659. var width = header.width, height = header.height;
  3660. var color, i = 0, x, y;
  3661. var imageData = new Uint8Array(width * height * 4);
  3662. for (y = y_start; y !== y_end; y += y_step) {
  3663. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3664. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3665. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3666. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3667. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3668. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3669. }
  3670. }
  3671. return imageData;
  3672. };
  3673. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3674. var image = pixel_data;
  3675. var width = header.width, height = header.height;
  3676. var i = 0, x, y;
  3677. var imageData = new Uint8Array(width * height * 4);
  3678. for (y = y_start; y !== y_end; y += y_step) {
  3679. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3680. imageData[(x + width * y) * 4 + 3] = 255;
  3681. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3682. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3683. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3684. }
  3685. }
  3686. return imageData;
  3687. };
  3688. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3689. var image = pixel_data;
  3690. var width = header.width, height = header.height;
  3691. var i = 0, x, y;
  3692. var imageData = new Uint8Array(width * height * 4);
  3693. for (y = y_start; y !== y_end; y += y_step) {
  3694. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3695. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3696. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3697. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3698. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3699. }
  3700. }
  3701. return imageData;
  3702. };
  3703. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3704. var image = pixel_data;
  3705. var width = header.width, height = header.height;
  3706. var color, i = 0, x, y;
  3707. var imageData = new Uint8Array(width * height * 4);
  3708. for (y = y_start; y !== y_end; y += y_step) {
  3709. for (x = x_start; x !== x_end; x += x_step, i++) {
  3710. color = image[i];
  3711. imageData[(x + width * y) * 4 + 0] = color;
  3712. imageData[(x + width * y) * 4 + 1] = color;
  3713. imageData[(x + width * y) * 4 + 2] = color;
  3714. imageData[(x + width * y) * 4 + 3] = 255;
  3715. }
  3716. }
  3717. return imageData;
  3718. };
  3719. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3720. var image = pixel_data;
  3721. var width = header.width, height = header.height;
  3722. var i = 0, x, y;
  3723. var imageData = new Uint8Array(width * height * 4);
  3724. for (y = y_start; y !== y_end; y += y_step) {
  3725. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3726. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3727. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3728. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3729. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3730. }
  3731. }
  3732. return imageData;
  3733. };
  3734. TGATools._TYPE_NO_DATA = 0;
  3735. TGATools._TYPE_INDEXED = 1;
  3736. TGATools._TYPE_RGB = 2;
  3737. TGATools._TYPE_GREY = 3;
  3738. TGATools._TYPE_RLE_INDEXED = 9;
  3739. TGATools._TYPE_RLE_RGB = 10;
  3740. TGATools._TYPE_RLE_GREY = 11;
  3741. TGATools._ORIGIN_MASK = 0x30;
  3742. TGATools._ORIGIN_SHIFT = 0x04;
  3743. TGATools._ORIGIN_BL = 0x00;
  3744. TGATools._ORIGIN_BR = 0x01;
  3745. TGATools._ORIGIN_UL = 0x02;
  3746. TGATools._ORIGIN_UR = 0x03;
  3747. return TGATools;
  3748. })();
  3749. Internals.TGATools = TGATools;
  3750. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3751. })(BABYLON || (BABYLON = {}));
  3752. var BABYLON;
  3753. (function (BABYLON) {
  3754. var SmartArray = (function () {
  3755. function SmartArray(capacity) {
  3756. this.length = 0;
  3757. this._duplicateId = 0;
  3758. this.data = new Array(capacity);
  3759. this._id = SmartArray._GlobalId++;
  3760. }
  3761. SmartArray.prototype.push = function (value) {
  3762. this.data[this.length++] = value;
  3763. if (this.length > this.data.length) {
  3764. this.data.length *= 2;
  3765. }
  3766. if (!value.__smartArrayFlags) {
  3767. value.__smartArrayFlags = {};
  3768. }
  3769. value.__smartArrayFlags[this._id] = this._duplicateId;
  3770. };
  3771. SmartArray.prototype.pushNoDuplicate = function (value) {
  3772. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3773. return;
  3774. }
  3775. this.push(value);
  3776. };
  3777. SmartArray.prototype.sort = function (compareFn) {
  3778. this.data.sort(compareFn);
  3779. };
  3780. SmartArray.prototype.reset = function () {
  3781. this.length = 0;
  3782. this._duplicateId++;
  3783. };
  3784. SmartArray.prototype.concat = function (array) {
  3785. if (array.length === 0) {
  3786. return;
  3787. }
  3788. if (this.length + array.length > this.data.length) {
  3789. this.data.length = (this.length + array.length) * 2;
  3790. }
  3791. for (var index = 0; index < array.length; index++) {
  3792. this.data[this.length++] = (array.data || array)[index];
  3793. }
  3794. };
  3795. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3796. if (array.length === 0) {
  3797. return;
  3798. }
  3799. if (this.length + array.length > this.data.length) {
  3800. this.data.length = (this.length + array.length) * 2;
  3801. }
  3802. for (var index = 0; index < array.length; index++) {
  3803. var item = (array.data || array)[index];
  3804. this.pushNoDuplicate(item);
  3805. }
  3806. };
  3807. SmartArray.prototype.indexOf = function (value) {
  3808. var position = this.data.indexOf(value);
  3809. if (position >= this.length) {
  3810. return -1;
  3811. }
  3812. return position;
  3813. };
  3814. // Statics
  3815. SmartArray._GlobalId = 0;
  3816. return SmartArray;
  3817. })();
  3818. BABYLON.SmartArray = SmartArray;
  3819. })(BABYLON || (BABYLON = {}));
  3820. var BABYLON;
  3821. (function (BABYLON) {
  3822. var SmartCollection = (function () {
  3823. function SmartCollection(capacity) {
  3824. if (capacity === void 0) { capacity = 10; }
  3825. this.count = 0;
  3826. this._initialCapacity = capacity;
  3827. this.items = {};
  3828. this._keys = new Array(this._initialCapacity);
  3829. }
  3830. SmartCollection.prototype.add = function (key, item) {
  3831. if (this.items[key] != undefined) {
  3832. return -1;
  3833. }
  3834. this.items[key] = item;
  3835. //literal keys are always strings, but we keep source type of key in _keys array
  3836. this._keys[this.count++] = key;
  3837. if (this.count > this._keys.length) {
  3838. this._keys.length *= 2;
  3839. }
  3840. return this.count;
  3841. };
  3842. SmartCollection.prototype.remove = function (key) {
  3843. if (this.items[key] == undefined) {
  3844. return -1;
  3845. }
  3846. return this.removeItemOfIndex(this.indexOf(key));
  3847. };
  3848. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3849. if (index < this.count && index > -1) {
  3850. delete this.items[this._keys[index]];
  3851. //here, shifting by hand is better optimised than .splice
  3852. while (index < this.count) {
  3853. this._keys[index] = this._keys[index + 1];
  3854. index++;
  3855. }
  3856. }
  3857. else {
  3858. return -1;
  3859. }
  3860. return --this.count;
  3861. };
  3862. SmartCollection.prototype.indexOf = function (key) {
  3863. for (var i = 0; i !== this.count; i++) {
  3864. if (this._keys[i] === key) {
  3865. return i;
  3866. }
  3867. }
  3868. return -1;
  3869. };
  3870. SmartCollection.prototype.item = function (key) {
  3871. return this.items[key];
  3872. };
  3873. SmartCollection.prototype.getAllKeys = function () {
  3874. if (this.count > 0) {
  3875. var keys = new Array(this.count);
  3876. for (var i = 0; i < this.count; i++) {
  3877. keys[i] = this._keys[i];
  3878. }
  3879. return keys;
  3880. }
  3881. else {
  3882. return undefined;
  3883. }
  3884. };
  3885. SmartCollection.prototype.getKeyByIndex = function (index) {
  3886. if (index < this.count && index > -1) {
  3887. return this._keys[index];
  3888. }
  3889. else {
  3890. return undefined;
  3891. }
  3892. };
  3893. SmartCollection.prototype.getItemByIndex = function (index) {
  3894. if (index < this.count && index > -1) {
  3895. return this.items[this._keys[index]];
  3896. }
  3897. else {
  3898. return undefined;
  3899. }
  3900. };
  3901. SmartCollection.prototype.empty = function () {
  3902. if (this.count > 0) {
  3903. this.count = 0;
  3904. this.items = {};
  3905. this._keys = new Array(this._initialCapacity);
  3906. }
  3907. };
  3908. SmartCollection.prototype.forEach = function (block) {
  3909. var key;
  3910. for (key in this.items) {
  3911. if (this.items.hasOwnProperty(key)) {
  3912. block(this.items[key]);
  3913. }
  3914. }
  3915. };
  3916. return SmartCollection;
  3917. })();
  3918. BABYLON.SmartCollection = SmartCollection;
  3919. })(BABYLON || (BABYLON = {}));
  3920. var BABYLON;
  3921. (function (BABYLON) {
  3922. // Screenshots
  3923. var screenshotCanvas;
  3924. var cloneValue = function (source, destinationObject) {
  3925. if (!source)
  3926. return null;
  3927. if (source instanceof BABYLON.Mesh) {
  3928. return null;
  3929. }
  3930. if (source instanceof BABYLON.SubMesh) {
  3931. return source.clone(destinationObject);
  3932. }
  3933. else if (source.clone) {
  3934. return source.clone();
  3935. }
  3936. return null;
  3937. };
  3938. var Tools = (function () {
  3939. function Tools() {
  3940. }
  3941. Tools.Instantiate = function (className) {
  3942. var arr = className.split(".");
  3943. var fn = (window || this);
  3944. for (var i = 0, len = arr.length; i < len; i++) {
  3945. fn = fn[arr[i]];
  3946. }
  3947. if (typeof fn !== "function") {
  3948. return null;
  3949. }
  3950. return fn;
  3951. };
  3952. Tools.GetConstructorName = function (obj) {
  3953. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3954. var cname = str.match(/function\s(\w*)/)[1];
  3955. var aliases = ["", "anonymous", "Anonymous"];
  3956. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3957. };
  3958. Tools.ToHex = function (i) {
  3959. var str = i.toString(16);
  3960. if (i <= 15) {
  3961. return ("0" + str).toUpperCase();
  3962. }
  3963. return str.toUpperCase();
  3964. };
  3965. Tools.SetImmediate = function (action) {
  3966. if (window.setImmediate) {
  3967. window.setImmediate(action);
  3968. }
  3969. else {
  3970. setTimeout(action, 1);
  3971. }
  3972. };
  3973. Tools.IsExponentOfTwo = function (value) {
  3974. var count = 1;
  3975. do {
  3976. count *= 2;
  3977. } while (count < value);
  3978. return count === value;
  3979. };
  3980. Tools.GetExponentOfTwo = function (value, max) {
  3981. var count = 1;
  3982. do {
  3983. count *= 2;
  3984. } while (count < value);
  3985. if (count > max)
  3986. count = max;
  3987. return count;
  3988. };
  3989. Tools.GetFilename = function (path) {
  3990. var index = path.lastIndexOf("/");
  3991. if (index < 0)
  3992. return path;
  3993. return path.substring(index + 1);
  3994. };
  3995. Tools.GetDOMTextContent = function (element) {
  3996. var result = "";
  3997. var child = element.firstChild;
  3998. while (child) {
  3999. if (child.nodeType === 3) {
  4000. result += child.textContent;
  4001. }
  4002. child = child.nextSibling;
  4003. }
  4004. return result;
  4005. };
  4006. Tools.ToDegrees = function (angle) {
  4007. return angle * 180 / Math.PI;
  4008. };
  4009. Tools.ToRadians = function (angle) {
  4010. return angle * Math.PI / 180;
  4011. };
  4012. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4013. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4014. var output = "";
  4015. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4016. var i = 0;
  4017. var bytes = new Uint8Array(buffer);
  4018. while (i < bytes.length) {
  4019. chr1 = bytes[i++];
  4020. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4021. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4022. enc1 = chr1 >> 2;
  4023. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4024. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4025. enc4 = chr3 & 63;
  4026. if (isNaN(chr2)) {
  4027. enc3 = enc4 = 64;
  4028. }
  4029. else if (isNaN(chr3)) {
  4030. enc4 = 64;
  4031. }
  4032. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4033. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4034. }
  4035. return "data:image/png;base64," + output;
  4036. };
  4037. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4038. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4039. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4040. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4041. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4042. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4043. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4044. }
  4045. return {
  4046. minimum: minimum,
  4047. maximum: maximum
  4048. };
  4049. };
  4050. Tools.ExtractMinAndMax = function (positions, start, count) {
  4051. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4052. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4053. for (var index = start; index < start + count; index++) {
  4054. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4055. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4056. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4057. }
  4058. return {
  4059. minimum: minimum,
  4060. maximum: maximum
  4061. };
  4062. };
  4063. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4064. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4065. return undefined;
  4066. return Array.isArray(obj) ? obj : [obj];
  4067. };
  4068. // Misc.
  4069. Tools.GetPointerPrefix = function () {
  4070. var eventPrefix = "pointer";
  4071. // Check if pointer events are supported
  4072. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4073. eventPrefix = "mouse";
  4074. }
  4075. return eventPrefix;
  4076. };
  4077. Tools.QueueNewFrame = function (func) {
  4078. if (window.requestAnimationFrame)
  4079. window.requestAnimationFrame(func);
  4080. else if (window.msRequestAnimationFrame)
  4081. window.msRequestAnimationFrame(func);
  4082. else if (window.webkitRequestAnimationFrame)
  4083. window.webkitRequestAnimationFrame(func);
  4084. else if (window.mozRequestAnimationFrame)
  4085. window.mozRequestAnimationFrame(func);
  4086. else if (window.oRequestAnimationFrame)
  4087. window.oRequestAnimationFrame(func);
  4088. else {
  4089. window.setTimeout(func, 16);
  4090. }
  4091. };
  4092. Tools.RequestFullscreen = function (element) {
  4093. if (element.requestFullscreen)
  4094. element.requestFullscreen();
  4095. else if (element.msRequestFullscreen)
  4096. element.msRequestFullscreen();
  4097. else if (element.webkitRequestFullscreen)
  4098. element.webkitRequestFullscreen();
  4099. else if (element.mozRequestFullScreen)
  4100. element.mozRequestFullScreen();
  4101. };
  4102. Tools.ExitFullscreen = function () {
  4103. if (document.exitFullscreen) {
  4104. document.exitFullscreen();
  4105. }
  4106. else if (document.mozCancelFullScreen) {
  4107. document.mozCancelFullScreen();
  4108. }
  4109. else if (document.webkitCancelFullScreen) {
  4110. document.webkitCancelFullScreen();
  4111. }
  4112. else if (document.msCancelFullScreen) {
  4113. document.msCancelFullScreen();
  4114. }
  4115. };
  4116. // External files
  4117. Tools.CleanUrl = function (url) {
  4118. url = url.replace(/#/mg, "%23");
  4119. return url;
  4120. };
  4121. Tools.LoadImage = function (url, onload, onerror, database) {
  4122. if (url instanceof ArrayBuffer) {
  4123. url = Tools.EncodeArrayBufferTobase64(url);
  4124. }
  4125. url = Tools.CleanUrl(url);
  4126. var img = new Image();
  4127. if (url.substr(0, 5) !== "data:") {
  4128. if (Tools.CorsBehavior) {
  4129. switch (typeof (Tools.CorsBehavior)) {
  4130. case "function":
  4131. var result = Tools.CorsBehavior(url);
  4132. if (result) {
  4133. img.crossOrigin = result;
  4134. }
  4135. break;
  4136. case "string":
  4137. default:
  4138. img.crossOrigin = Tools.CorsBehavior;
  4139. break;
  4140. }
  4141. }
  4142. }
  4143. img.onload = function () {
  4144. onload(img);
  4145. };
  4146. img.onerror = function (err) {
  4147. Tools.Error("Error while trying to load texture: " + url);
  4148. if (Tools.UseFallbackTexture) {
  4149. 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";
  4150. onload(img);
  4151. }
  4152. else {
  4153. onerror();
  4154. }
  4155. };
  4156. var noIndexedDB = function () {
  4157. img.src = url;
  4158. };
  4159. var loadFromIndexedDB = function () {
  4160. database.loadImageFromDB(url, img);
  4161. };
  4162. //ANY database to do!
  4163. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4164. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4165. }
  4166. else {
  4167. if (url.indexOf("file:") === -1) {
  4168. noIndexedDB();
  4169. }
  4170. else {
  4171. try {
  4172. var textureName = url.substring(5);
  4173. var blobURL;
  4174. try {
  4175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4176. }
  4177. catch (ex) {
  4178. // Chrome doesn't support oneTimeOnly parameter
  4179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4180. }
  4181. img.src = blobURL;
  4182. }
  4183. catch (e) {
  4184. img.src = null;
  4185. }
  4186. }
  4187. }
  4188. return img;
  4189. };
  4190. //ANY
  4191. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4192. url = Tools.CleanUrl(url);
  4193. var noIndexedDB = function () {
  4194. var request = new XMLHttpRequest();
  4195. var loadUrl = Tools.BaseUrl + url;
  4196. request.open('GET', loadUrl, true);
  4197. if (useArrayBuffer) {
  4198. request.responseType = "arraybuffer";
  4199. }
  4200. request.onprogress = progressCallBack;
  4201. request.onreadystatechange = function () {
  4202. if (request.readyState === 4) {
  4203. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4204. callback(!useArrayBuffer ? request.responseText : request.response);
  4205. }
  4206. else {
  4207. if (onError) {
  4208. onError();
  4209. }
  4210. else {
  4211. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4212. }
  4213. }
  4214. }
  4215. };
  4216. request.send(null);
  4217. };
  4218. var loadFromIndexedDB = function () {
  4219. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4220. };
  4221. if (url.indexOf("file:") !== -1) {
  4222. var fileName = url.substring(5);
  4223. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4224. }
  4225. else {
  4226. // Caching all files
  4227. if (database && database.enableSceneOffline) {
  4228. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4229. }
  4230. else {
  4231. noIndexedDB();
  4232. }
  4233. }
  4234. };
  4235. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4236. var reader = new FileReader();
  4237. reader.onload = function (e) {
  4238. //target doesn't have result from ts 1.3
  4239. callback(e.target['result']);
  4240. };
  4241. reader.onprogress = progressCallback;
  4242. reader.readAsDataURL(fileToLoad);
  4243. };
  4244. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4245. var reader = new FileReader();
  4246. reader.onerror = function (e) {
  4247. Tools.Log("Error while reading file: " + fileToLoad.name);
  4248. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4249. };
  4250. reader.onload = function (e) {
  4251. //target doesn't have result from ts 1.3
  4252. callback(e.target['result']);
  4253. };
  4254. reader.onprogress = progressCallBack;
  4255. if (!useArrayBuffer) {
  4256. // Asynchronous read
  4257. reader.readAsText(fileToLoad);
  4258. }
  4259. else {
  4260. reader.readAsArrayBuffer(fileToLoad);
  4261. }
  4262. };
  4263. //returns a downloadable url to a file content.
  4264. Tools.FileAsURL = function (content) {
  4265. var fileBlob = new Blob([content]);
  4266. var url = window.URL || window.webkitURL;
  4267. var link = url.createObjectURL(fileBlob);
  4268. return link;
  4269. };
  4270. // Misc.
  4271. Tools.Clamp = function (value, min, max) {
  4272. if (min === void 0) { min = 0; }
  4273. if (max === void 0) { max = 1; }
  4274. return Math.min(max, Math.max(min, value));
  4275. };
  4276. // Returns -1 when value is a negative number and
  4277. // +1 when value is a positive number.
  4278. Tools.Sign = function (value) {
  4279. value = +value; // convert to a number
  4280. if (value === 0 || isNaN(value))
  4281. return value;
  4282. return value > 0 ? 1 : -1;
  4283. };
  4284. Tools.Format = function (value, decimals) {
  4285. if (decimals === void 0) { decimals = 2; }
  4286. return value.toFixed(decimals);
  4287. };
  4288. Tools.CheckExtends = function (v, min, max) {
  4289. if (v.x < min.x)
  4290. min.x = v.x;
  4291. if (v.y < min.y)
  4292. min.y = v.y;
  4293. if (v.z < min.z)
  4294. min.z = v.z;
  4295. if (v.x > max.x)
  4296. max.x = v.x;
  4297. if (v.y > max.y)
  4298. max.y = v.y;
  4299. if (v.z > max.z)
  4300. max.z = v.z;
  4301. };
  4302. Tools.WithinEpsilon = function (a, b, epsilon) {
  4303. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4304. var num = a - b;
  4305. return -epsilon <= num && num <= epsilon;
  4306. };
  4307. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4308. for (var prop in source) {
  4309. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4310. continue;
  4311. }
  4312. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4313. continue;
  4314. }
  4315. var sourceValue = source[prop];
  4316. var typeOfSourceValue = typeof sourceValue;
  4317. if (typeOfSourceValue === "function") {
  4318. continue;
  4319. }
  4320. if (typeOfSourceValue === "object") {
  4321. if (sourceValue instanceof Array) {
  4322. destination[prop] = [];
  4323. if (sourceValue.length > 0) {
  4324. if (typeof sourceValue[0] == "object") {
  4325. for (var index = 0; index < sourceValue.length; index++) {
  4326. var clonedValue = cloneValue(sourceValue[index], destination);
  4327. if (destination[prop].indexOf(clonedValue) === -1) {
  4328. destination[prop].push(clonedValue);
  4329. }
  4330. }
  4331. }
  4332. else {
  4333. destination[prop] = sourceValue.slice(0);
  4334. }
  4335. }
  4336. }
  4337. else {
  4338. destination[prop] = cloneValue(sourceValue, destination);
  4339. }
  4340. }
  4341. else {
  4342. destination[prop] = sourceValue;
  4343. }
  4344. }
  4345. };
  4346. Tools.IsEmpty = function (obj) {
  4347. for (var i in obj) {
  4348. return false;
  4349. }
  4350. return true;
  4351. };
  4352. Tools.RegisterTopRootEvents = function (events) {
  4353. for (var index = 0; index < events.length; index++) {
  4354. var event = events[index];
  4355. window.addEventListener(event.name, event.handler, false);
  4356. try {
  4357. if (window.parent) {
  4358. window.parent.addEventListener(event.name, event.handler, false);
  4359. }
  4360. }
  4361. catch (e) {
  4362. }
  4363. }
  4364. };
  4365. Tools.UnregisterTopRootEvents = function (events) {
  4366. for (var index = 0; index < events.length; index++) {
  4367. var event = events[index];
  4368. window.removeEventListener(event.name, event.handler);
  4369. try {
  4370. if (window.parent) {
  4371. window.parent.removeEventListener(event.name, event.handler);
  4372. }
  4373. }
  4374. catch (e) {
  4375. }
  4376. }
  4377. };
  4378. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4379. // Read the contents of the framebuffer
  4380. var numberOfChannelsByLine = width * 4;
  4381. var halfHeight = height / 2;
  4382. //Reading datas from WebGL
  4383. var data = engine.readPixels(0, 0, width, height);
  4384. //To flip image on Y axis.
  4385. for (var i = 0; i < halfHeight; i++) {
  4386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4387. var currentCell = j + i * numberOfChannelsByLine;
  4388. var targetLine = height - i - 1;
  4389. var targetCell = j + targetLine * numberOfChannelsByLine;
  4390. var temp = data[currentCell];
  4391. data[currentCell] = data[targetCell];
  4392. data[targetCell] = temp;
  4393. }
  4394. }
  4395. // Create a 2D canvas to store the result
  4396. if (!screenshotCanvas) {
  4397. screenshotCanvas = document.createElement('canvas');
  4398. }
  4399. screenshotCanvas.width = width;
  4400. screenshotCanvas.height = height;
  4401. var context = screenshotCanvas.getContext('2d');
  4402. // Copy the pixels to a 2D canvas
  4403. var imageData = context.createImageData(width, height);
  4404. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4405. var castData = imageData.data;
  4406. castData.set(data);
  4407. context.putImageData(imageData, 0, 0);
  4408. var base64Image = screenshotCanvas.toDataURL();
  4409. if (successCallback) {
  4410. successCallback(base64Image);
  4411. }
  4412. else {
  4413. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4414. if (("download" in document.createElement("a"))) {
  4415. var a = window.document.createElement("a");
  4416. a.href = base64Image;
  4417. var date = new Date();
  4418. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4419. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4420. window.document.body.appendChild(a);
  4421. a.addEventListener("click", function () {
  4422. a.parentElement.removeChild(a);
  4423. });
  4424. a.click();
  4425. }
  4426. else {
  4427. var newWindow = window.open("");
  4428. var img = newWindow.document.createElement("img");
  4429. img.src = base64Image;
  4430. newWindow.document.body.appendChild(img);
  4431. }
  4432. }
  4433. };
  4434. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4435. var width;
  4436. var height;
  4437. //If a precision value is specified
  4438. if (size.precision) {
  4439. width = Math.round(engine.getRenderWidth() * size.precision);
  4440. height = Math.round(width / engine.getAspectRatio(camera));
  4441. size = { width: width, height: height };
  4442. }
  4443. else if (size.width && size.height) {
  4444. width = size.width;
  4445. height = size.height;
  4446. }
  4447. else if (size.width && !size.height) {
  4448. width = size.width;
  4449. height = Math.round(width / engine.getAspectRatio(camera));
  4450. size = { width: width, height: height };
  4451. }
  4452. else if (size.height && !size.width) {
  4453. height = size.height;
  4454. width = Math.round(height * engine.getAspectRatio(camera));
  4455. size = { width: width, height: height };
  4456. }
  4457. else if (!isNaN(size)) {
  4458. height = size;
  4459. width = size;
  4460. }
  4461. else {
  4462. Tools.Error("Invalid 'size' parameter !");
  4463. return;
  4464. }
  4465. var scene = camera.getScene();
  4466. var previousCamera = null;
  4467. if (scene.activeCamera !== camera) {
  4468. previousCamera = scene.activeCamera;
  4469. scene.activeCamera = camera;
  4470. }
  4471. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4472. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4473. texture.renderList = scene.meshes;
  4474. texture.onAfterRender = function () {
  4475. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4476. };
  4477. scene.incrementRenderId();
  4478. texture.render(true);
  4479. texture.dispose();
  4480. if (previousCamera) {
  4481. scene.activeCamera = previousCamera;
  4482. }
  4483. camera.getProjectionMatrix(true); // Force cache refresh;
  4484. };
  4485. // XHR response validator for local file scenario
  4486. Tools.ValidateXHRData = function (xhr, dataType) {
  4487. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4488. if (dataType === void 0) { dataType = 7; }
  4489. try {
  4490. if (dataType & 1) {
  4491. if (xhr.responseText && xhr.responseText.length > 0) {
  4492. return true;
  4493. }
  4494. else if (dataType === 1) {
  4495. return false;
  4496. }
  4497. }
  4498. if (dataType & 2) {
  4499. // Check header width and height since there is no "TGA" magic number
  4500. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4501. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4502. return true;
  4503. }
  4504. else if (dataType === 2) {
  4505. return false;
  4506. }
  4507. }
  4508. if (dataType & 4) {
  4509. // Check for the "DDS" magic number
  4510. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4511. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4512. return true;
  4513. }
  4514. else {
  4515. return false;
  4516. }
  4517. }
  4518. }
  4519. catch (e) {
  4520. }
  4521. return false;
  4522. };
  4523. Object.defineProperty(Tools, "NoneLogLevel", {
  4524. get: function () {
  4525. return Tools._NoneLogLevel;
  4526. },
  4527. enumerable: true,
  4528. configurable: true
  4529. });
  4530. Object.defineProperty(Tools, "MessageLogLevel", {
  4531. get: function () {
  4532. return Tools._MessageLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "WarningLogLevel", {
  4538. get: function () {
  4539. return Tools._WarningLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Object.defineProperty(Tools, "ErrorLogLevel", {
  4545. get: function () {
  4546. return Tools._ErrorLogLevel;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(Tools, "AllLogLevel", {
  4552. get: function () {
  4553. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Tools._AddLogEntry = function (entry) {
  4559. Tools._LogCache = entry + Tools._LogCache;
  4560. if (Tools.OnNewCacheEntry) {
  4561. Tools.OnNewCacheEntry(entry);
  4562. }
  4563. };
  4564. Tools._FormatMessage = function (message) {
  4565. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4566. var date = new Date();
  4567. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4568. };
  4569. Tools._LogDisabled = function (message) {
  4570. // nothing to do
  4571. };
  4572. Tools._LogEnabled = function (message) {
  4573. var formattedMessage = Tools._FormatMessage(message);
  4574. console.log("BJS - " + formattedMessage);
  4575. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4576. Tools._AddLogEntry(entry);
  4577. };
  4578. Tools._WarnDisabled = function (message) {
  4579. // nothing to do
  4580. };
  4581. Tools._WarnEnabled = function (message) {
  4582. var formattedMessage = Tools._FormatMessage(message);
  4583. console.warn("BJS - " + formattedMessage);
  4584. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4585. Tools._AddLogEntry(entry);
  4586. };
  4587. Tools._ErrorDisabled = function (message) {
  4588. // nothing to do
  4589. };
  4590. Tools._ErrorEnabled = function (message) {
  4591. Tools.errorsCount++;
  4592. var formattedMessage = Tools._FormatMessage(message);
  4593. console.error("BJS - " + formattedMessage);
  4594. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4595. Tools._AddLogEntry(entry);
  4596. };
  4597. Object.defineProperty(Tools, "LogCache", {
  4598. get: function () {
  4599. return Tools._LogCache;
  4600. },
  4601. enumerable: true,
  4602. configurable: true
  4603. });
  4604. Tools.ClearLogCache = function () {
  4605. Tools._LogCache = "";
  4606. Tools.errorsCount = 0;
  4607. };
  4608. Object.defineProperty(Tools, "LogLevels", {
  4609. set: function (level) {
  4610. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4611. Tools.Log = Tools._LogEnabled;
  4612. }
  4613. else {
  4614. Tools.Log = Tools._LogDisabled;
  4615. }
  4616. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4617. Tools.Warn = Tools._WarnEnabled;
  4618. }
  4619. else {
  4620. Tools.Warn = Tools._WarnDisabled;
  4621. }
  4622. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4623. Tools.Error = Tools._ErrorEnabled;
  4624. }
  4625. else {
  4626. Tools.Error = Tools._ErrorDisabled;
  4627. }
  4628. },
  4629. enumerable: true,
  4630. configurable: true
  4631. });
  4632. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4633. get: function () {
  4634. return Tools._PerformanceNoneLogLevel;
  4635. },
  4636. enumerable: true,
  4637. configurable: true
  4638. });
  4639. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4640. get: function () {
  4641. return Tools._PerformanceUserMarkLogLevel;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4647. get: function () {
  4648. return Tools._PerformanceConsoleLogLevel;
  4649. },
  4650. enumerable: true,
  4651. configurable: true
  4652. });
  4653. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4654. set: function (level) {
  4655. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4656. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4657. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4658. return;
  4659. }
  4660. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4661. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4662. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4663. return;
  4664. }
  4665. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4666. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4667. },
  4668. enumerable: true,
  4669. configurable: true
  4670. });
  4671. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4672. };
  4673. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4674. };
  4675. Tools._StartUserMark = function (counterName, condition) {
  4676. if (condition === void 0) { condition = true; }
  4677. if (!condition || !Tools._performance.mark) {
  4678. return;
  4679. }
  4680. Tools._performance.mark(counterName + "-Begin");
  4681. };
  4682. Tools._EndUserMark = function (counterName, condition) {
  4683. if (condition === void 0) { condition = true; }
  4684. if (!condition || !Tools._performance.mark) {
  4685. return;
  4686. }
  4687. Tools._performance.mark(counterName + "-End");
  4688. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4689. };
  4690. Tools._StartPerformanceConsole = function (counterName, condition) {
  4691. if (condition === void 0) { condition = true; }
  4692. if (!condition) {
  4693. return;
  4694. }
  4695. Tools._StartUserMark(counterName, condition);
  4696. if (console.time) {
  4697. console.time(counterName);
  4698. }
  4699. };
  4700. Tools._EndPerformanceConsole = function (counterName, condition) {
  4701. if (condition === void 0) { condition = true; }
  4702. if (!condition) {
  4703. return;
  4704. }
  4705. Tools._EndUserMark(counterName, condition);
  4706. if (console.time) {
  4707. console.timeEnd(counterName);
  4708. }
  4709. };
  4710. Object.defineProperty(Tools, "Now", {
  4711. get: function () {
  4712. if (window.performance && window.performance.now) {
  4713. return window.performance.now();
  4714. }
  4715. return new Date().getTime();
  4716. },
  4717. enumerable: true,
  4718. configurable: true
  4719. });
  4720. Tools.BaseUrl = "";
  4721. Tools.CorsBehavior = "anonymous";
  4722. Tools.UseFallbackTexture = true;
  4723. // Logs
  4724. Tools._NoneLogLevel = 0;
  4725. Tools._MessageLogLevel = 1;
  4726. Tools._WarningLogLevel = 2;
  4727. Tools._ErrorLogLevel = 4;
  4728. Tools._LogCache = "";
  4729. Tools.errorsCount = 0;
  4730. Tools.Log = Tools._LogEnabled;
  4731. Tools.Warn = Tools._WarnEnabled;
  4732. Tools.Error = Tools._ErrorEnabled;
  4733. // Performances
  4734. Tools._PerformanceNoneLogLevel = 0;
  4735. Tools._PerformanceUserMarkLogLevel = 1;
  4736. Tools._PerformanceConsoleLogLevel = 2;
  4737. Tools._performance = window.performance;
  4738. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4739. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4740. return Tools;
  4741. })();
  4742. BABYLON.Tools = Tools;
  4743. /**
  4744. * An implementation of a loop for asynchronous functions.
  4745. */
  4746. var AsyncLoop = (function () {
  4747. /**
  4748. * Constroctor.
  4749. * @param iterations the number of iterations.
  4750. * @param _fn the function to run each iteration
  4751. * @param _successCallback the callback that will be called upon succesful execution
  4752. * @param offset starting offset.
  4753. */
  4754. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4755. if (offset === void 0) { offset = 0; }
  4756. this.iterations = iterations;
  4757. this._fn = _fn;
  4758. this._successCallback = _successCallback;
  4759. this.index = offset - 1;
  4760. this._done = false;
  4761. }
  4762. /**
  4763. * Execute the next iteration. Must be called after the last iteration was finished.
  4764. */
  4765. AsyncLoop.prototype.executeNext = function () {
  4766. if (!this._done) {
  4767. if (this.index + 1 < this.iterations) {
  4768. ++this.index;
  4769. this._fn(this);
  4770. }
  4771. else {
  4772. this.breakLoop();
  4773. }
  4774. }
  4775. };
  4776. /**
  4777. * Break the loop and run the success callback.
  4778. */
  4779. AsyncLoop.prototype.breakLoop = function () {
  4780. this._done = true;
  4781. this._successCallback();
  4782. };
  4783. /**
  4784. * Helper function
  4785. */
  4786. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4787. if (offset === void 0) { offset = 0; }
  4788. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4789. loop.executeNext();
  4790. return loop;
  4791. };
  4792. /**
  4793. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4794. * @param iterations total number of iterations
  4795. * @param syncedIterations number of synchronous iterations in each async iteration.
  4796. * @param fn the function to call each iteration.
  4797. * @param callback a success call back that will be called when iterating stops.
  4798. * @param breakFunction a break condition (optional)
  4799. * @param timeout timeout settings for the setTimeout function. default - 0.
  4800. * @constructor
  4801. */
  4802. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4803. if (timeout === void 0) { timeout = 0; }
  4804. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4805. if (breakFunction && breakFunction())
  4806. loop.breakLoop();
  4807. else {
  4808. setTimeout(function () {
  4809. for (var i = 0; i < syncedIterations; ++i) {
  4810. var iteration = (loop.index * syncedIterations) + i;
  4811. if (iteration >= iterations)
  4812. break;
  4813. fn(iteration);
  4814. if (breakFunction && breakFunction()) {
  4815. loop.breakLoop();
  4816. break;
  4817. }
  4818. }
  4819. loop.executeNext();
  4820. }, timeout);
  4821. }
  4822. }, callback);
  4823. };
  4824. return AsyncLoop;
  4825. })();
  4826. BABYLON.AsyncLoop = AsyncLoop;
  4827. })(BABYLON || (BABYLON = {}));
  4828. var BABYLON;
  4829. (function (BABYLON) {
  4830. var _DepthCullingState = (function () {
  4831. function _DepthCullingState() {
  4832. this._isDepthTestDirty = false;
  4833. this._isDepthMaskDirty = false;
  4834. this._isDepthFuncDirty = false;
  4835. this._isCullFaceDirty = false;
  4836. this._isCullDirty = false;
  4837. this._isZOffsetDirty = false;
  4838. }
  4839. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4840. get: function () {
  4841. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4842. },
  4843. enumerable: true,
  4844. configurable: true
  4845. });
  4846. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4847. get: function () {
  4848. return this._zOffset;
  4849. },
  4850. set: function (value) {
  4851. if (this._zOffset === value) {
  4852. return;
  4853. }
  4854. this._zOffset = value;
  4855. this._isZOffsetDirty = true;
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4861. get: function () {
  4862. return this._cullFace;
  4863. },
  4864. set: function (value) {
  4865. if (this._cullFace === value) {
  4866. return;
  4867. }
  4868. this._cullFace = value;
  4869. this._isCullFaceDirty = true;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4875. get: function () {
  4876. return this._cull;
  4877. },
  4878. set: function (value) {
  4879. if (this._cull === value) {
  4880. return;
  4881. }
  4882. this._cull = value;
  4883. this._isCullDirty = true;
  4884. },
  4885. enumerable: true,
  4886. configurable: true
  4887. });
  4888. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4889. get: function () {
  4890. return this._depthFunc;
  4891. },
  4892. set: function (value) {
  4893. if (this._depthFunc === value) {
  4894. return;
  4895. }
  4896. this._depthFunc = value;
  4897. this._isDepthFuncDirty = true;
  4898. },
  4899. enumerable: true,
  4900. configurable: true
  4901. });
  4902. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4903. get: function () {
  4904. return this._depthMask;
  4905. },
  4906. set: function (value) {
  4907. if (this._depthMask === value) {
  4908. return;
  4909. }
  4910. this._depthMask = value;
  4911. this._isDepthMaskDirty = true;
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4917. get: function () {
  4918. return this._depthTest;
  4919. },
  4920. set: function (value) {
  4921. if (this._depthTest === value) {
  4922. return;
  4923. }
  4924. this._depthTest = value;
  4925. this._isDepthTestDirty = true;
  4926. },
  4927. enumerable: true,
  4928. configurable: true
  4929. });
  4930. _DepthCullingState.prototype.reset = function () {
  4931. this._depthMask = true;
  4932. this._depthTest = true;
  4933. this._depthFunc = null;
  4934. this._cull = null;
  4935. this._cullFace = null;
  4936. this._zOffset = 0;
  4937. this._isDepthTestDirty = true;
  4938. this._isDepthMaskDirty = true;
  4939. this._isDepthFuncDirty = false;
  4940. this._isCullFaceDirty = false;
  4941. this._isCullDirty = false;
  4942. this._isZOffsetDirty = false;
  4943. };
  4944. _DepthCullingState.prototype.apply = function (gl) {
  4945. if (!this.isDirty) {
  4946. return;
  4947. }
  4948. // Cull
  4949. if (this._isCullDirty) {
  4950. if (this.cull) {
  4951. gl.enable(gl.CULL_FACE);
  4952. }
  4953. else {
  4954. gl.disable(gl.CULL_FACE);
  4955. }
  4956. this._isCullDirty = false;
  4957. }
  4958. // Cull face
  4959. if (this._isCullFaceDirty) {
  4960. gl.cullFace(this.cullFace);
  4961. this._isCullFaceDirty = false;
  4962. }
  4963. // Depth mask
  4964. if (this._isDepthMaskDirty) {
  4965. gl.depthMask(this.depthMask);
  4966. this._isDepthMaskDirty = false;
  4967. }
  4968. // Depth test
  4969. if (this._isDepthTestDirty) {
  4970. if (this.depthTest) {
  4971. gl.enable(gl.DEPTH_TEST);
  4972. }
  4973. else {
  4974. gl.disable(gl.DEPTH_TEST);
  4975. }
  4976. this._isDepthTestDirty = false;
  4977. }
  4978. // Depth func
  4979. if (this._isDepthFuncDirty) {
  4980. gl.depthFunc(this.depthFunc);
  4981. this._isDepthFuncDirty = false;
  4982. }
  4983. // zOffset
  4984. if (this._isZOffsetDirty) {
  4985. if (this.zOffset) {
  4986. gl.enable(gl.POLYGON_OFFSET_FILL);
  4987. gl.polygonOffset(this.zOffset, 0);
  4988. }
  4989. else {
  4990. gl.disable(gl.POLYGON_OFFSET_FILL);
  4991. }
  4992. this._isZOffsetDirty = false;
  4993. }
  4994. };
  4995. return _DepthCullingState;
  4996. })();
  4997. BABYLON._DepthCullingState = _DepthCullingState;
  4998. var _AlphaState = (function () {
  4999. function _AlphaState() {
  5000. this._isAlphaBlendDirty = false;
  5001. this._isBlendFunctionParametersDirty = false;
  5002. this._alphaBlend = false;
  5003. this._blendFunctionParameters = new Array(4);
  5004. }
  5005. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5006. get: function () {
  5007. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5008. },
  5009. enumerable: true,
  5010. configurable: true
  5011. });
  5012. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5013. get: function () {
  5014. return this._alphaBlend;
  5015. },
  5016. set: function (value) {
  5017. if (this._alphaBlend === value) {
  5018. return;
  5019. }
  5020. this._alphaBlend = value;
  5021. this._isAlphaBlendDirty = true;
  5022. },
  5023. enumerable: true,
  5024. configurable: true
  5025. });
  5026. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5027. if (this._blendFunctionParameters[0] === value0 &&
  5028. this._blendFunctionParameters[1] === value1 &&
  5029. this._blendFunctionParameters[2] === value2 &&
  5030. this._blendFunctionParameters[3] === value3) {
  5031. return;
  5032. }
  5033. this._blendFunctionParameters[0] = value0;
  5034. this._blendFunctionParameters[1] = value1;
  5035. this._blendFunctionParameters[2] = value2;
  5036. this._blendFunctionParameters[3] = value3;
  5037. this._isBlendFunctionParametersDirty = true;
  5038. };
  5039. _AlphaState.prototype.reset = function () {
  5040. this._alphaBlend = false;
  5041. this._blendFunctionParameters[0] = null;
  5042. this._blendFunctionParameters[1] = null;
  5043. this._blendFunctionParameters[2] = null;
  5044. this._blendFunctionParameters[3] = null;
  5045. this._isAlphaBlendDirty = true;
  5046. this._isBlendFunctionParametersDirty = false;
  5047. };
  5048. _AlphaState.prototype.apply = function (gl) {
  5049. if (!this.isDirty) {
  5050. return;
  5051. }
  5052. // Alpha blend
  5053. if (this._isAlphaBlendDirty) {
  5054. if (this._alphaBlend) {
  5055. gl.enable(gl.BLEND);
  5056. }
  5057. else {
  5058. gl.disable(gl.BLEND);
  5059. }
  5060. this._isAlphaBlendDirty = false;
  5061. }
  5062. // Alpha function
  5063. if (this._isBlendFunctionParametersDirty) {
  5064. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5065. this._isBlendFunctionParametersDirty = false;
  5066. }
  5067. };
  5068. return _AlphaState;
  5069. })();
  5070. BABYLON._AlphaState = _AlphaState;
  5071. var compileShader = function (gl, source, type, defines) {
  5072. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5073. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5074. gl.compileShader(shader);
  5075. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5076. throw new Error(gl.getShaderInfoLog(shader));
  5077. }
  5078. return shader;
  5079. };
  5080. var getWebGLTextureType = function (gl, type) {
  5081. var textureType = gl.UNSIGNED_BYTE;
  5082. if (type === Engine.TEXTURETYPE_FLOAT)
  5083. textureType = gl.FLOAT;
  5084. return textureType;
  5085. };
  5086. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5087. var magFilter = gl.NEAREST;
  5088. var minFilter = gl.NEAREST;
  5089. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5090. magFilter = gl.LINEAR;
  5091. if (generateMipMaps) {
  5092. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5093. }
  5094. else {
  5095. minFilter = gl.LINEAR;
  5096. }
  5097. }
  5098. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5099. magFilter = gl.LINEAR;
  5100. if (generateMipMaps) {
  5101. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5102. }
  5103. else {
  5104. minFilter = gl.LINEAR;
  5105. }
  5106. }
  5107. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5108. magFilter = gl.NEAREST;
  5109. if (generateMipMaps) {
  5110. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5111. }
  5112. else {
  5113. minFilter = gl.NEAREST;
  5114. }
  5115. }
  5116. return {
  5117. min: minFilter,
  5118. mag: magFilter
  5119. };
  5120. };
  5121. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5123. var engine = scene.getEngine();
  5124. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5125. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5126. gl.bindTexture(gl.TEXTURE_2D, texture);
  5127. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5128. texture._baseWidth = width;
  5129. texture._baseHeight = height;
  5130. texture._width = potWidth;
  5131. texture._height = potHeight;
  5132. texture.isReady = true;
  5133. processFunction(potWidth, potHeight);
  5134. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5137. if (!noMipmap && !isCompressed) {
  5138. gl.generateMipmap(gl.TEXTURE_2D);
  5139. }
  5140. gl.bindTexture(gl.TEXTURE_2D, null);
  5141. engine.resetTextureCache();
  5142. scene._removePendingData(texture);
  5143. if (onLoad) {
  5144. onLoad();
  5145. }
  5146. };
  5147. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5148. var img;
  5149. var onload = function () {
  5150. loadedImages[index] = img;
  5151. loadedImages._internalCount++;
  5152. scene._removePendingData(img);
  5153. if (loadedImages._internalCount === 6) {
  5154. onfinish(loadedImages);
  5155. }
  5156. };
  5157. var onerror = function () {
  5158. scene._removePendingData(img);
  5159. };
  5160. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5161. scene._addPendingData(img);
  5162. };
  5163. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5164. var loadedImages = [];
  5165. loadedImages._internalCount = 0;
  5166. for (var index = 0; index < 6; index++) {
  5167. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5168. }
  5169. };
  5170. var EngineCapabilities = (function () {
  5171. function EngineCapabilities() {
  5172. }
  5173. return EngineCapabilities;
  5174. })();
  5175. BABYLON.EngineCapabilities = EngineCapabilities;
  5176. /**
  5177. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5178. */
  5179. var Engine = (function () {
  5180. /**
  5181. * @constructor
  5182. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5183. * @param {boolean} [antialias] - enable antialias
  5184. * @param options - further options to be sent to the getContext function
  5185. */
  5186. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5187. var _this = this;
  5188. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5189. // Public members
  5190. this.isFullscreen = false;
  5191. this.isPointerLock = false;
  5192. this.cullBackFaces = true;
  5193. this.renderEvenInBackground = true;
  5194. // To enable/disable IDB support and avoid XHR on .manifest
  5195. this.enableOfflineSupport = true;
  5196. this.scenes = new Array();
  5197. this._windowIsBackground = false;
  5198. this._webGLVersion = "1.0";
  5199. this._drawCalls = 0;
  5200. this._renderingQueueLaunched = false;
  5201. this._activeRenderLoops = [];
  5202. // FPS
  5203. this.fpsRange = 60;
  5204. this.previousFramesDuration = [];
  5205. this.fps = 60;
  5206. this.deltaTime = 0;
  5207. // States
  5208. this._depthCullingState = new _DepthCullingState();
  5209. this._alphaState = new _AlphaState();
  5210. this._alphaMode = Engine.ALPHA_DISABLE;
  5211. // Cache
  5212. this._loadedTexturesCache = new Array();
  5213. this._maxTextureChannels = 16;
  5214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5215. this._compiledEffects = {};
  5216. this._uintIndicesCurrentlySet = false;
  5217. this._renderingCanvas = canvas;
  5218. options = options || {};
  5219. options.antialias = antialias;
  5220. if (options.preserveDrawingBuffer === undefined) {
  5221. options.preserveDrawingBuffer = false;
  5222. }
  5223. // GL
  5224. try {
  5225. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5226. if (this._gl) {
  5227. this._webGLVersion = "2.0";
  5228. }
  5229. }
  5230. catch (e) {
  5231. }
  5232. if (!this._gl) {
  5233. try {
  5234. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5235. }
  5236. catch (e) {
  5237. throw new Error("WebGL not supported");
  5238. }
  5239. }
  5240. if (!this._gl) {
  5241. throw new Error("WebGL not supported");
  5242. }
  5243. this._onBlur = function () {
  5244. _this._windowIsBackground = true;
  5245. };
  5246. this._onFocus = function () {
  5247. _this._windowIsBackground = false;
  5248. };
  5249. window.addEventListener("blur", this._onBlur);
  5250. window.addEventListener("focus", this._onFocus);
  5251. // Viewport
  5252. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5253. this.resize();
  5254. // Caps
  5255. this._caps = new EngineCapabilities();
  5256. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5257. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5258. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5259. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5260. // Infos
  5261. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5262. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5263. if (rendererInfo != null) {
  5264. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5265. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5266. }
  5267. if (!this._glVendor) {
  5268. this._glVendor = "Unknown vendor";
  5269. }
  5270. if (!this._glRenderer) {
  5271. this._glRenderer = "Unknown renderer";
  5272. }
  5273. // Extensions
  5274. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5275. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5276. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5277. 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');
  5278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5279. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5280. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5281. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5282. this._caps.highPrecisionShaderSupported = true;
  5283. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5284. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5285. if (this._gl.getShaderPrecisionFormat) {
  5286. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5287. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5288. }
  5289. // Depth buffer
  5290. this.setDepthBuffer(true);
  5291. this.setDepthFunctionToLessOrEqual();
  5292. this.setDepthWrite(true);
  5293. // Fullscreen
  5294. this._onFullscreenChange = function () {
  5295. if (document.fullscreen !== undefined) {
  5296. _this.isFullscreen = document.fullscreen;
  5297. }
  5298. else if (document.mozFullScreen !== undefined) {
  5299. _this.isFullscreen = document.mozFullScreen;
  5300. }
  5301. else if (document.webkitIsFullScreen !== undefined) {
  5302. _this.isFullscreen = document.webkitIsFullScreen;
  5303. }
  5304. else if (document.msIsFullScreen !== undefined) {
  5305. _this.isFullscreen = document.msIsFullScreen;
  5306. }
  5307. // Pointer lock
  5308. if (_this.isFullscreen && _this._pointerLockRequested) {
  5309. canvas.requestPointerLock = canvas.requestPointerLock ||
  5310. canvas.msRequestPointerLock ||
  5311. canvas.mozRequestPointerLock ||
  5312. canvas.webkitRequestPointerLock;
  5313. if (canvas.requestPointerLock) {
  5314. canvas.requestPointerLock();
  5315. }
  5316. }
  5317. };
  5318. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5319. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5320. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5321. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5322. // Pointer lock
  5323. this._onPointerLockChange = function () {
  5324. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5325. document.webkitPointerLockElement === canvas ||
  5326. document.msPointerLockElement === canvas ||
  5327. document.pointerLockElement === canvas);
  5328. };
  5329. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5330. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5331. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5332. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5333. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5334. Engine.audioEngine = new BABYLON.AudioEngine();
  5335. }
  5336. //default loading screen
  5337. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5338. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5339. }
  5340. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5341. get: function () {
  5342. return Engine._ALPHA_DISABLE;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5348. get: function () {
  5349. return Engine._ALPHA_ONEONE;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Engine, "ALPHA_ADD", {
  5355. get: function () {
  5356. return Engine._ALPHA_ADD;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5362. get: function () {
  5363. return Engine._ALPHA_COMBINE;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5369. get: function () {
  5370. return Engine._ALPHA_SUBTRACT;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5376. get: function () {
  5377. return Engine._ALPHA_MULTIPLY;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5383. get: function () {
  5384. return Engine._ALPHA_MAXIMIZED;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5390. get: function () {
  5391. return Engine._DELAYLOADSTATE_NONE;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5397. get: function () {
  5398. return Engine._DELAYLOADSTATE_LOADED;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5404. get: function () {
  5405. return Engine._DELAYLOADSTATE_LOADING;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5411. get: function () {
  5412. return Engine._DELAYLOADSTATE_NOTLOADED;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5418. get: function () {
  5419. return Engine._TEXTUREFORMAT_ALPHA;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5425. get: function () {
  5426. return Engine._TEXTUREFORMAT_LUMINANCE;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5432. get: function () {
  5433. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5439. get: function () {
  5440. return Engine._TEXTUREFORMAT_RGB;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5446. get: function () {
  5447. return Engine._TEXTUREFORMAT_RGBA;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5453. get: function () {
  5454. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5460. get: function () {
  5461. return Engine._TEXTURETYPE_FLOAT;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "Version", {
  5467. get: function () {
  5468. return "2.4.0-alpha";
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5474. get: function () {
  5475. return this._webGLVersion;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Engine.prototype._prepareWorkingCanvas = function () {
  5481. if (this._workingCanvas) {
  5482. return;
  5483. }
  5484. this._workingCanvas = document.createElement("canvas");
  5485. this._workingContext = this._workingCanvas.getContext("2d");
  5486. };
  5487. Engine.prototype.resetTextureCache = function () {
  5488. for (var index = 0; index < this._maxTextureChannels; index++) {
  5489. this._activeTexturesCache[index] = null;
  5490. }
  5491. };
  5492. Engine.prototype.getGlInfo = function () {
  5493. return {
  5494. vendor: this._glVendor,
  5495. renderer: this._glRenderer,
  5496. version: this._glVersion
  5497. };
  5498. };
  5499. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5500. if (useScreen === void 0) { useScreen = false; }
  5501. var viewport = camera.viewport;
  5502. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5503. };
  5504. Engine.prototype.getRenderWidth = function (useScreen) {
  5505. if (useScreen === void 0) { useScreen = false; }
  5506. if (!useScreen && this._currentRenderTarget) {
  5507. return this._currentRenderTarget._width;
  5508. }
  5509. return this._renderingCanvas.width;
  5510. };
  5511. Engine.prototype.getRenderHeight = function (useScreen) {
  5512. if (useScreen === void 0) { useScreen = false; }
  5513. if (!useScreen && this._currentRenderTarget) {
  5514. return this._currentRenderTarget._height;
  5515. }
  5516. return this._renderingCanvas.height;
  5517. };
  5518. Engine.prototype.getRenderingCanvas = function () {
  5519. return this._renderingCanvas;
  5520. };
  5521. Engine.prototype.getRenderingCanvasClientRect = function () {
  5522. return this._renderingCanvas.getBoundingClientRect();
  5523. };
  5524. Engine.prototype.setHardwareScalingLevel = function (level) {
  5525. this._hardwareScalingLevel = level;
  5526. this.resize();
  5527. };
  5528. Engine.prototype.getHardwareScalingLevel = function () {
  5529. return this._hardwareScalingLevel;
  5530. };
  5531. Engine.prototype.getLoadedTexturesCache = function () {
  5532. return this._loadedTexturesCache;
  5533. };
  5534. Engine.prototype.getCaps = function () {
  5535. return this._caps;
  5536. };
  5537. Object.defineProperty(Engine.prototype, "drawCalls", {
  5538. get: function () {
  5539. return this._drawCalls;
  5540. },
  5541. enumerable: true,
  5542. configurable: true
  5543. });
  5544. // Methods
  5545. Engine.prototype.resetDrawCalls = function () {
  5546. this._drawCalls = 0;
  5547. };
  5548. Engine.prototype.setDepthFunctionToGreater = function () {
  5549. this._depthCullingState.depthFunc = this._gl.GREATER;
  5550. };
  5551. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5552. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5553. };
  5554. Engine.prototype.setDepthFunctionToLess = function () {
  5555. this._depthCullingState.depthFunc = this._gl.LESS;
  5556. };
  5557. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5558. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5559. };
  5560. /**
  5561. * stop executing a render loop function and remove it from the execution array
  5562. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5563. */
  5564. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5565. if (!renderFunction) {
  5566. this._activeRenderLoops = [];
  5567. return;
  5568. }
  5569. var index = this._activeRenderLoops.indexOf(renderFunction);
  5570. if (index >= 0) {
  5571. this._activeRenderLoops.splice(index, 1);
  5572. }
  5573. };
  5574. Engine.prototype._renderLoop = function () {
  5575. var shouldRender = true;
  5576. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5577. shouldRender = false;
  5578. }
  5579. if (shouldRender) {
  5580. // Start new frame
  5581. this.beginFrame();
  5582. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5583. var renderFunction = this._activeRenderLoops[index];
  5584. renderFunction();
  5585. }
  5586. // Present
  5587. this.endFrame();
  5588. }
  5589. if (this._activeRenderLoops.length > 0) {
  5590. // Register new frame
  5591. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5592. }
  5593. else {
  5594. this._renderingQueueLaunched = false;
  5595. }
  5596. };
  5597. /**
  5598. * Register and execute a render loop. The engine can have more than one render function.
  5599. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5600. * @example
  5601. * engine.runRenderLoop(function () {
  5602. * scene.render()
  5603. * })
  5604. */
  5605. Engine.prototype.runRenderLoop = function (renderFunction) {
  5606. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5607. return;
  5608. }
  5609. this._activeRenderLoops.push(renderFunction);
  5610. if (!this._renderingQueueLaunched) {
  5611. this._renderingQueueLaunched = true;
  5612. this._bindedRenderFunction = this._renderLoop.bind(this);
  5613. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5614. }
  5615. };
  5616. /**
  5617. * Toggle full screen mode.
  5618. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5619. */
  5620. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5621. if (this.isFullscreen) {
  5622. BABYLON.Tools.ExitFullscreen();
  5623. }
  5624. else {
  5625. this._pointerLockRequested = requestPointerLock;
  5626. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5627. }
  5628. };
  5629. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5630. this.applyStates();
  5631. if (backBuffer) {
  5632. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5633. }
  5634. if (depthStencil && this._depthCullingState.depthMask) {
  5635. this._gl.clearDepth(1.0);
  5636. }
  5637. var mode = 0;
  5638. if (backBuffer) {
  5639. mode |= this._gl.COLOR_BUFFER_BIT;
  5640. }
  5641. if (depthStencil && this._depthCullingState.depthMask) {
  5642. mode |= this._gl.DEPTH_BUFFER_BIT;
  5643. }
  5644. this._gl.clear(mode);
  5645. };
  5646. /**
  5647. * Set the WebGL's viewport
  5648. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5649. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5650. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5651. */
  5652. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5653. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5654. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5655. var x = viewport.x || 0;
  5656. var y = viewport.y || 0;
  5657. this._cachedViewport = viewport;
  5658. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5659. };
  5660. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5661. this._cachedViewport = null;
  5662. this._gl.viewport(x, y, width, height);
  5663. };
  5664. Engine.prototype.beginFrame = function () {
  5665. this._measureFps();
  5666. };
  5667. Engine.prototype.endFrame = function () {
  5668. //this.flushFramebuffer();
  5669. };
  5670. /**
  5671. * resize the view according to the canvas' size.
  5672. * @example
  5673. * window.addEventListener("resize", function () {
  5674. * engine.resize();
  5675. * });
  5676. */
  5677. Engine.prototype.resize = function () {
  5678. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5679. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5680. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5681. for (var index = 0; index < this.scenes.length; index++) {
  5682. var scene = this.scenes[index];
  5683. if (scene.debugLayer.isVisible()) {
  5684. scene.debugLayer._syncPositions();
  5685. }
  5686. }
  5687. };
  5688. /**
  5689. * force a specific size of the canvas
  5690. * @param {number} width - the new canvas' width
  5691. * @param {number} height - the new canvas' height
  5692. */
  5693. Engine.prototype.setSize = function (width, height) {
  5694. this._renderingCanvas.width = width;
  5695. this._renderingCanvas.height = height;
  5696. for (var index = 0; index < this.scenes.length; index++) {
  5697. var scene = this.scenes[index];
  5698. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5699. var cam = scene.cameras[camIndex];
  5700. cam._currentRenderId = 0;
  5701. }
  5702. }
  5703. };
  5704. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5705. this._currentRenderTarget = texture;
  5706. var gl = this._gl;
  5707. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5708. if (texture.isCube) {
  5709. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5710. }
  5711. else {
  5712. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5713. }
  5714. this._gl.viewport(0, 0, texture._width, texture._height);
  5715. this.wipeCaches();
  5716. };
  5717. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5718. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5719. this._currentRenderTarget = null;
  5720. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5721. var gl = this._gl;
  5722. gl.bindTexture(gl.TEXTURE_2D, texture);
  5723. gl.generateMipmap(gl.TEXTURE_2D);
  5724. gl.bindTexture(gl.TEXTURE_2D, null);
  5725. }
  5726. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5727. };
  5728. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5729. if (texture.generateMipMaps) {
  5730. var gl = this._gl;
  5731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5732. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5733. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5734. }
  5735. };
  5736. Engine.prototype.flushFramebuffer = function () {
  5737. this._gl.flush();
  5738. };
  5739. Engine.prototype.restoreDefaultFramebuffer = function () {
  5740. this._currentRenderTarget = null;
  5741. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5742. this.setViewport(this._cachedViewport);
  5743. this.wipeCaches();
  5744. };
  5745. // VBOs
  5746. Engine.prototype._resetVertexBufferBinding = function () {
  5747. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5748. this._cachedVertexBuffers = null;
  5749. };
  5750. Engine.prototype.createVertexBuffer = function (vertices) {
  5751. var vbo = this._gl.createBuffer();
  5752. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5753. if (vertices instanceof Float32Array) {
  5754. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5755. }
  5756. else {
  5757. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5758. }
  5759. this._resetVertexBufferBinding();
  5760. vbo.references = 1;
  5761. return vbo;
  5762. };
  5763. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5764. var vbo = this._gl.createBuffer();
  5765. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5766. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5767. this._resetVertexBufferBinding();
  5768. vbo.references = 1;
  5769. return vbo;
  5770. };
  5771. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5772. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5773. if (offset === undefined) {
  5774. offset = 0;
  5775. }
  5776. if (vertices instanceof Float32Array) {
  5777. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5778. }
  5779. else {
  5780. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5781. }
  5782. this._resetVertexBufferBinding();
  5783. };
  5784. Engine.prototype._resetIndexBufferBinding = function () {
  5785. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5786. this._cachedIndexBuffer = null;
  5787. };
  5788. Engine.prototype.createIndexBuffer = function (indices) {
  5789. var vbo = this._gl.createBuffer();
  5790. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5791. // Check for 32 bits indices
  5792. var arrayBuffer;
  5793. var need32Bits = false;
  5794. if (this._caps.uintIndices) {
  5795. for (var index = 0; index < indices.length; index++) {
  5796. if (indices[index] > 65535) {
  5797. need32Bits = true;
  5798. break;
  5799. }
  5800. }
  5801. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5802. }
  5803. else {
  5804. arrayBuffer = new Uint16Array(indices);
  5805. }
  5806. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5807. this._resetIndexBufferBinding();
  5808. vbo.references = 1;
  5809. vbo.is32Bits = need32Bits;
  5810. return vbo;
  5811. };
  5812. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5813. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5814. this._cachedVertexBuffers = vertexBuffer;
  5815. this._cachedEffectForVertexBuffers = effect;
  5816. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5817. var offset = 0;
  5818. for (var index = 0; index < vertexDeclaration.length; index++) {
  5819. var order = effect.getAttributeLocation(index);
  5820. if (order >= 0) {
  5821. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5822. }
  5823. offset += vertexDeclaration[index] * 4;
  5824. }
  5825. }
  5826. if (this._cachedIndexBuffer !== indexBuffer) {
  5827. this._cachedIndexBuffer = indexBuffer;
  5828. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5829. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5830. }
  5831. };
  5832. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5833. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5834. this._cachedVertexBuffers = vertexBuffers;
  5835. this._cachedEffectForVertexBuffers = effect;
  5836. var attributes = effect.getAttributesNames();
  5837. for (var index = 0; index < attributes.length; index++) {
  5838. var order = effect.getAttributeLocation(index);
  5839. if (order >= 0) {
  5840. var vertexBuffer = vertexBuffers[attributes[index]];
  5841. if (!vertexBuffer) {
  5842. continue;
  5843. }
  5844. var stride = vertexBuffer.getStrideSize();
  5845. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5846. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5847. }
  5848. }
  5849. }
  5850. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5851. this._cachedIndexBuffer = indexBuffer;
  5852. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5853. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5854. }
  5855. };
  5856. Engine.prototype._releaseBuffer = function (buffer) {
  5857. buffer.references--;
  5858. if (buffer.references === 0) {
  5859. this._gl.deleteBuffer(buffer);
  5860. return true;
  5861. }
  5862. return false;
  5863. };
  5864. Engine.prototype.createInstancesBuffer = function (capacity) {
  5865. var buffer = this._gl.createBuffer();
  5866. buffer.capacity = capacity;
  5867. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5868. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5869. return buffer;
  5870. };
  5871. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5872. this._gl.deleteBuffer(buffer);
  5873. };
  5874. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5875. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5876. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5877. for (var index = 0; index < 4; index++) {
  5878. var offsetLocation = offsetLocations[index];
  5879. this._gl.enableVertexAttribArray(offsetLocation);
  5880. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5881. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5882. }
  5883. };
  5884. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5885. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5886. for (var index = 0; index < 4; index++) {
  5887. var offsetLocation = offsetLocations[index];
  5888. this._gl.disableVertexAttribArray(offsetLocation);
  5889. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5890. }
  5891. };
  5892. Engine.prototype.applyStates = function () {
  5893. this._depthCullingState.apply(this._gl);
  5894. this._alphaState.apply(this._gl);
  5895. };
  5896. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5897. // Apply states
  5898. this.applyStates();
  5899. this._drawCalls++;
  5900. // Render
  5901. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5902. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5903. if (instancesCount) {
  5904. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5905. return;
  5906. }
  5907. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5908. };
  5909. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5910. // Apply states
  5911. this.applyStates();
  5912. this._drawCalls++;
  5913. if (instancesCount) {
  5914. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5915. return;
  5916. }
  5917. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5918. };
  5919. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5920. // Apply states
  5921. this.applyStates();
  5922. this._drawCalls++;
  5923. if (instancesCount) {
  5924. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5925. return;
  5926. }
  5927. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5928. };
  5929. // Shaders
  5930. Engine.prototype._releaseEffect = function (effect) {
  5931. if (this._compiledEffects[effect._key]) {
  5932. delete this._compiledEffects[effect._key];
  5933. if (effect.getProgram()) {
  5934. this._gl.deleteProgram(effect.getProgram());
  5935. }
  5936. }
  5937. };
  5938. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5939. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5940. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5941. var name = vertex + "+" + fragment + "@" + defines;
  5942. if (this._compiledEffects[name]) {
  5943. return this._compiledEffects[name];
  5944. }
  5945. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5946. effect._key = name;
  5947. this._compiledEffects[name] = effect;
  5948. return effect;
  5949. };
  5950. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5951. if (uniformsNames === void 0) { uniformsNames = []; }
  5952. if (samplers === void 0) { samplers = []; }
  5953. if (defines === void 0) { defines = ""; }
  5954. return this.createEffect({
  5955. vertex: "particles",
  5956. fragmentElement: fragmentName
  5957. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5958. };
  5959. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5960. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5961. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5962. var shaderProgram = this._gl.createProgram();
  5963. this._gl.attachShader(shaderProgram, vertexShader);
  5964. this._gl.attachShader(shaderProgram, fragmentShader);
  5965. this._gl.linkProgram(shaderProgram);
  5966. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5967. if (!linked) {
  5968. var error = this._gl.getProgramInfoLog(shaderProgram);
  5969. if (error) {
  5970. throw new Error(error);
  5971. }
  5972. }
  5973. this._gl.deleteShader(vertexShader);
  5974. this._gl.deleteShader(fragmentShader);
  5975. return shaderProgram;
  5976. };
  5977. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5978. var results = [];
  5979. for (var index = 0; index < uniformsNames.length; index++) {
  5980. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5981. }
  5982. return results;
  5983. };
  5984. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5985. var results = [];
  5986. for (var index = 0; index < attributesNames.length; index++) {
  5987. try {
  5988. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5989. }
  5990. catch (e) {
  5991. results.push(-1);
  5992. }
  5993. }
  5994. return results;
  5995. };
  5996. Engine.prototype.enableEffect = function (effect) {
  5997. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5998. if (effect && effect.onBind) {
  5999. effect.onBind(effect);
  6000. }
  6001. return;
  6002. }
  6003. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6004. // Use program
  6005. this._gl.useProgram(effect.getProgram());
  6006. for (var i in this._vertexAttribArrays) {
  6007. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6008. continue;
  6009. }
  6010. this._vertexAttribArrays[i] = false;
  6011. this._gl.disableVertexAttribArray(i);
  6012. }
  6013. var attributesCount = effect.getAttributesCount();
  6014. for (var index = 0; index < attributesCount; index++) {
  6015. // Attributes
  6016. var order = effect.getAttributeLocation(index);
  6017. if (order >= 0) {
  6018. this._vertexAttribArrays[order] = true;
  6019. this._gl.enableVertexAttribArray(order);
  6020. }
  6021. }
  6022. this._currentEffect = effect;
  6023. if (effect.onBind) {
  6024. effect.onBind(effect);
  6025. }
  6026. };
  6027. Engine.prototype.setArray = function (uniform, array) {
  6028. if (!uniform)
  6029. return;
  6030. this._gl.uniform1fv(uniform, array);
  6031. };
  6032. Engine.prototype.setArray2 = function (uniform, array) {
  6033. if (!uniform || array.length % 2 !== 0)
  6034. return;
  6035. this._gl.uniform2fv(uniform, array);
  6036. };
  6037. Engine.prototype.setArray3 = function (uniform, array) {
  6038. if (!uniform || array.length % 3 !== 0)
  6039. return;
  6040. this._gl.uniform3fv(uniform, array);
  6041. };
  6042. Engine.prototype.setArray4 = function (uniform, array) {
  6043. if (!uniform || array.length % 4 !== 0)
  6044. return;
  6045. this._gl.uniform4fv(uniform, array);
  6046. };
  6047. Engine.prototype.setMatrices = function (uniform, matrices) {
  6048. if (!uniform)
  6049. return;
  6050. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6051. };
  6052. Engine.prototype.setMatrix = function (uniform, matrix) {
  6053. if (!uniform)
  6054. return;
  6055. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6056. };
  6057. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6058. if (!uniform)
  6059. return;
  6060. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6061. };
  6062. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6063. if (!uniform)
  6064. return;
  6065. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6066. };
  6067. Engine.prototype.setFloat = function (uniform, value) {
  6068. if (!uniform)
  6069. return;
  6070. this._gl.uniform1f(uniform, value);
  6071. };
  6072. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6073. if (!uniform)
  6074. return;
  6075. this._gl.uniform2f(uniform, x, y);
  6076. };
  6077. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6078. if (!uniform)
  6079. return;
  6080. this._gl.uniform3f(uniform, x, y, z);
  6081. };
  6082. Engine.prototype.setBool = function (uniform, bool) {
  6083. if (!uniform)
  6084. return;
  6085. this._gl.uniform1i(uniform, bool);
  6086. };
  6087. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6088. if (!uniform)
  6089. return;
  6090. this._gl.uniform4f(uniform, x, y, z, w);
  6091. };
  6092. Engine.prototype.setColor3 = function (uniform, color3) {
  6093. if (!uniform)
  6094. return;
  6095. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6096. };
  6097. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6098. if (!uniform)
  6099. return;
  6100. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6101. };
  6102. // States
  6103. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6104. if (zOffset === void 0) { zOffset = 0; }
  6105. if (reverseSide === void 0) { reverseSide = false; }
  6106. // Culling
  6107. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6108. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6109. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6110. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6111. if (culling) {
  6112. this._depthCullingState.cullFace = cullFace;
  6113. this._depthCullingState.cull = true;
  6114. }
  6115. else {
  6116. this._depthCullingState.cull = false;
  6117. }
  6118. }
  6119. // Z offset
  6120. this._depthCullingState.zOffset = zOffset;
  6121. };
  6122. Engine.prototype.setDepthBuffer = function (enable) {
  6123. this._depthCullingState.depthTest = enable;
  6124. };
  6125. Engine.prototype.getDepthWrite = function () {
  6126. return this._depthCullingState.depthMask;
  6127. };
  6128. Engine.prototype.setDepthWrite = function (enable) {
  6129. this._depthCullingState.depthMask = enable;
  6130. };
  6131. Engine.prototype.setColorWrite = function (enable) {
  6132. this._gl.colorMask(enable, enable, enable, enable);
  6133. };
  6134. Engine.prototype.setAlphaMode = function (mode) {
  6135. if (this._alphaMode === mode) {
  6136. return;
  6137. }
  6138. switch (mode) {
  6139. case Engine.ALPHA_DISABLE:
  6140. this.setDepthWrite(true);
  6141. this._alphaState.alphaBlend = false;
  6142. break;
  6143. case Engine.ALPHA_COMBINE:
  6144. this.setDepthWrite(false);
  6145. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6146. this._alphaState.alphaBlend = true;
  6147. break;
  6148. case Engine.ALPHA_ONEONE:
  6149. this.setDepthWrite(false);
  6150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6151. this._alphaState.alphaBlend = true;
  6152. break;
  6153. case Engine.ALPHA_ADD:
  6154. this.setDepthWrite(false);
  6155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6156. this._alphaState.alphaBlend = true;
  6157. break;
  6158. case Engine.ALPHA_SUBTRACT:
  6159. this.setDepthWrite(false);
  6160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6161. this._alphaState.alphaBlend = true;
  6162. break;
  6163. case Engine.ALPHA_MULTIPLY:
  6164. this.setDepthWrite(false);
  6165. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6166. this._alphaState.alphaBlend = true;
  6167. break;
  6168. case Engine.ALPHA_MAXIMIZED:
  6169. this.setDepthWrite(false);
  6170. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6171. this._alphaState.alphaBlend = true;
  6172. break;
  6173. }
  6174. this._alphaMode = mode;
  6175. };
  6176. Engine.prototype.getAlphaMode = function () {
  6177. return this._alphaMode;
  6178. };
  6179. Engine.prototype.setAlphaTesting = function (enable) {
  6180. this._alphaTest = enable;
  6181. };
  6182. Engine.prototype.getAlphaTesting = function () {
  6183. return this._alphaTest;
  6184. };
  6185. // Textures
  6186. Engine.prototype.wipeCaches = function () {
  6187. this.resetTextureCache();
  6188. this._currentEffect = null;
  6189. this._depthCullingState.reset();
  6190. this._alphaState.reset();
  6191. this._cachedVertexBuffers = null;
  6192. this._cachedIndexBuffer = null;
  6193. this._cachedEffectForVertexBuffers = null;
  6194. };
  6195. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6196. var gl = this._gl;
  6197. gl.bindTexture(gl.TEXTURE_2D, texture);
  6198. var magFilter = gl.NEAREST;
  6199. var minFilter = gl.NEAREST;
  6200. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6201. magFilter = gl.LINEAR;
  6202. minFilter = gl.LINEAR;
  6203. }
  6204. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6205. magFilter = gl.LINEAR;
  6206. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6207. }
  6208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6210. gl.bindTexture(gl.TEXTURE_2D, null);
  6211. texture.samplingMode = samplingMode;
  6212. };
  6213. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6214. var _this = this;
  6215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6216. if (onLoad === void 0) { onLoad = null; }
  6217. if (onError === void 0) { onError = null; }
  6218. if (buffer === void 0) { buffer = null; }
  6219. var texture = this._gl.createTexture();
  6220. var extension;
  6221. var fromData = false;
  6222. if (url.substr(0, 5) === "data:") {
  6223. fromData = true;
  6224. }
  6225. if (!fromData)
  6226. extension = url.substr(url.length - 4, 4).toLowerCase();
  6227. else {
  6228. var oldUrl = url;
  6229. fromData = oldUrl.split(':');
  6230. url = oldUrl;
  6231. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6232. }
  6233. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6234. var isTGA = (extension === ".tga");
  6235. scene._addPendingData(texture);
  6236. texture.url = url;
  6237. texture.noMipmap = noMipmap;
  6238. texture.references = 1;
  6239. texture.samplingMode = samplingMode;
  6240. this._loadedTexturesCache.push(texture);
  6241. var onerror = function () {
  6242. scene._removePendingData(texture);
  6243. if (onError) {
  6244. onError();
  6245. }
  6246. };
  6247. var callback;
  6248. if (isTGA) {
  6249. callback = function (arrayBuffer) {
  6250. var data = new Uint8Array(arrayBuffer);
  6251. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6252. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6253. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6254. }, onLoad, samplingMode);
  6255. };
  6256. if (!(fromData instanceof Array))
  6257. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6258. callback(arrayBuffer);
  6259. }, onerror, scene.database, true);
  6260. else
  6261. callback(buffer);
  6262. }
  6263. else if (isDDS) {
  6264. callback = function (data) {
  6265. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6266. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6267. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6268. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6269. }, onLoad, samplingMode);
  6270. };
  6271. if (!(fromData instanceof Array))
  6272. BABYLON.Tools.LoadFile(url, function (data) {
  6273. callback(data);
  6274. }, onerror, scene.database, true);
  6275. else
  6276. callback(buffer);
  6277. }
  6278. else {
  6279. var onload = function (img) {
  6280. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6281. var isPot = (img.width === potWidth && img.height === potHeight);
  6282. if (!isPot) {
  6283. _this._prepareWorkingCanvas();
  6284. _this._workingCanvas.width = potWidth;
  6285. _this._workingCanvas.height = potHeight;
  6286. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6287. _this._workingContext.imageSmoothingEnabled = false;
  6288. _this._workingContext.mozImageSmoothingEnabled = false;
  6289. _this._workingContext.oImageSmoothingEnabled = false;
  6290. _this._workingContext.webkitImageSmoothingEnabled = false;
  6291. _this._workingContext.msImageSmoothingEnabled = false;
  6292. }
  6293. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6294. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6295. _this._workingContext.imageSmoothingEnabled = true;
  6296. _this._workingContext.mozImageSmoothingEnabled = true;
  6297. _this._workingContext.oImageSmoothingEnabled = true;
  6298. _this._workingContext.webkitImageSmoothingEnabled = true;
  6299. _this._workingContext.msImageSmoothingEnabled = true;
  6300. }
  6301. }
  6302. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6303. }, onLoad, samplingMode);
  6304. };
  6305. if (!(fromData instanceof Array))
  6306. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6307. else
  6308. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6309. }
  6310. return texture;
  6311. };
  6312. Engine.prototype._getInternalFormat = function (format) {
  6313. var internalFormat = this._gl.RGBA;
  6314. switch (format) {
  6315. case Engine.TEXTUREFORMAT_ALPHA:
  6316. internalFormat = this._gl.ALPHA;
  6317. break;
  6318. case Engine.TEXTUREFORMAT_LUMINANCE:
  6319. internalFormat = this._gl.LUMINANCE;
  6320. break;
  6321. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6322. internalFormat = this._gl.LUMINANCE_ALPHA;
  6323. break;
  6324. case Engine.TEXTUREFORMAT_RGB:
  6325. internalFormat = this._gl.RGB;
  6326. break;
  6327. case Engine.TEXTUREFORMAT_RGBA:
  6328. internalFormat = this._gl.RGBA;
  6329. break;
  6330. }
  6331. return internalFormat;
  6332. };
  6333. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6334. if (compression === void 0) { compression = null; }
  6335. var internalFormat = this._getInternalFormat(format);
  6336. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6337. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6338. if (compression) {
  6339. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6340. }
  6341. else {
  6342. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6343. }
  6344. if (texture.generateMipMaps) {
  6345. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6346. }
  6347. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6348. this.resetTextureCache();
  6349. texture.isReady = true;
  6350. };
  6351. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6352. if (compression === void 0) { compression = null; }
  6353. var texture = this._gl.createTexture();
  6354. texture._baseWidth = width;
  6355. texture._baseHeight = height;
  6356. texture._width = width;
  6357. texture._height = height;
  6358. texture.references = 1;
  6359. this.updateRawTexture(texture, data, format, invertY, compression);
  6360. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6361. // Filters
  6362. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6363. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6364. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6365. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6366. texture.samplingMode = samplingMode;
  6367. this._loadedTexturesCache.push(texture);
  6368. return texture;
  6369. };
  6370. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6371. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6372. var texture = this._gl.createTexture();
  6373. texture._baseWidth = width;
  6374. texture._baseHeight = height;
  6375. if (forceExponantOfTwo) {
  6376. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6377. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6378. }
  6379. this.resetTextureCache();
  6380. texture._width = width;
  6381. texture._height = height;
  6382. texture.isReady = false;
  6383. texture.generateMipMaps = generateMipMaps;
  6384. texture.references = 1;
  6385. texture.samplingMode = samplingMode;
  6386. this.updateTextureSamplingMode(samplingMode, texture);
  6387. this._loadedTexturesCache.push(texture);
  6388. return texture;
  6389. };
  6390. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6391. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6392. if (texture.isCube) {
  6393. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6394. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6395. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6396. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6397. }
  6398. else {
  6399. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6400. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6401. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6402. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6403. }
  6404. };
  6405. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6406. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6407. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6408. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6409. if (texture.generateMipMaps) {
  6410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6411. }
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6413. this.resetTextureCache();
  6414. texture.isReady = true;
  6415. };
  6416. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6417. if (texture._isDisabled) {
  6418. return;
  6419. }
  6420. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6421. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6422. try {
  6423. // Testing video texture support
  6424. if (this._videoTextureSupported === undefined) {
  6425. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6426. if (this._gl.getError() !== 0) {
  6427. this._videoTextureSupported = false;
  6428. }
  6429. else {
  6430. this._videoTextureSupported = true;
  6431. }
  6432. }
  6433. // Copy video through the current working canvas if video texture is not supported
  6434. if (!this._videoTextureSupported) {
  6435. if (!texture._workingCanvas) {
  6436. texture._workingCanvas = document.createElement("canvas");
  6437. texture._workingContext = texture._workingCanvas.getContext("2d");
  6438. texture._workingCanvas.width = texture._width;
  6439. texture._workingCanvas.height = texture._height;
  6440. }
  6441. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6442. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6443. }
  6444. else {
  6445. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6446. }
  6447. if (texture.generateMipMaps) {
  6448. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6449. }
  6450. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6451. this.resetTextureCache();
  6452. texture.isReady = true;
  6453. }
  6454. catch (ex) {
  6455. // Something unexpected
  6456. // Let's disable the texture
  6457. texture._isDisabled = true;
  6458. }
  6459. };
  6460. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6461. // old version had a "generateMipMaps" arg instead of options.
  6462. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6463. // in the same way, generateDepthBuffer is defaulted to true
  6464. var generateMipMaps = false;
  6465. var generateDepthBuffer = true;
  6466. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6467. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6468. if (options !== undefined) {
  6469. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6470. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6471. type = options.type === undefined ? type : options.type;
  6472. if (options.samplingMode !== undefined) {
  6473. samplingMode = options.samplingMode;
  6474. }
  6475. if (type === Engine.TEXTURETYPE_FLOAT) {
  6476. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6477. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6478. }
  6479. }
  6480. var gl = this._gl;
  6481. var texture = gl.createTexture();
  6482. gl.bindTexture(gl.TEXTURE_2D, texture);
  6483. var width = size.width || size;
  6484. var height = size.height || size;
  6485. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6486. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6487. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6488. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6489. }
  6490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6491. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6494. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6495. var depthBuffer;
  6496. // Create the depth buffer
  6497. if (generateDepthBuffer) {
  6498. depthBuffer = gl.createRenderbuffer();
  6499. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6500. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6501. }
  6502. // Create the framebuffer
  6503. var framebuffer = gl.createFramebuffer();
  6504. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6505. if (generateDepthBuffer) {
  6506. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6507. }
  6508. if (generateMipMaps) {
  6509. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6510. }
  6511. // Unbind
  6512. gl.bindTexture(gl.TEXTURE_2D, null);
  6513. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6514. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6515. texture._framebuffer = framebuffer;
  6516. if (generateDepthBuffer) {
  6517. texture._depthBuffer = depthBuffer;
  6518. }
  6519. texture._width = width;
  6520. texture._height = height;
  6521. texture.isReady = true;
  6522. texture.generateMipMaps = generateMipMaps;
  6523. texture.references = 1;
  6524. texture.samplingMode = samplingMode;
  6525. this.resetTextureCache();
  6526. this._loadedTexturesCache.push(texture);
  6527. return texture;
  6528. };
  6529. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6530. var gl = this._gl;
  6531. var texture = gl.createTexture();
  6532. var generateMipMaps = true;
  6533. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6534. if (options !== undefined) {
  6535. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6536. if (options.samplingMode !== undefined) {
  6537. samplingMode = options.samplingMode;
  6538. }
  6539. }
  6540. texture.isCube = true;
  6541. texture.references = 1;
  6542. texture.generateMipMaps = generateMipMaps;
  6543. texture.references = 1;
  6544. texture.samplingMode = samplingMode;
  6545. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6546. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6547. for (var face = 0; face < 6; face++) {
  6548. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6549. }
  6550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6554. // Create the depth buffer
  6555. var depthBuffer = gl.createRenderbuffer();
  6556. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6557. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6558. // Create the framebuffer
  6559. var framebuffer = gl.createFramebuffer();
  6560. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6561. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6562. // Mipmaps
  6563. if (texture.generateMipMaps) {
  6564. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6565. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6566. }
  6567. // Unbind
  6568. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6569. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6570. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6571. texture._framebuffer = framebuffer;
  6572. texture._depthBuffer = depthBuffer;
  6573. this.resetTextureCache();
  6574. texture._width = size;
  6575. texture._height = size;
  6576. texture.isReady = true;
  6577. return texture;
  6578. };
  6579. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6580. var _this = this;
  6581. var gl = this._gl;
  6582. var texture = gl.createTexture();
  6583. texture.isCube = true;
  6584. texture.url = rootUrl;
  6585. texture.references = 1;
  6586. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6587. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6588. if (isDDS) {
  6589. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6590. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6591. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6592. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6593. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6594. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6595. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6596. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6597. }
  6598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6602. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6603. _this.resetTextureCache();
  6604. texture._width = info.width;
  6605. texture._height = info.height;
  6606. texture.isReady = true;
  6607. }, null, null, true);
  6608. }
  6609. else {
  6610. cascadeLoad(rootUrl, scene, function (imgs) {
  6611. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6612. var height = width;
  6613. _this._prepareWorkingCanvas();
  6614. _this._workingCanvas.width = width;
  6615. _this._workingCanvas.height = height;
  6616. var faces = [
  6617. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6618. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6619. ];
  6620. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6621. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6622. for (var index = 0; index < faces.length; index++) {
  6623. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6624. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6625. }
  6626. if (!noMipmap) {
  6627. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6628. }
  6629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6633. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6634. _this.resetTextureCache();
  6635. texture._width = width;
  6636. texture._height = height;
  6637. texture.isReady = true;
  6638. }, files);
  6639. }
  6640. return texture;
  6641. };
  6642. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6643. var _this = this;
  6644. var gl = this._gl;
  6645. var texture = gl.createTexture();
  6646. scene._addPendingData(texture);
  6647. texture.isCube = true;
  6648. texture.references = 1;
  6649. texture.url = url;
  6650. var internalFormat = this._getInternalFormat(format);
  6651. var textureType = gl.UNSIGNED_BYTE;
  6652. if (type === Engine.TEXTURETYPE_FLOAT) {
  6653. textureType = gl.FLOAT;
  6654. }
  6655. var width = size;
  6656. var height = width;
  6657. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6658. texture._width = width;
  6659. texture._height = height;
  6660. var onerror = function () {
  6661. scene._removePendingData(texture);
  6662. };
  6663. var internalCallback = function (data) {
  6664. var rgbeDataArrays = callback(data);
  6665. var facesIndex = [
  6666. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6667. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6668. ];
  6669. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6670. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6671. for (var index = 0; index < facesIndex.length; index++) {
  6672. var faceData = rgbeDataArrays[index];
  6673. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6674. }
  6675. if (!noMipmap && isPot) {
  6676. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6677. }
  6678. else {
  6679. noMipmap = true;
  6680. }
  6681. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6684. }
  6685. else {
  6686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6688. }
  6689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6691. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6692. texture.isReady = true;
  6693. _this.resetTextureCache();
  6694. scene._removePendingData(texture);
  6695. };
  6696. BABYLON.Tools.LoadFile(url, function (data) {
  6697. internalCallback(data);
  6698. }, onerror, scene.database, true);
  6699. return texture;
  6700. };
  6701. ;
  6702. Engine.prototype._releaseTexture = function (texture) {
  6703. var gl = this._gl;
  6704. if (texture._framebuffer) {
  6705. gl.deleteFramebuffer(texture._framebuffer);
  6706. }
  6707. if (texture._depthBuffer) {
  6708. gl.deleteRenderbuffer(texture._depthBuffer);
  6709. }
  6710. gl.deleteTexture(texture);
  6711. // Unbind channels
  6712. this.unbindAllTextures();
  6713. var index = this._loadedTexturesCache.indexOf(texture);
  6714. if (index !== -1) {
  6715. this._loadedTexturesCache.splice(index, 1);
  6716. }
  6717. };
  6718. Engine.prototype.bindSamplers = function (effect) {
  6719. this._gl.useProgram(effect.getProgram());
  6720. var samplers = effect.getSamplers();
  6721. for (var index = 0; index < samplers.length; index++) {
  6722. var uniform = effect.getUniform(samplers[index]);
  6723. this._gl.uniform1i(uniform, index);
  6724. }
  6725. this._currentEffect = null;
  6726. };
  6727. Engine.prototype._bindTexture = function (channel, texture) {
  6728. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6729. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6730. this._activeTexturesCache[channel] = null;
  6731. };
  6732. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6733. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6734. };
  6735. Engine.prototype.unbindAllTextures = function () {
  6736. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6737. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6738. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6739. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6740. this._activeTexturesCache[channel] = null;
  6741. }
  6742. };
  6743. Engine.prototype.setTexture = function (channel, texture) {
  6744. if (channel < 0) {
  6745. return;
  6746. }
  6747. // Not ready?
  6748. if (!texture || !texture.isReady()) {
  6749. if (this._activeTexturesCache[channel] != null) {
  6750. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6751. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6752. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6753. this._activeTexturesCache[channel] = null;
  6754. }
  6755. return;
  6756. }
  6757. // Video
  6758. var alreadyActivated = false;
  6759. if (texture instanceof BABYLON.VideoTexture) {
  6760. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6761. alreadyActivated = true;
  6762. texture.update();
  6763. }
  6764. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6765. texture.delayLoad();
  6766. return;
  6767. }
  6768. if (this._activeTexturesCache[channel] === texture) {
  6769. return;
  6770. }
  6771. this._activeTexturesCache[channel] = texture;
  6772. var internalTexture = texture.getInternalTexture();
  6773. if (!alreadyActivated) {
  6774. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6775. }
  6776. if (internalTexture.isCube) {
  6777. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6778. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6779. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6780. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6781. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6782. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6783. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6784. }
  6785. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6786. }
  6787. else {
  6788. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6789. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6790. internalTexture._cachedWrapU = texture.wrapU;
  6791. switch (texture.wrapU) {
  6792. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6793. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6794. break;
  6795. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6796. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6797. break;
  6798. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6799. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6800. break;
  6801. }
  6802. }
  6803. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6804. internalTexture._cachedWrapV = texture.wrapV;
  6805. switch (texture.wrapV) {
  6806. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6807. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6808. break;
  6809. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6810. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6811. break;
  6812. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6813. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6814. break;
  6815. }
  6816. }
  6817. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6818. }
  6819. };
  6820. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6821. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6822. var value = texture.anisotropicFilteringLevel;
  6823. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6824. value = 1;
  6825. }
  6826. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6827. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6828. texture._cachedAnisotropicFilteringLevel = value;
  6829. }
  6830. };
  6831. Engine.prototype.readPixels = function (x, y, width, height) {
  6832. var data = new Uint8Array(height * width * 4);
  6833. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6834. return data;
  6835. };
  6836. Engine.prototype.releaseInternalTexture = function (texture) {
  6837. if (!texture) {
  6838. return;
  6839. }
  6840. texture.references--;
  6841. // Final reference ?
  6842. if (texture.references === 0) {
  6843. var texturesCache = this.getLoadedTexturesCache();
  6844. var index = texturesCache.indexOf(texture);
  6845. if (index > -1) {
  6846. texturesCache.splice(index, 1);
  6847. }
  6848. this._releaseTexture(texture);
  6849. }
  6850. };
  6851. // Dispose
  6852. Engine.prototype.dispose = function () {
  6853. this.hideLoadingUI();
  6854. this.stopRenderLoop();
  6855. // Release scenes
  6856. while (this.scenes.length) {
  6857. this.scenes[0].dispose();
  6858. }
  6859. // Release audio engine
  6860. Engine.audioEngine.dispose();
  6861. // Release effects
  6862. for (var name in this._compiledEffects) {
  6863. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6864. }
  6865. // Unbind
  6866. for (var i in this._vertexAttribArrays) {
  6867. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6868. continue;
  6869. }
  6870. this._gl.disableVertexAttribArray(i);
  6871. }
  6872. this._gl = null;
  6873. // Events
  6874. window.removeEventListener("blur", this._onBlur);
  6875. window.removeEventListener("focus", this._onFocus);
  6876. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6877. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6878. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6879. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6880. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6881. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6882. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6883. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6884. };
  6885. // Loading screen
  6886. Engine.prototype.displayLoadingUI = function () {
  6887. this._loadingScreen.displayLoadingUI();
  6888. };
  6889. Engine.prototype.hideLoadingUI = function () {
  6890. this._loadingScreen.hideLoadingUI();
  6891. };
  6892. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6893. get: function () {
  6894. return this._loadingScreen;
  6895. },
  6896. set: function (loadingScreen) {
  6897. this._loadingScreen = loadingScreen;
  6898. },
  6899. enumerable: true,
  6900. configurable: true
  6901. });
  6902. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6903. set: function (text) {
  6904. this._loadingScreen.loadingUIText = text;
  6905. },
  6906. enumerable: true,
  6907. configurable: true
  6908. });
  6909. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6910. set: function (color) {
  6911. this._loadingScreen.loadingUIBackgroundColor = color;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. // FPS
  6917. Engine.prototype.getFps = function () {
  6918. return this.fps;
  6919. };
  6920. Engine.prototype.getDeltaTime = function () {
  6921. return this.deltaTime;
  6922. };
  6923. Engine.prototype._measureFps = function () {
  6924. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6925. var length = this.previousFramesDuration.length;
  6926. if (length >= 2) {
  6927. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6928. }
  6929. if (length >= this.fpsRange) {
  6930. if (length > this.fpsRange) {
  6931. this.previousFramesDuration.splice(0, 1);
  6932. length = this.previousFramesDuration.length;
  6933. }
  6934. var sum = 0;
  6935. for (var id = 0; id < length - 1; id++) {
  6936. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6937. }
  6938. this.fps = 1000.0 / (sum / (length - 1));
  6939. }
  6940. };
  6941. // Statics
  6942. Engine.isSupported = function () {
  6943. try {
  6944. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6945. if (navigator.isCocoonJS) {
  6946. return true;
  6947. }
  6948. var tempcanvas = document.createElement("canvas");
  6949. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6950. return gl != null && !!window.WebGLRenderingContext;
  6951. }
  6952. catch (e) {
  6953. return false;
  6954. }
  6955. };
  6956. // Const statics
  6957. Engine._ALPHA_DISABLE = 0;
  6958. Engine._ALPHA_ADD = 1;
  6959. Engine._ALPHA_COMBINE = 2;
  6960. Engine._ALPHA_SUBTRACT = 3;
  6961. Engine._ALPHA_MULTIPLY = 4;
  6962. Engine._ALPHA_MAXIMIZED = 5;
  6963. Engine._ALPHA_ONEONE = 6;
  6964. Engine._DELAYLOADSTATE_NONE = 0;
  6965. Engine._DELAYLOADSTATE_LOADED = 1;
  6966. Engine._DELAYLOADSTATE_LOADING = 2;
  6967. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6968. Engine._TEXTUREFORMAT_ALPHA = 0;
  6969. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6970. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6971. Engine._TEXTUREFORMAT_RGB = 4;
  6972. Engine._TEXTUREFORMAT_RGBA = 5;
  6973. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6974. Engine._TEXTURETYPE_FLOAT = 1;
  6975. // Updatable statics so stick with vars here
  6976. Engine.Epsilon = 0.001;
  6977. Engine.CollisionsEpsilon = 0.001;
  6978. Engine.CodeRepository = "src/";
  6979. Engine.ShadersRepository = "src/Shaders/";
  6980. return Engine;
  6981. })();
  6982. BABYLON.Engine = Engine;
  6983. })(BABYLON || (BABYLON = {}));
  6984. var BABYLON;
  6985. (function (BABYLON) {
  6986. /**
  6987. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6988. */
  6989. var Node = (function () {
  6990. /**
  6991. * @constructor
  6992. * @param {string} name - the name and id to be given to this node
  6993. * @param {BABYLON.Scene} the scene this node will be added to
  6994. */
  6995. function Node(name, scene) {
  6996. this.state = "";
  6997. this.animations = new Array();
  6998. this._ranges = {};
  6999. this._childrenFlag = -1;
  7000. this._isEnabled = true;
  7001. this._isReady = true;
  7002. this._currentRenderId = -1;
  7003. this._parentRenderId = -1;
  7004. this.name = name;
  7005. this.id = name;
  7006. this._scene = scene;
  7007. this._initCache();
  7008. }
  7009. Node.prototype.getScene = function () {
  7010. return this._scene;
  7011. };
  7012. Node.prototype.getEngine = function () {
  7013. return this._scene.getEngine();
  7014. };
  7015. // override it in derived class
  7016. Node.prototype.getWorldMatrix = function () {
  7017. return BABYLON.Matrix.Identity();
  7018. };
  7019. // override it in derived class if you add new variables to the cache
  7020. // and call the parent class method
  7021. Node.prototype._initCache = function () {
  7022. this._cache = {};
  7023. this._cache.parent = undefined;
  7024. };
  7025. Node.prototype.updateCache = function (force) {
  7026. if (!force && this.isSynchronized())
  7027. return;
  7028. this._cache.parent = this.parent;
  7029. this._updateCache();
  7030. };
  7031. // override it in derived class if you add new variables to the cache
  7032. // and call the parent class method if !ignoreParentClass
  7033. Node.prototype._updateCache = function (ignoreParentClass) {
  7034. };
  7035. // override it in derived class if you add new variables to the cache
  7036. Node.prototype._isSynchronized = function () {
  7037. return true;
  7038. };
  7039. Node.prototype._markSyncedWithParent = function () {
  7040. this._parentRenderId = this.parent._currentRenderId;
  7041. };
  7042. Node.prototype.isSynchronizedWithParent = function () {
  7043. if (!this.parent) {
  7044. return true;
  7045. }
  7046. if (this._parentRenderId !== this.parent._currentRenderId) {
  7047. return false;
  7048. }
  7049. return this.parent.isSynchronized();
  7050. };
  7051. Node.prototype.isSynchronized = function (updateCache) {
  7052. var check = this.hasNewParent();
  7053. check = check || !this.isSynchronizedWithParent();
  7054. check = check || !this._isSynchronized();
  7055. if (updateCache)
  7056. this.updateCache(true);
  7057. return !check;
  7058. };
  7059. Node.prototype.hasNewParent = function (update) {
  7060. if (this._cache.parent === this.parent)
  7061. return false;
  7062. if (update)
  7063. this._cache.parent = this.parent;
  7064. return true;
  7065. };
  7066. /**
  7067. * Is this node ready to be used/rendered
  7068. * @return {boolean} is it ready
  7069. */
  7070. Node.prototype.isReady = function () {
  7071. return this._isReady;
  7072. };
  7073. /**
  7074. * Is this node enabled.
  7075. * If the node has a parent and is enabled, the parent will be inspected as well.
  7076. * @return {boolean} whether this node (and its parent) is enabled.
  7077. * @see setEnabled
  7078. */
  7079. Node.prototype.isEnabled = function () {
  7080. if (!this._isEnabled) {
  7081. return false;
  7082. }
  7083. if (this.parent) {
  7084. return this.parent.isEnabled();
  7085. }
  7086. return true;
  7087. };
  7088. /**
  7089. * Set the enabled state of this node.
  7090. * @param {boolean} value - the new enabled state
  7091. * @see isEnabled
  7092. */
  7093. Node.prototype.setEnabled = function (value) {
  7094. this._isEnabled = value;
  7095. };
  7096. /**
  7097. * Is this node a descendant of the given node.
  7098. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7099. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7100. * @see parent
  7101. */
  7102. Node.prototype.isDescendantOf = function (ancestor) {
  7103. if (this.parent) {
  7104. if (this.parent === ancestor) {
  7105. return true;
  7106. }
  7107. return this.parent.isDescendantOf(ancestor);
  7108. }
  7109. return false;
  7110. };
  7111. Node.prototype._getDescendants = function (list, results) {
  7112. for (var index = 0; index < list.length; index++) {
  7113. var item = list[index];
  7114. if (item.isDescendantOf(this)) {
  7115. results.push(item);
  7116. }
  7117. }
  7118. };
  7119. /**
  7120. * Will return all nodes that have this node as parent.
  7121. * @return {BABYLON.Node[]} all children nodes of all types.
  7122. */
  7123. Node.prototype.getDescendants = function () {
  7124. var results = [];
  7125. this._getDescendants(this._scene.meshes, results);
  7126. this._getDescendants(this._scene.lights, results);
  7127. this._getDescendants(this._scene.cameras, results);
  7128. return results;
  7129. };
  7130. Node.prototype._setReady = function (state) {
  7131. if (state === this._isReady) {
  7132. return;
  7133. }
  7134. if (!state) {
  7135. this._isReady = false;
  7136. return;
  7137. }
  7138. this._isReady = true;
  7139. if (this.onReady) {
  7140. this.onReady(this);
  7141. }
  7142. };
  7143. Node.prototype.getAnimationByName = function (name) {
  7144. for (var i = 0; i < this.animations.length; i++) {
  7145. var animation = this.animations[i];
  7146. if (animation.name === name) {
  7147. return animation;
  7148. }
  7149. }
  7150. return null;
  7151. };
  7152. Node.prototype.createAnimationRange = function (name, from, to) {
  7153. // check name not already in use
  7154. if (!this._ranges[name]) {
  7155. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7156. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7157. if (this.animations[i]) {
  7158. this.animations[i].createRange(name, from, to);
  7159. }
  7160. }
  7161. }
  7162. };
  7163. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7164. if (deleteFrames === void 0) { deleteFrames = true; }
  7165. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7166. if (this.animations[i]) {
  7167. this.animations[i].deleteRange(name, deleteFrames);
  7168. }
  7169. }
  7170. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7171. };
  7172. Node.prototype.getAnimationRange = function (name) {
  7173. return this._ranges[name];
  7174. };
  7175. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7176. var range = this.getAnimationRange(name);
  7177. if (!range) {
  7178. return null;
  7179. }
  7180. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7181. };
  7182. Node.prototype.serializeAnimationRanges = function () {
  7183. var serializationRanges = [];
  7184. for (var name in this._ranges) {
  7185. var range = {};
  7186. range.name = name;
  7187. range.from = this._ranges[name].from;
  7188. range.to = this._ranges[name].to;
  7189. serializationRanges.push(range);
  7190. }
  7191. return serializationRanges;
  7192. };
  7193. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7194. if (parsedNode.ranges) {
  7195. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7196. var data = parsedNode.ranges[index];
  7197. node.createAnimationRange(data.name, data.from, data.to);
  7198. }
  7199. }
  7200. };
  7201. return Node;
  7202. })();
  7203. BABYLON.Node = Node;
  7204. })(BABYLON || (BABYLON = {}));
  7205. var BABYLON;
  7206. (function (BABYLON) {
  7207. var FilesInput = (function () {
  7208. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7209. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7210. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7211. this._engine = p_engine;
  7212. this._canvas = p_canvas;
  7213. this._currentScene = p_scene;
  7214. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7215. this._progressCallback = p_progressCallback;
  7216. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7217. this._textureLoadingCallback = p_textureLoadingCallback;
  7218. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7219. }
  7220. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7221. var _this = this;
  7222. if (p_elementToMonitor) {
  7223. this._elementToMonitor = p_elementToMonitor;
  7224. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7225. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7226. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7227. }
  7228. };
  7229. FilesInput.prototype.renderFunction = function () {
  7230. if (this._additionnalRenderLoopLogicCallback) {
  7231. this._additionnalRenderLoopLogicCallback();
  7232. }
  7233. if (this._currentScene) {
  7234. if (this._textureLoadingCallback) {
  7235. var remaining = this._currentScene.getWaitingItemsCount();
  7236. if (remaining > 0) {
  7237. this._textureLoadingCallback(remaining);
  7238. }
  7239. }
  7240. this._currentScene.render();
  7241. }
  7242. };
  7243. FilesInput.prototype.drag = function (e) {
  7244. e.stopPropagation();
  7245. e.preventDefault();
  7246. };
  7247. FilesInput.prototype.drop = function (eventDrop) {
  7248. eventDrop.stopPropagation();
  7249. eventDrop.preventDefault();
  7250. this.loadFiles(eventDrop);
  7251. };
  7252. FilesInput.prototype.loadFiles = function (event) {
  7253. if (this._startingProcessingFilesCallback)
  7254. this._startingProcessingFilesCallback();
  7255. // Handling data transfer via drag'n'drop
  7256. if (event && event.dataTransfer && event.dataTransfer.files) {
  7257. this._filesToLoad = event.dataTransfer.files;
  7258. }
  7259. // Handling files from input files
  7260. if (event && event.target && event.target.files) {
  7261. this._filesToLoad = event.target.files;
  7262. }
  7263. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7264. for (var i = 0; i < this._filesToLoad.length; i++) {
  7265. switch (this._filesToLoad[i].type) {
  7266. case "image/jpeg":
  7267. case "image/png":
  7268. case "image/bmp":
  7269. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7270. break;
  7271. case "image/targa":
  7272. case "image/vnd.ms-dds":
  7273. case "audio/wav":
  7274. case "audio/x-wav":
  7275. case "audio/mp3":
  7276. case "audio/mpeg":
  7277. case "audio/mpeg3":
  7278. case "audio/x-mpeg-3":
  7279. case "audio/ogg":
  7280. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7281. break;
  7282. default:
  7283. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7284. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7285. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7286. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7287. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7288. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7289. this._sceneFileToLoad = this._filesToLoad[i];
  7290. }
  7291. break;
  7292. }
  7293. }
  7294. this.reload();
  7295. }
  7296. };
  7297. FilesInput.prototype.reload = function () {
  7298. var _this = this;
  7299. var that = this;
  7300. // If a ".babylon" file has been provided
  7301. if (this._sceneFileToLoad) {
  7302. if (this._currentScene) {
  7303. if (BABYLON.Tools.errorsCount > 0) {
  7304. BABYLON.Tools.ClearLogCache();
  7305. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7306. }
  7307. this._engine.stopRenderLoop();
  7308. this._currentScene.dispose();
  7309. }
  7310. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7311. that._currentScene = newScene;
  7312. // Wait for textures and shaders to be ready
  7313. that._currentScene.executeWhenReady(function () {
  7314. // Attach camera to canvas inputs
  7315. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7316. that._currentScene.createDefaultCameraOrLight();
  7317. }
  7318. that._currentScene.activeCamera.attachControl(that._canvas);
  7319. if (that._sceneLoadedCallback) {
  7320. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7321. }
  7322. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7323. });
  7324. }, function (progress) {
  7325. if (_this._progressCallback) {
  7326. _this._progressCallback(progress);
  7327. }
  7328. });
  7329. }
  7330. else {
  7331. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7332. }
  7333. };
  7334. FilesInput.FilesTextures = new Array();
  7335. FilesInput.FilesToLoad = new Array();
  7336. return FilesInput;
  7337. })();
  7338. BABYLON.FilesInput = FilesInput;
  7339. })(BABYLON || (BABYLON = {}));
  7340. var BABYLON;
  7341. (function (BABYLON) {
  7342. var IntersectionInfo = (function () {
  7343. function IntersectionInfo(bu, bv, distance) {
  7344. this.bu = bu;
  7345. this.bv = bv;
  7346. this.distance = distance;
  7347. this.faceId = 0;
  7348. this.subMeshId = 0;
  7349. }
  7350. return IntersectionInfo;
  7351. })();
  7352. BABYLON.IntersectionInfo = IntersectionInfo;
  7353. var PickingInfo = (function () {
  7354. function PickingInfo() {
  7355. this.hit = false;
  7356. this.distance = 0;
  7357. this.pickedPoint = null;
  7358. this.pickedMesh = null;
  7359. this.bu = 0;
  7360. this.bv = 0;
  7361. this.faceId = -1;
  7362. this.subMeshId = 0;
  7363. this.pickedSprite = null;
  7364. }
  7365. // Methods
  7366. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7367. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7368. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7369. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7370. return null;
  7371. }
  7372. var indices = this.pickedMesh.getIndices();
  7373. var result;
  7374. if (useVerticesNormals) {
  7375. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7376. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7377. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7378. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7379. normal0 = normal0.scale(this.bu);
  7380. normal1 = normal1.scale(this.bv);
  7381. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7382. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7383. }
  7384. else {
  7385. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7386. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7387. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7388. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7389. var p1p2 = vertex1.subtract(vertex2);
  7390. var p3p2 = vertex3.subtract(vertex2);
  7391. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7392. }
  7393. if (useWorldCoordinates) {
  7394. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7395. }
  7396. return BABYLON.Vector3.Normalize(result);
  7397. };
  7398. PickingInfo.prototype.getTextureCoordinates = function () {
  7399. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7400. return null;
  7401. }
  7402. var indices = this.pickedMesh.getIndices();
  7403. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7404. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7405. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7406. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7407. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7408. uv1 = uv1.scale(this.bu);
  7409. uv2 = uv2.scale(this.bv);
  7410. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7411. };
  7412. return PickingInfo;
  7413. })();
  7414. BABYLON.PickingInfo = PickingInfo;
  7415. })(BABYLON || (BABYLON = {}));
  7416. var BABYLON;
  7417. (function (BABYLON) {
  7418. var BoundingSphere = (function () {
  7419. function BoundingSphere(minimum, maximum) {
  7420. this.minimum = minimum;
  7421. this.maximum = maximum;
  7422. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7423. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7424. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7425. this.radius = distance * 0.5;
  7426. this.centerWorld = BABYLON.Vector3.Zero();
  7427. this._update(BABYLON.Matrix.Identity());
  7428. }
  7429. // Methods
  7430. BoundingSphere.prototype._update = function (world) {
  7431. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7432. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7433. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7434. };
  7435. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7436. for (var i = 0; i < 6; i++) {
  7437. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7438. return false;
  7439. }
  7440. return true;
  7441. };
  7442. BoundingSphere.prototype.intersectsPoint = function (point) {
  7443. var x = this.centerWorld.x - point.x;
  7444. var y = this.centerWorld.y - point.y;
  7445. var z = this.centerWorld.z - point.z;
  7446. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7447. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7448. return false;
  7449. return true;
  7450. };
  7451. // Statics
  7452. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7453. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7454. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7455. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7456. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7457. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7458. return false;
  7459. return true;
  7460. };
  7461. return BoundingSphere;
  7462. })();
  7463. BABYLON.BoundingSphere = BoundingSphere;
  7464. })(BABYLON || (BABYLON = {}));
  7465. var BABYLON;
  7466. (function (BABYLON) {
  7467. var BoundingBox = (function () {
  7468. function BoundingBox(minimum, maximum) {
  7469. this.minimum = minimum;
  7470. this.maximum = maximum;
  7471. this.vectors = new Array();
  7472. this.vectorsWorld = new Array();
  7473. // Bounding vectors
  7474. this.vectors.push(this.minimum.clone());
  7475. this.vectors.push(this.maximum.clone());
  7476. this.vectors.push(this.minimum.clone());
  7477. this.vectors[2].x = this.maximum.x;
  7478. this.vectors.push(this.minimum.clone());
  7479. this.vectors[3].y = this.maximum.y;
  7480. this.vectors.push(this.minimum.clone());
  7481. this.vectors[4].z = this.maximum.z;
  7482. this.vectors.push(this.maximum.clone());
  7483. this.vectors[5].z = this.minimum.z;
  7484. this.vectors.push(this.maximum.clone());
  7485. this.vectors[6].x = this.minimum.x;
  7486. this.vectors.push(this.maximum.clone());
  7487. this.vectors[7].y = this.minimum.y;
  7488. // OBB
  7489. this.center = this.maximum.add(this.minimum).scale(0.5);
  7490. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7491. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7492. // World
  7493. for (var index = 0; index < this.vectors.length; index++) {
  7494. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7495. }
  7496. this.minimumWorld = BABYLON.Vector3.Zero();
  7497. this.maximumWorld = BABYLON.Vector3.Zero();
  7498. this._update(BABYLON.Matrix.Identity());
  7499. }
  7500. // Methods
  7501. BoundingBox.prototype.getWorldMatrix = function () {
  7502. return this._worldMatrix;
  7503. };
  7504. BoundingBox.prototype._update = function (world) {
  7505. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7506. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7507. for (var index = 0; index < this.vectors.length; index++) {
  7508. var v = this.vectorsWorld[index];
  7509. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7510. if (v.x < this.minimumWorld.x)
  7511. this.minimumWorld.x = v.x;
  7512. if (v.y < this.minimumWorld.y)
  7513. this.minimumWorld.y = v.y;
  7514. if (v.z < this.minimumWorld.z)
  7515. this.minimumWorld.z = v.z;
  7516. if (v.x > this.maximumWorld.x)
  7517. this.maximumWorld.x = v.x;
  7518. if (v.y > this.maximumWorld.y)
  7519. this.maximumWorld.y = v.y;
  7520. if (v.z > this.maximumWorld.z)
  7521. this.maximumWorld.z = v.z;
  7522. }
  7523. // OBB
  7524. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7525. this.center.scaleInPlace(0.5);
  7526. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7527. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7528. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7529. this._worldMatrix = world;
  7530. };
  7531. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7532. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7533. };
  7534. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7535. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7536. };
  7537. BoundingBox.prototype.intersectsPoint = function (point) {
  7538. var delta = -BABYLON.Engine.Epsilon;
  7539. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7540. return false;
  7541. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7542. return false;
  7543. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7544. return false;
  7545. return true;
  7546. };
  7547. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7548. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7549. };
  7550. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7551. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7552. return false;
  7553. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7554. return false;
  7555. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7556. return false;
  7557. return true;
  7558. };
  7559. // Statics
  7560. BoundingBox.Intersects = function (box0, box1) {
  7561. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7562. return false;
  7563. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7564. return false;
  7565. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7566. return false;
  7567. return true;
  7568. };
  7569. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7570. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7571. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7572. return (num <= (sphereRadius * sphereRadius));
  7573. };
  7574. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7575. for (var p = 0; p < 6; p++) {
  7576. for (var i = 0; i < 8; i++) {
  7577. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7578. return false;
  7579. }
  7580. }
  7581. }
  7582. return true;
  7583. };
  7584. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7585. for (var p = 0; p < 6; p++) {
  7586. var inCount = 8;
  7587. for (var i = 0; i < 8; i++) {
  7588. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7589. --inCount;
  7590. }
  7591. else {
  7592. break;
  7593. }
  7594. }
  7595. if (inCount === 0)
  7596. return false;
  7597. }
  7598. return true;
  7599. };
  7600. return BoundingBox;
  7601. })();
  7602. BABYLON.BoundingBox = BoundingBox;
  7603. })(BABYLON || (BABYLON = {}));
  7604. var BABYLON;
  7605. (function (BABYLON) {
  7606. var computeBoxExtents = function (axis, box) {
  7607. var p = BABYLON.Vector3.Dot(box.center, axis);
  7608. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7609. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7610. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7611. var r = r0 + r1 + r2;
  7612. return {
  7613. min: p - r,
  7614. max: p + r
  7615. };
  7616. };
  7617. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7618. var axisOverlap = function (axis, box0, box1) {
  7619. var result0 = computeBoxExtents(axis, box0);
  7620. var result1 = computeBoxExtents(axis, box1);
  7621. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7622. };
  7623. var BoundingInfo = (function () {
  7624. function BoundingInfo(minimum, maximum) {
  7625. this.minimum = minimum;
  7626. this.maximum = maximum;
  7627. this._isLocked = false;
  7628. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7629. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7630. }
  7631. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7632. get: function () {
  7633. return this._isLocked;
  7634. },
  7635. set: function (value) {
  7636. this._isLocked = value;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. // Methods
  7642. BoundingInfo.prototype.update = function (world) {
  7643. if (this._isLocked) {
  7644. return;
  7645. }
  7646. this.boundingBox._update(world);
  7647. this.boundingSphere._update(world);
  7648. };
  7649. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7650. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7651. return false;
  7652. return this.boundingBox.isInFrustum(frustumPlanes);
  7653. };
  7654. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7655. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7656. };
  7657. BoundingInfo.prototype._checkCollision = function (collider) {
  7658. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7659. };
  7660. BoundingInfo.prototype.intersectsPoint = function (point) {
  7661. if (!this.boundingSphere.centerWorld) {
  7662. return false;
  7663. }
  7664. if (!this.boundingSphere.intersectsPoint(point)) {
  7665. return false;
  7666. }
  7667. if (!this.boundingBox.intersectsPoint(point)) {
  7668. return false;
  7669. }
  7670. return true;
  7671. };
  7672. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7673. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7674. return false;
  7675. }
  7676. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7677. return false;
  7678. }
  7679. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7680. return false;
  7681. }
  7682. if (!precise) {
  7683. return true;
  7684. }
  7685. var box0 = this.boundingBox;
  7686. var box1 = boundingInfo.boundingBox;
  7687. if (!axisOverlap(box0.directions[0], box0, box1))
  7688. return false;
  7689. if (!axisOverlap(box0.directions[1], box0, box1))
  7690. return false;
  7691. if (!axisOverlap(box0.directions[2], box0, box1))
  7692. return false;
  7693. if (!axisOverlap(box1.directions[0], box0, box1))
  7694. return false;
  7695. if (!axisOverlap(box1.directions[1], box0, box1))
  7696. return false;
  7697. if (!axisOverlap(box1.directions[2], box0, box1))
  7698. return false;
  7699. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7700. return false;
  7701. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7702. return false;
  7703. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7704. return false;
  7705. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7706. return false;
  7707. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7708. return false;
  7709. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7710. return false;
  7711. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7712. return false;
  7713. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7714. return false;
  7715. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7716. return false;
  7717. return true;
  7718. };
  7719. return BoundingInfo;
  7720. })();
  7721. BABYLON.BoundingInfo = BoundingInfo;
  7722. })(BABYLON || (BABYLON = {}));
  7723. var BABYLON;
  7724. (function (BABYLON) {
  7725. var AbstractMesh = (function (_super) {
  7726. __extends(AbstractMesh, _super);
  7727. // Constructor
  7728. function AbstractMesh(name, scene) {
  7729. var _this = this;
  7730. _super.call(this, name, scene);
  7731. // Properties
  7732. this.definedFacingForward = true; // orientation for POV movement & rotation
  7733. this.position = new BABYLON.Vector3(0, 0, 0);
  7734. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7735. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7736. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7737. this.visibility = 1.0;
  7738. this.alphaIndex = Number.MAX_VALUE;
  7739. this.infiniteDistance = false;
  7740. this.isVisible = true;
  7741. this.isPickable = true;
  7742. this.showBoundingBox = false;
  7743. this.showSubMeshesBoundingBox = false;
  7744. this.onDispose = null;
  7745. this.isBlocker = false;
  7746. this.renderingGroupId = 0;
  7747. this.receiveShadows = false;
  7748. this.renderOutline = false;
  7749. this.outlineColor = BABYLON.Color3.Red();
  7750. this.outlineWidth = 0.02;
  7751. this.renderOverlay = false;
  7752. this.overlayColor = BABYLON.Color3.Red();
  7753. this.overlayAlpha = 0.5;
  7754. this.hasVertexAlpha = false;
  7755. this.useVertexColors = true;
  7756. this.applyFog = true;
  7757. this.computeBonesUsingShaders = true;
  7758. this.scalingDeterminant = 1;
  7759. this.numBoneInfluencers = 4;
  7760. this.useOctreeForRenderingSelection = true;
  7761. this.useOctreeForPicking = true;
  7762. this.useOctreeForCollisions = true;
  7763. this.layerMask = 0x0FFFFFFF;
  7764. this.alwaysSelectAsActiveMesh = false;
  7765. // Physics
  7766. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7767. // Collisions
  7768. this._checkCollisions = false;
  7769. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7770. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7771. this._collider = new BABYLON.Collider();
  7772. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7773. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7774. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7775. // Edges
  7776. this.edgesWidth = 1;
  7777. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7778. // Cache
  7779. this._localWorld = BABYLON.Matrix.Zero();
  7780. this._worldMatrix = BABYLON.Matrix.Zero();
  7781. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7782. this._absolutePosition = BABYLON.Vector3.Zero();
  7783. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7784. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7785. this._isDirty = false;
  7786. this._pivotMatrix = BABYLON.Matrix.Identity();
  7787. this._isDisposed = false;
  7788. this._renderId = 0;
  7789. this._intersectionsInProgress = new Array();
  7790. this._onAfterWorldMatrixUpdate = new Array();
  7791. this._isWorldMatrixFrozen = false;
  7792. this._unIndexed = false;
  7793. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7794. if (collidedMesh === void 0) { collidedMesh = null; }
  7795. //TODO move this to the collision coordinator!
  7796. if (_this.getScene().workerCollisions)
  7797. newPosition.multiplyInPlace(_this._collider.radius);
  7798. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7799. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7800. _this.position.addInPlace(_this._diffPositionForCollisions);
  7801. }
  7802. if (_this.onCollide && collidedMesh) {
  7803. _this.onCollide(collidedMesh);
  7804. }
  7805. if (_this.onCollisionPositionChange) {
  7806. _this.onCollisionPositionChange(_this.position);
  7807. }
  7808. };
  7809. scene.addMesh(this);
  7810. }
  7811. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7812. get: function () {
  7813. return AbstractMesh._BILLBOARDMODE_NONE;
  7814. },
  7815. enumerable: true,
  7816. configurable: true
  7817. });
  7818. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7819. get: function () {
  7820. return AbstractMesh._BILLBOARDMODE_X;
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7826. get: function () {
  7827. return AbstractMesh._BILLBOARDMODE_Y;
  7828. },
  7829. enumerable: true,
  7830. configurable: true
  7831. });
  7832. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7833. get: function () {
  7834. return AbstractMesh._BILLBOARDMODE_Z;
  7835. },
  7836. enumerable: true,
  7837. configurable: true
  7838. });
  7839. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7840. get: function () {
  7841. return AbstractMesh._BILLBOARDMODE_ALL;
  7842. },
  7843. enumerable: true,
  7844. configurable: true
  7845. });
  7846. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7847. get: function () {
  7848. return this._skeleton;
  7849. },
  7850. set: function (value) {
  7851. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7852. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7853. }
  7854. if (value && value.needInitialSkinMatrix) {
  7855. value._registerMeshWithPoseMatrix(this);
  7856. }
  7857. this._skeleton = value;
  7858. if (!this._skeleton) {
  7859. this._bonesTransformMatrices = null;
  7860. }
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. // Methods
  7866. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7867. this._poseMatrix.copyFrom(matrix);
  7868. };
  7869. AbstractMesh.prototype.getPoseMatrix = function () {
  7870. return this._poseMatrix;
  7871. };
  7872. AbstractMesh.prototype.disableEdgesRendering = function () {
  7873. if (this._edgesRenderer !== undefined) {
  7874. this._edgesRenderer.dispose();
  7875. this._edgesRenderer = undefined;
  7876. }
  7877. };
  7878. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7879. if (epsilon === void 0) { epsilon = 0.95; }
  7880. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7881. this.disableEdgesRendering();
  7882. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7883. };
  7884. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7885. get: function () {
  7886. return false;
  7887. },
  7888. enumerable: true,
  7889. configurable: true
  7890. });
  7891. AbstractMesh.prototype.getLOD = function (camera) {
  7892. return this;
  7893. };
  7894. AbstractMesh.prototype.getTotalVertices = function () {
  7895. return 0;
  7896. };
  7897. AbstractMesh.prototype.getIndices = function () {
  7898. return null;
  7899. };
  7900. AbstractMesh.prototype.getVerticesData = function (kind) {
  7901. return null;
  7902. };
  7903. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7904. return false;
  7905. };
  7906. AbstractMesh.prototype.getBoundingInfo = function () {
  7907. if (this._masterMesh) {
  7908. return this._masterMesh.getBoundingInfo();
  7909. }
  7910. if (!this._boundingInfo) {
  7911. this._updateBoundingInfo();
  7912. }
  7913. return this._boundingInfo;
  7914. };
  7915. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7916. get: function () {
  7917. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. AbstractMesh.prototype._preActivate = function () {
  7923. };
  7924. AbstractMesh.prototype._activate = function (renderId) {
  7925. this._renderId = renderId;
  7926. };
  7927. AbstractMesh.prototype.getWorldMatrix = function () {
  7928. if (this._masterMesh) {
  7929. return this._masterMesh.getWorldMatrix();
  7930. }
  7931. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7932. this.computeWorldMatrix();
  7933. }
  7934. return this._worldMatrix;
  7935. };
  7936. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7937. get: function () {
  7938. return this._worldMatrix;
  7939. },
  7940. enumerable: true,
  7941. configurable: true
  7942. });
  7943. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7944. get: function () {
  7945. return this._absolutePosition;
  7946. },
  7947. enumerable: true,
  7948. configurable: true
  7949. });
  7950. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7951. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7952. this.computeWorldMatrix(true);
  7953. this._isWorldMatrixFrozen = true;
  7954. };
  7955. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7956. this._isWorldMatrixFrozen = false;
  7957. this.computeWorldMatrix(true);
  7958. };
  7959. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7960. get: function () {
  7961. return this._isWorldMatrixFrozen;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7967. axis.normalize();
  7968. if (!this.rotationQuaternion) {
  7969. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7970. this.rotation = BABYLON.Vector3.Zero();
  7971. }
  7972. var rotationQuaternion;
  7973. if (!space || space === BABYLON.Space.LOCAL) {
  7974. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7975. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7976. }
  7977. else {
  7978. if (this.parent) {
  7979. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7980. invertParentWorldMatrix.invert();
  7981. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7982. }
  7983. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7984. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7985. }
  7986. };
  7987. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7988. var displacementVector = axis.scale(distance);
  7989. if (!space || space === BABYLON.Space.LOCAL) {
  7990. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7991. this.setPositionWithLocalVector(tempV3);
  7992. }
  7993. else {
  7994. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7995. }
  7996. };
  7997. AbstractMesh.prototype.getAbsolutePosition = function () {
  7998. this.computeWorldMatrix();
  7999. return this._absolutePosition;
  8000. };
  8001. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8002. if (!absolutePosition) {
  8003. return;
  8004. }
  8005. var absolutePositionX;
  8006. var absolutePositionY;
  8007. var absolutePositionZ;
  8008. if (absolutePosition.x === undefined) {
  8009. if (arguments.length < 3) {
  8010. return;
  8011. }
  8012. absolutePositionX = arguments[0];
  8013. absolutePositionY = arguments[1];
  8014. absolutePositionZ = arguments[2];
  8015. }
  8016. else {
  8017. absolutePositionX = absolutePosition.x;
  8018. absolutePositionY = absolutePosition.y;
  8019. absolutePositionZ = absolutePosition.z;
  8020. }
  8021. if (this.parent) {
  8022. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8023. invertParentWorldMatrix.invert();
  8024. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8025. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8026. }
  8027. else {
  8028. this.position.x = absolutePositionX;
  8029. this.position.y = absolutePositionY;
  8030. this.position.z = absolutePositionZ;
  8031. }
  8032. };
  8033. // ================================== Point of View Movement =================================
  8034. /**
  8035. * Perform relative position change from the point of view of behind the front of the mesh.
  8036. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8037. * Supports definition of mesh facing forward or backward.
  8038. * @param {number} amountRight
  8039. * @param {number} amountUp
  8040. * @param {number} amountForward
  8041. */
  8042. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8043. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8044. };
  8045. /**
  8046. * Calculate relative position change from the point of view of behind the front of the mesh.
  8047. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8048. * Supports definition of mesh facing forward or backward.
  8049. * @param {number} amountRight
  8050. * @param {number} amountUp
  8051. * @param {number} amountForward
  8052. */
  8053. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8054. var rotMatrix = new BABYLON.Matrix();
  8055. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8056. rotQuaternion.toRotationMatrix(rotMatrix);
  8057. var translationDelta = BABYLON.Vector3.Zero();
  8058. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8059. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8060. return translationDelta;
  8061. };
  8062. // ================================== Point of View Rotation =================================
  8063. /**
  8064. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8065. * Supports definition of mesh facing forward or backward.
  8066. * @param {number} flipBack
  8067. * @param {number} twirlClockwise
  8068. * @param {number} tiltRight
  8069. */
  8070. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8071. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8072. };
  8073. /**
  8074. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8075. * Supports definition of mesh facing forward or backward.
  8076. * @param {number} flipBack
  8077. * @param {number} twirlClockwise
  8078. * @param {number} tiltRight
  8079. */
  8080. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8081. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8082. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8083. };
  8084. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8085. this._pivotMatrix = matrix;
  8086. this._cache.pivotMatrixUpdated = true;
  8087. };
  8088. AbstractMesh.prototype.getPivotMatrix = function () {
  8089. return this._pivotMatrix;
  8090. };
  8091. AbstractMesh.prototype._isSynchronized = function () {
  8092. if (this._isDirty) {
  8093. return false;
  8094. }
  8095. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8096. return false;
  8097. if (this._cache.pivotMatrixUpdated) {
  8098. return false;
  8099. }
  8100. if (this.infiniteDistance) {
  8101. return false;
  8102. }
  8103. if (!this._cache.position.equals(this.position))
  8104. return false;
  8105. if (this.rotationQuaternion) {
  8106. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8107. return false;
  8108. }
  8109. else {
  8110. if (!this._cache.rotation.equals(this.rotation))
  8111. return false;
  8112. }
  8113. if (!this._cache.scaling.equals(this.scaling))
  8114. return false;
  8115. return true;
  8116. };
  8117. AbstractMesh.prototype._initCache = function () {
  8118. _super.prototype._initCache.call(this);
  8119. this._cache.localMatrixUpdated = false;
  8120. this._cache.position = BABYLON.Vector3.Zero();
  8121. this._cache.scaling = BABYLON.Vector3.Zero();
  8122. this._cache.rotation = BABYLON.Vector3.Zero();
  8123. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8124. this._cache.billboardMode = -1;
  8125. };
  8126. AbstractMesh.prototype.markAsDirty = function (property) {
  8127. if (property === "rotation") {
  8128. this.rotationQuaternion = null;
  8129. }
  8130. this._currentRenderId = Number.MAX_VALUE;
  8131. this._isDirty = true;
  8132. };
  8133. AbstractMesh.prototype._updateBoundingInfo = function () {
  8134. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8135. this._boundingInfo.update(this.worldMatrixFromCache);
  8136. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8137. };
  8138. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8139. if (!this.subMeshes) {
  8140. return;
  8141. }
  8142. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8143. var subMesh = this.subMeshes[subIndex];
  8144. if (!subMesh.IsGlobal) {
  8145. subMesh.updateBoundingInfo(matrix);
  8146. }
  8147. }
  8148. };
  8149. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8150. if (this._isWorldMatrixFrozen) {
  8151. return this._worldMatrix;
  8152. }
  8153. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8154. this._currentRenderId = this.getScene().getRenderId();
  8155. return this._worldMatrix;
  8156. }
  8157. this._cache.position.copyFrom(this.position);
  8158. this._cache.scaling.copyFrom(this.scaling);
  8159. this._cache.pivotMatrixUpdated = false;
  8160. this._cache.billboardMode = this.billboardMode;
  8161. this._currentRenderId = this.getScene().getRenderId();
  8162. this._isDirty = false;
  8163. // Scaling
  8164. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8165. // Rotation
  8166. if (this.rotationQuaternion) {
  8167. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8168. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8169. }
  8170. else {
  8171. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8172. this._cache.rotation.copyFrom(this.rotation);
  8173. }
  8174. // Translation
  8175. if (this.infiniteDistance && !this.parent) {
  8176. var camera = this.getScene().activeCamera;
  8177. if (camera) {
  8178. var cameraWorldMatrix = camera.getWorldMatrix();
  8179. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8180. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8181. }
  8182. }
  8183. else {
  8184. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8185. }
  8186. // Composing transformations
  8187. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8188. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8189. // Billboarding
  8190. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8191. var localPosition = this.position.clone();
  8192. var zero = this.getScene().activeCamera.globalPosition.clone();
  8193. if (this.parent && this.parent.position) {
  8194. localPosition.addInPlace(this.parent.position);
  8195. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8196. }
  8197. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8198. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8199. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8200. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8201. zero.y = localPosition.y + 0.001;
  8202. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8203. zero.z = localPosition.z + 0.001;
  8204. }
  8205. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8206. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8207. BABYLON.Tmp.Matrix[3].invert();
  8208. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8209. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8210. }
  8211. // Local world
  8212. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8213. // Parent
  8214. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8215. this._markSyncedWithParent();
  8216. if (this._meshToBoneReferal) {
  8217. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8218. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8219. }
  8220. else {
  8221. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8222. }
  8223. }
  8224. else {
  8225. this._worldMatrix.copyFrom(this._localWorld);
  8226. }
  8227. // Bounding info
  8228. this._updateBoundingInfo();
  8229. // Absolute position
  8230. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8231. // Callbacks
  8232. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8233. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8234. }
  8235. if (!this._poseMatrix) {
  8236. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8237. }
  8238. return this._worldMatrix;
  8239. };
  8240. /**
  8241. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8242. * @param func: callback function to add
  8243. */
  8244. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8245. this._onAfterWorldMatrixUpdate.push(func);
  8246. };
  8247. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8248. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8249. if (index > -1) {
  8250. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8251. }
  8252. };
  8253. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8254. this.computeWorldMatrix();
  8255. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8256. };
  8257. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8258. this.computeWorldMatrix();
  8259. var invLocalWorldMatrix = this._localWorld.clone();
  8260. invLocalWorldMatrix.invert();
  8261. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8262. };
  8263. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8264. this.computeWorldMatrix(true);
  8265. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8266. };
  8267. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8268. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8269. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8270. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8271. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8272. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8273. /// <returns>Mesh oriented towards targetMesh</returns>
  8274. yawCor = yawCor || 0; // default to zero if undefined
  8275. pitchCor = pitchCor || 0;
  8276. rollCor = rollCor || 0;
  8277. var dv = targetPoint.subtract(this.position);
  8278. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8279. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8280. var pitch = Math.atan2(dv.y, len);
  8281. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8282. };
  8283. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8284. this._meshToBoneReferal = affectedMesh;
  8285. this.parent = bone;
  8286. if (bone.getWorldMatrix().determinant() < 0) {
  8287. this.scalingDeterminant *= -1;
  8288. }
  8289. };
  8290. AbstractMesh.prototype.detachFromBone = function () {
  8291. if (this.parent.getWorldMatrix().determinant() < 0) {
  8292. this.scalingDeterminant *= -1;
  8293. }
  8294. this._meshToBoneReferal = null;
  8295. this.parent = null;
  8296. };
  8297. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8298. return this._boundingInfo.isInFrustum(frustumPlanes);
  8299. };
  8300. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8301. if (!camera) {
  8302. camera = this.getScene().activeCamera;
  8303. }
  8304. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8305. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8306. return false;
  8307. }
  8308. return true;
  8309. };
  8310. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8311. if (!this._boundingInfo || !mesh._boundingInfo) {
  8312. return false;
  8313. }
  8314. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8315. };
  8316. AbstractMesh.prototype.intersectsPoint = function (point) {
  8317. if (!this._boundingInfo) {
  8318. return false;
  8319. }
  8320. return this._boundingInfo.intersectsPoint(point);
  8321. };
  8322. // Physics
  8323. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8324. var physicsEngine = this.getScene().getPhysicsEngine();
  8325. if (!physicsEngine) {
  8326. return null;
  8327. }
  8328. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8329. if (impostor.impostor) {
  8330. // Old API
  8331. options = impostor;
  8332. impostor = impostor.impostor;
  8333. }
  8334. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8335. physicsEngine._unregisterMesh(this);
  8336. return null;
  8337. }
  8338. if (!options) {
  8339. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8340. }
  8341. else {
  8342. if (!options.mass && options.mass !== 0)
  8343. options.mass = 0;
  8344. if (!options.friction && options.friction !== 0)
  8345. options.friction = 0.2;
  8346. if (!options.restitution && options.restitution !== 0)
  8347. options.restitution = 0.2;
  8348. }
  8349. this._physicImpostor = impostor;
  8350. this._physicsMass = options.mass;
  8351. this._physicsFriction = options.friction;
  8352. this._physicRestitution = options.restitution;
  8353. return physicsEngine._registerMesh(this, impostor, options);
  8354. };
  8355. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8356. if (!this._physicImpostor) {
  8357. return BABYLON.PhysicsEngine.NoImpostor;
  8358. }
  8359. return this._physicImpostor;
  8360. };
  8361. AbstractMesh.prototype.getPhysicsMass = function () {
  8362. if (!this._physicsMass) {
  8363. return 0;
  8364. }
  8365. return this._physicsMass;
  8366. };
  8367. AbstractMesh.prototype.getPhysicsFriction = function () {
  8368. if (!this._physicsFriction) {
  8369. return 0;
  8370. }
  8371. return this._physicsFriction;
  8372. };
  8373. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8374. if (!this._physicRestitution) {
  8375. return 0;
  8376. }
  8377. return this._physicRestitution;
  8378. };
  8379. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8380. if (!camera) {
  8381. camera = this.getScene().activeCamera;
  8382. }
  8383. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8384. };
  8385. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8386. if (!camera) {
  8387. camera = this.getScene().activeCamera;
  8388. }
  8389. return this.absolutePosition.subtract(camera.position).length();
  8390. };
  8391. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8392. if (!this._physicImpostor) {
  8393. return;
  8394. }
  8395. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8396. };
  8397. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8398. if (!this._physicImpostor) {
  8399. return;
  8400. }
  8401. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8402. };
  8403. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8404. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8405. this.updatePhysicsBody();
  8406. };
  8407. AbstractMesh.prototype.updatePhysicsBody = function () {
  8408. if (!this._physicImpostor) {
  8409. return;
  8410. }
  8411. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8412. };
  8413. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8414. // Collisions
  8415. get: function () {
  8416. return this._checkCollisions;
  8417. },
  8418. set: function (collisionEnabled) {
  8419. this._checkCollisions = collisionEnabled;
  8420. if (this.getScene().workerCollisions) {
  8421. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8422. }
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8428. var globalPosition = this.getAbsolutePosition();
  8429. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8430. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8431. this._collider.radius = this.ellipsoid;
  8432. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8433. };
  8434. // Submeshes octree
  8435. /**
  8436. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8437. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8438. */
  8439. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8440. if (maxCapacity === void 0) { maxCapacity = 64; }
  8441. if (maxDepth === void 0) { maxDepth = 2; }
  8442. if (!this._submeshesOctree) {
  8443. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8444. }
  8445. this.computeWorldMatrix(true);
  8446. // Update octree
  8447. var bbox = this.getBoundingInfo().boundingBox;
  8448. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8449. return this._submeshesOctree;
  8450. };
  8451. // Collisions
  8452. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8453. this._generatePointsArray();
  8454. // Transformation
  8455. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8456. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8457. subMesh._lastColliderWorldVertices = [];
  8458. subMesh._trianglePlanes = [];
  8459. var start = subMesh.verticesStart;
  8460. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8461. for (var i = start; i < end; i++) {
  8462. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8463. }
  8464. }
  8465. // Collide
  8466. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8467. if (collider.collisionFound) {
  8468. collider.collidedMesh = this;
  8469. }
  8470. };
  8471. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8472. var subMeshes;
  8473. var len;
  8474. // Octrees
  8475. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8476. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8477. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8478. len = intersections.length;
  8479. subMeshes = intersections.data;
  8480. }
  8481. else {
  8482. subMeshes = this.subMeshes;
  8483. len = subMeshes.length;
  8484. }
  8485. for (var index = 0; index < len; index++) {
  8486. var subMesh = subMeshes[index];
  8487. // Bounding test
  8488. if (len > 1 && !subMesh._checkCollision(collider))
  8489. continue;
  8490. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8491. }
  8492. };
  8493. AbstractMesh.prototype._checkCollision = function (collider) {
  8494. // Bounding box test
  8495. if (!this._boundingInfo._checkCollision(collider))
  8496. return;
  8497. // Transformation matrix
  8498. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8499. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8500. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8501. };
  8502. // Picking
  8503. AbstractMesh.prototype._generatePointsArray = function () {
  8504. return false;
  8505. };
  8506. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8507. var pickingInfo = new BABYLON.PickingInfo();
  8508. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8509. return pickingInfo;
  8510. }
  8511. if (!this._generatePointsArray()) {
  8512. return pickingInfo;
  8513. }
  8514. var intersectInfo = null;
  8515. // Octrees
  8516. var subMeshes;
  8517. var len;
  8518. if (this._submeshesOctree && this.useOctreeForPicking) {
  8519. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8520. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8521. len = intersections.length;
  8522. subMeshes = intersections.data;
  8523. }
  8524. else {
  8525. subMeshes = this.subMeshes;
  8526. len = subMeshes.length;
  8527. }
  8528. for (var index = 0; index < len; index++) {
  8529. var subMesh = subMeshes[index];
  8530. // Bounding test
  8531. if (len > 1 && !subMesh.canIntersects(ray))
  8532. continue;
  8533. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8534. if (currentIntersectInfo) {
  8535. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8536. intersectInfo = currentIntersectInfo;
  8537. intersectInfo.subMeshId = index;
  8538. if (fastCheck) {
  8539. break;
  8540. }
  8541. }
  8542. }
  8543. }
  8544. if (intersectInfo) {
  8545. // Get picked point
  8546. var world = this.getWorldMatrix();
  8547. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8548. var direction = ray.direction.clone();
  8549. direction = direction.scale(intersectInfo.distance);
  8550. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8551. var pickedPoint = worldOrigin.add(worldDirection);
  8552. // Return result
  8553. pickingInfo.hit = true;
  8554. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8555. pickingInfo.pickedPoint = pickedPoint;
  8556. pickingInfo.pickedMesh = this;
  8557. pickingInfo.bu = intersectInfo.bu;
  8558. pickingInfo.bv = intersectInfo.bv;
  8559. pickingInfo.faceId = intersectInfo.faceId;
  8560. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8561. return pickingInfo;
  8562. }
  8563. return pickingInfo;
  8564. };
  8565. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8566. return null;
  8567. };
  8568. AbstractMesh.prototype.releaseSubMeshes = function () {
  8569. if (this.subMeshes) {
  8570. while (this.subMeshes.length) {
  8571. this.subMeshes[0].dispose();
  8572. }
  8573. }
  8574. else {
  8575. this.subMeshes = new Array();
  8576. }
  8577. };
  8578. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8579. var index;
  8580. // Skeleton
  8581. this.skeleton = null;
  8582. // Animations
  8583. this.getScene().stopAnimation(this);
  8584. // Physics
  8585. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8586. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8587. }
  8588. // Intersections in progress
  8589. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8590. var other = this._intersectionsInProgress[index];
  8591. var pos = other._intersectionsInProgress.indexOf(this);
  8592. other._intersectionsInProgress.splice(pos, 1);
  8593. }
  8594. this._intersectionsInProgress = [];
  8595. // Edges
  8596. if (this._edgesRenderer) {
  8597. this._edgesRenderer.dispose();
  8598. this._edgesRenderer = null;
  8599. }
  8600. // SubMeshes
  8601. this.releaseSubMeshes();
  8602. // Remove from scene
  8603. this.getScene().removeMesh(this);
  8604. if (!doNotRecurse) {
  8605. // Particles
  8606. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8607. if (this.getScene().particleSystems[index].emitter === this) {
  8608. this.getScene().particleSystems[index].dispose();
  8609. index--;
  8610. }
  8611. }
  8612. // Children
  8613. var objects = this.getScene().meshes.slice(0);
  8614. for (index = 0; index < objects.length; index++) {
  8615. if (objects[index].parent === this) {
  8616. objects[index].dispose();
  8617. }
  8618. }
  8619. }
  8620. else {
  8621. for (index = 0; index < this.getScene().meshes.length; index++) {
  8622. var obj = this.getScene().meshes[index];
  8623. if (obj.parent === this) {
  8624. obj.parent = null;
  8625. obj.computeWorldMatrix(true);
  8626. }
  8627. }
  8628. }
  8629. this._onAfterWorldMatrixUpdate = [];
  8630. this._isDisposed = true;
  8631. // Callback
  8632. if (this.onDispose) {
  8633. this.onDispose();
  8634. }
  8635. };
  8636. // Statics
  8637. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8638. AbstractMesh._BILLBOARDMODE_X = 1;
  8639. AbstractMesh._BILLBOARDMODE_Y = 2;
  8640. AbstractMesh._BILLBOARDMODE_Z = 4;
  8641. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8642. return AbstractMesh;
  8643. })(BABYLON.Node);
  8644. BABYLON.AbstractMesh = AbstractMesh;
  8645. })(BABYLON || (BABYLON = {}));
  8646. var BABYLON;
  8647. (function (BABYLON) {
  8648. var Light = (function (_super) {
  8649. __extends(Light, _super);
  8650. function Light(name, scene) {
  8651. _super.call(this, name, scene);
  8652. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8653. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8654. this.intensity = 1.0;
  8655. this.range = Number.MAX_VALUE;
  8656. this.includeOnlyWithLayerMask = 0;
  8657. this.includedOnlyMeshes = new Array();
  8658. this.excludedMeshes = new Array();
  8659. this.excludeWithLayerMask = 0;
  8660. this._excludedMeshesIds = new Array();
  8661. this._includedOnlyMeshesIds = new Array();
  8662. scene.addLight(this);
  8663. }
  8664. Light.prototype.getShadowGenerator = function () {
  8665. return this._shadowGenerator;
  8666. };
  8667. Light.prototype.getAbsolutePosition = function () {
  8668. return BABYLON.Vector3.Zero();
  8669. };
  8670. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8671. };
  8672. Light.prototype._getWorldMatrix = function () {
  8673. return BABYLON.Matrix.Identity();
  8674. };
  8675. Light.prototype.canAffectMesh = function (mesh) {
  8676. if (!mesh) {
  8677. return true;
  8678. }
  8679. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8680. return false;
  8681. }
  8682. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8683. return false;
  8684. }
  8685. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8686. return false;
  8687. }
  8688. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8689. return false;
  8690. }
  8691. return true;
  8692. };
  8693. Light.prototype.getWorldMatrix = function () {
  8694. this._currentRenderId = this.getScene().getRenderId();
  8695. var worldMatrix = this._getWorldMatrix();
  8696. if (this.parent && this.parent.getWorldMatrix) {
  8697. if (!this._parentedWorldMatrix) {
  8698. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8699. }
  8700. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8701. this._markSyncedWithParent();
  8702. return this._parentedWorldMatrix;
  8703. }
  8704. return worldMatrix;
  8705. };
  8706. Light.prototype.dispose = function () {
  8707. if (this._shadowGenerator) {
  8708. this._shadowGenerator.dispose();
  8709. this._shadowGenerator = null;
  8710. }
  8711. // Animations
  8712. this.getScene().stopAnimation(this);
  8713. // Remove from scene
  8714. this.getScene().removeLight(this);
  8715. };
  8716. Light.prototype.serialize = function () {
  8717. var serializationObject = {};
  8718. serializationObject.name = this.name;
  8719. serializationObject.id = this.id;
  8720. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8721. if (this.intensity) {
  8722. serializationObject.intensity = this.intensity;
  8723. }
  8724. // Parent
  8725. if (this.parent) {
  8726. serializationObject.parentId = this.parent.id;
  8727. }
  8728. serializationObject.range = this.range;
  8729. serializationObject.diffuse = this.diffuse.asArray();
  8730. serializationObject.specular = this.specular.asArray();
  8731. return serializationObject;
  8732. };
  8733. Light.Parse = function (parsedLight, scene) {
  8734. var light;
  8735. switch (parsedLight.type) {
  8736. case 0:
  8737. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8738. break;
  8739. case 1:
  8740. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8741. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8742. break;
  8743. case 2:
  8744. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8745. break;
  8746. case 3:
  8747. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8748. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8749. break;
  8750. }
  8751. light.id = parsedLight.id;
  8752. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8753. if (parsedLight.intensity !== undefined) {
  8754. light.intensity = parsedLight.intensity;
  8755. }
  8756. if (parsedLight.range) {
  8757. light.range = parsedLight.range;
  8758. }
  8759. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8760. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8761. if (parsedLight.excludedMeshesIds) {
  8762. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8763. }
  8764. // Parent
  8765. if (parsedLight.parentId) {
  8766. light._waitingParentId = parsedLight.parentId;
  8767. }
  8768. if (parsedLight.includedOnlyMeshesIds) {
  8769. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8770. }
  8771. // Animations
  8772. if (parsedLight.animations) {
  8773. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8774. var parsedAnimation = parsedLight.animations[animationIndex];
  8775. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8776. }
  8777. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8778. }
  8779. if (parsedLight.autoAnimate) {
  8780. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8781. }
  8782. return light;
  8783. };
  8784. return Light;
  8785. })(BABYLON.Node);
  8786. BABYLON.Light = Light;
  8787. })(BABYLON || (BABYLON = {}));
  8788. var BABYLON;
  8789. (function (BABYLON) {
  8790. var PointLight = (function (_super) {
  8791. __extends(PointLight, _super);
  8792. function PointLight(name, position, scene) {
  8793. _super.call(this, name, scene);
  8794. this.position = position;
  8795. }
  8796. PointLight.prototype.getAbsolutePosition = function () {
  8797. return this.transformedPosition ? this.transformedPosition : this.position;
  8798. };
  8799. PointLight.prototype.computeTransformedPosition = function () {
  8800. if (this.parent && this.parent.getWorldMatrix) {
  8801. if (!this.transformedPosition) {
  8802. this.transformedPosition = BABYLON.Vector3.Zero();
  8803. }
  8804. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8805. return true;
  8806. }
  8807. return false;
  8808. };
  8809. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8810. if (this.parent && this.parent.getWorldMatrix) {
  8811. this.computeTransformedPosition();
  8812. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8813. return;
  8814. }
  8815. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8816. };
  8817. PointLight.prototype.needCube = function () {
  8818. return true;
  8819. };
  8820. PointLight.prototype.supportsVSM = function () {
  8821. return false;
  8822. };
  8823. PointLight.prototype.needRefreshPerFrame = function () {
  8824. return false;
  8825. };
  8826. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8827. switch (faceIndex) {
  8828. case 0:
  8829. return new BABYLON.Vector3(1, 0, 0);
  8830. case 1:
  8831. return new BABYLON.Vector3(-1, 0, 0);
  8832. case 2:
  8833. return new BABYLON.Vector3(0, -1, 0);
  8834. case 3:
  8835. return new BABYLON.Vector3(0, 1, 0);
  8836. case 4:
  8837. return new BABYLON.Vector3(0, 0, 1);
  8838. case 5:
  8839. return new BABYLON.Vector3(0, 0, -1);
  8840. }
  8841. return BABYLON.Vector3.Zero();
  8842. };
  8843. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8844. var activeCamera = this.getScene().activeCamera;
  8845. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8846. };
  8847. PointLight.prototype._getWorldMatrix = function () {
  8848. if (!this._worldMatrix) {
  8849. this._worldMatrix = BABYLON.Matrix.Identity();
  8850. }
  8851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8852. return this._worldMatrix;
  8853. };
  8854. PointLight.prototype.serialize = function () {
  8855. var serializationObject = _super.prototype.serialize.call(this);
  8856. serializationObject.type = 0;
  8857. serializationObject.position = this.position.asArray();
  8858. return serializationObject;
  8859. };
  8860. return PointLight;
  8861. })(BABYLON.Light);
  8862. BABYLON.PointLight = PointLight;
  8863. })(BABYLON || (BABYLON = {}));
  8864. var BABYLON;
  8865. (function (BABYLON) {
  8866. var SpotLight = (function (_super) {
  8867. __extends(SpotLight, _super);
  8868. function SpotLight(name, position, direction, angle, exponent, scene) {
  8869. _super.call(this, name, scene);
  8870. this.position = position;
  8871. this.direction = direction;
  8872. this.angle = angle;
  8873. this.exponent = exponent;
  8874. }
  8875. SpotLight.prototype.getAbsolutePosition = function () {
  8876. return this.transformedPosition ? this.transformedPosition : this.position;
  8877. };
  8878. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8879. var activeCamera = this.getScene().activeCamera;
  8880. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8881. };
  8882. SpotLight.prototype.needCube = function () {
  8883. return false;
  8884. };
  8885. SpotLight.prototype.supportsVSM = function () {
  8886. return true;
  8887. };
  8888. SpotLight.prototype.needRefreshPerFrame = function () {
  8889. return false;
  8890. };
  8891. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8892. return this.direction;
  8893. };
  8894. SpotLight.prototype.setDirectionToTarget = function (target) {
  8895. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8896. return this.direction;
  8897. };
  8898. SpotLight.prototype.computeTransformedPosition = function () {
  8899. if (this.parent && this.parent.getWorldMatrix) {
  8900. if (!this.transformedPosition) {
  8901. this.transformedPosition = BABYLON.Vector3.Zero();
  8902. }
  8903. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8904. return true;
  8905. }
  8906. return false;
  8907. };
  8908. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8909. var normalizeDirection;
  8910. if (this.parent && this.parent.getWorldMatrix) {
  8911. if (!this._transformedDirection) {
  8912. this._transformedDirection = BABYLON.Vector3.Zero();
  8913. }
  8914. this.computeTransformedPosition();
  8915. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8916. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8917. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8918. }
  8919. else {
  8920. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8921. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8922. }
  8923. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8924. };
  8925. SpotLight.prototype._getWorldMatrix = function () {
  8926. if (!this._worldMatrix) {
  8927. this._worldMatrix = BABYLON.Matrix.Identity();
  8928. }
  8929. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8930. return this._worldMatrix;
  8931. };
  8932. SpotLight.prototype.serialize = function () {
  8933. var serializationObject = _super.prototype.serialize.call(this);
  8934. serializationObject.type = 2;
  8935. serializationObject.position = this.position.asArray();
  8936. serializationObject.direction = this.position.asArray();
  8937. serializationObject.angle = this.angle;
  8938. serializationObject.exponent = this.exponent;
  8939. return serializationObject;
  8940. };
  8941. return SpotLight;
  8942. })(BABYLON.Light);
  8943. BABYLON.SpotLight = SpotLight;
  8944. })(BABYLON || (BABYLON = {}));
  8945. var BABYLON;
  8946. (function (BABYLON) {
  8947. var HemisphericLight = (function (_super) {
  8948. __extends(HemisphericLight, _super);
  8949. function HemisphericLight(name, direction, scene) {
  8950. _super.call(this, name, scene);
  8951. this.direction = direction;
  8952. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8953. }
  8954. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8955. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8956. return this.direction;
  8957. };
  8958. HemisphericLight.prototype.getShadowGenerator = function () {
  8959. return null;
  8960. };
  8961. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8962. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8963. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8964. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8965. };
  8966. HemisphericLight.prototype._getWorldMatrix = function () {
  8967. if (!this._worldMatrix) {
  8968. this._worldMatrix = BABYLON.Matrix.Identity();
  8969. }
  8970. return this._worldMatrix;
  8971. };
  8972. HemisphericLight.prototype.serialize = function () {
  8973. var serializationObject = _super.prototype.serialize.call(this);
  8974. serializationObject.type = 3;
  8975. serializationObject.direction = this.direction.asArray();
  8976. serializationObject.groundColor = this.groundColor.asArray();
  8977. return serializationObject;
  8978. };
  8979. return HemisphericLight;
  8980. })(BABYLON.Light);
  8981. BABYLON.HemisphericLight = HemisphericLight;
  8982. })(BABYLON || (BABYLON = {}));
  8983. var BABYLON;
  8984. (function (BABYLON) {
  8985. var DirectionalLight = (function (_super) {
  8986. __extends(DirectionalLight, _super);
  8987. function DirectionalLight(name, direction, scene) {
  8988. _super.call(this, name, scene);
  8989. this.direction = direction;
  8990. this.shadowOrthoScale = 0.5;
  8991. this.autoUpdateExtends = true;
  8992. // Cache
  8993. this._orthoLeft = Number.MAX_VALUE;
  8994. this._orthoRight = Number.MIN_VALUE;
  8995. this._orthoTop = Number.MIN_VALUE;
  8996. this._orthoBottom = Number.MAX_VALUE;
  8997. this.position = direction.scale(-1);
  8998. }
  8999. DirectionalLight.prototype.getAbsolutePosition = function () {
  9000. return this.transformedPosition ? this.transformedPosition : this.position;
  9001. };
  9002. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9003. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9004. return this.direction;
  9005. };
  9006. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9007. var activeCamera = this.getScene().activeCamera;
  9008. // Check extends
  9009. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9010. var tempVector3 = BABYLON.Vector3.Zero();
  9011. this._orthoLeft = Number.MAX_VALUE;
  9012. this._orthoRight = Number.MIN_VALUE;
  9013. this._orthoTop = Number.MIN_VALUE;
  9014. this._orthoBottom = Number.MAX_VALUE;
  9015. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9016. var mesh = renderList[meshIndex];
  9017. if (!mesh) {
  9018. continue;
  9019. }
  9020. var boundingInfo = mesh.getBoundingInfo();
  9021. if (!boundingInfo) {
  9022. continue;
  9023. }
  9024. var boundingBox = boundingInfo.boundingBox;
  9025. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9026. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9027. if (tempVector3.x < this._orthoLeft)
  9028. this._orthoLeft = tempVector3.x;
  9029. if (tempVector3.y < this._orthoBottom)
  9030. this._orthoBottom = tempVector3.y;
  9031. if (tempVector3.x > this._orthoRight)
  9032. this._orthoRight = tempVector3.x;
  9033. if (tempVector3.y > this._orthoTop)
  9034. this._orthoTop = tempVector3.y;
  9035. }
  9036. }
  9037. }
  9038. var xOffset = this._orthoRight - this._orthoLeft;
  9039. var yOffset = this._orthoTop - this._orthoBottom;
  9040. 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);
  9041. };
  9042. DirectionalLight.prototype.supportsVSM = function () {
  9043. return true;
  9044. };
  9045. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9046. return true;
  9047. };
  9048. DirectionalLight.prototype.needCube = function () {
  9049. return false;
  9050. };
  9051. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9052. return this.direction;
  9053. };
  9054. DirectionalLight.prototype.computeTransformedPosition = function () {
  9055. if (this.parent && this.parent.getWorldMatrix) {
  9056. if (!this.transformedPosition) {
  9057. this.transformedPosition = BABYLON.Vector3.Zero();
  9058. }
  9059. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9060. return true;
  9061. }
  9062. return false;
  9063. };
  9064. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9065. if (this.parent && this.parent.getWorldMatrix) {
  9066. if (!this._transformedDirection) {
  9067. this._transformedDirection = BABYLON.Vector3.Zero();
  9068. }
  9069. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9070. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9071. return;
  9072. }
  9073. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9074. };
  9075. DirectionalLight.prototype._getWorldMatrix = function () {
  9076. if (!this._worldMatrix) {
  9077. this._worldMatrix = BABYLON.Matrix.Identity();
  9078. }
  9079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9080. return this._worldMatrix;
  9081. };
  9082. DirectionalLight.prototype.serialize = function () {
  9083. var serializationObject = _super.prototype.serialize.call(this);
  9084. serializationObject.type = 1;
  9085. serializationObject.position = this.position.asArray();
  9086. serializationObject.direction = this.direction.asArray();
  9087. return serializationObject;
  9088. };
  9089. return DirectionalLight;
  9090. })(BABYLON.Light);
  9091. BABYLON.DirectionalLight = DirectionalLight;
  9092. })(BABYLON || (BABYLON = {}));
  9093. var BABYLON;
  9094. (function (BABYLON) {
  9095. var ShadowGenerator = (function () {
  9096. function ShadowGenerator(mapSize, light) {
  9097. var _this = this;
  9098. // Members
  9099. this._filter = ShadowGenerator.FILTER_NONE;
  9100. this.blurScale = 2;
  9101. this._blurBoxOffset = 0;
  9102. this._bias = 0.00005;
  9103. this._lightDirection = BABYLON.Vector3.Zero();
  9104. this.forceBackFacesOnly = false;
  9105. this._darkness = 0;
  9106. this._transparencyShadow = false;
  9107. this._viewMatrix = BABYLON.Matrix.Zero();
  9108. this._projectionMatrix = BABYLON.Matrix.Zero();
  9109. this._transformMatrix = BABYLON.Matrix.Zero();
  9110. this._worldViewProjection = BABYLON.Matrix.Zero();
  9111. this._currentFaceIndex = 0;
  9112. this._currentFaceIndexCache = 0;
  9113. this._light = light;
  9114. this._scene = light.getScene();
  9115. this._mapSize = mapSize;
  9116. light._shadowGenerator = this;
  9117. // Render target
  9118. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9119. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9120. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9121. this._shadowMap.anisotropicFilteringLevel = 1;
  9122. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9123. this._shadowMap.renderParticles = false;
  9124. this._shadowMap.onBeforeRender = function (faceIndex) {
  9125. _this._currentFaceIndex = faceIndex;
  9126. };
  9127. this._shadowMap.onAfterUnbind = function () {
  9128. if (!_this.useBlurVarianceShadowMap) {
  9129. return;
  9130. }
  9131. if (!_this._shadowMap2) {
  9132. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9133. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9134. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9135. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9136. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9137. _this._downSamplePostprocess.onApply = function (effect) {
  9138. effect.setTexture("textureSampler", _this._shadowMap);
  9139. };
  9140. _this.blurBoxOffset = 1;
  9141. }
  9142. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9143. };
  9144. // Custom render function
  9145. var renderSubMesh = function (subMesh) {
  9146. var mesh = subMesh.getRenderingMesh();
  9147. var scene = _this._scene;
  9148. var engine = scene.getEngine();
  9149. // Culling
  9150. engine.setState(subMesh.getMaterial().backFaceCulling);
  9151. // Managing instances
  9152. var batch = mesh._getInstancesRenderList(subMesh._id);
  9153. if (batch.mustReturn) {
  9154. return;
  9155. }
  9156. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9157. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9158. engine.enableEffect(_this._effect);
  9159. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9160. var material = subMesh.getMaterial();
  9161. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9162. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9163. if (_this.getLight().needCube()) {
  9164. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9165. }
  9166. // Alpha test
  9167. if (material && material.needAlphaTesting()) {
  9168. var alphaTexture = material.getAlphaTestTexture();
  9169. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9170. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9171. }
  9172. // Bones
  9173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9174. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9175. }
  9176. if (_this.forceBackFacesOnly) {
  9177. engine.setState(true, 0, false, true);
  9178. }
  9179. // Draw
  9180. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9181. if (_this.forceBackFacesOnly) {
  9182. engine.setState(true, 0, false, false);
  9183. }
  9184. }
  9185. else {
  9186. // Need to reset refresh rate of the shadowMap
  9187. _this._shadowMap.resetRefreshCounter();
  9188. }
  9189. };
  9190. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9191. var index;
  9192. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9193. renderSubMesh(opaqueSubMeshes.data[index]);
  9194. }
  9195. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9196. renderSubMesh(alphaTestSubMeshes.data[index]);
  9197. }
  9198. if (_this._transparencyShadow) {
  9199. for (index = 0; index < transparentSubMeshes.length; index++) {
  9200. renderSubMesh(transparentSubMeshes.data[index]);
  9201. }
  9202. }
  9203. };
  9204. this._shadowMap.onClear = function (engine) {
  9205. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9206. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9207. }
  9208. else {
  9209. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9210. }
  9211. };
  9212. }
  9213. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9214. // Static
  9215. get: function () {
  9216. return ShadowGenerator._FILTER_NONE;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9222. get: function () {
  9223. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9229. get: function () {
  9230. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9236. get: function () {
  9237. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9238. },
  9239. enumerable: true,
  9240. configurable: true
  9241. });
  9242. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9243. get: function () {
  9244. return this._bias;
  9245. },
  9246. set: function (bias) {
  9247. this._bias = bias;
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9253. get: function () {
  9254. return this._blurBoxOffset;
  9255. },
  9256. set: function (value) {
  9257. var _this = this;
  9258. if (this._blurBoxOffset === value) {
  9259. return;
  9260. }
  9261. this._blurBoxOffset = value;
  9262. if (this._boxBlurPostprocess) {
  9263. this._boxBlurPostprocess.dispose();
  9264. }
  9265. 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);
  9266. this._boxBlurPostprocess.onApply = function (effect) {
  9267. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9268. };
  9269. },
  9270. enumerable: true,
  9271. configurable: true
  9272. });
  9273. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9274. get: function () {
  9275. return this._filter;
  9276. },
  9277. set: function (value) {
  9278. if (this._filter === value) {
  9279. return;
  9280. }
  9281. this._filter = value;
  9282. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9283. this._shadowMap.anisotropicFilteringLevel = 16;
  9284. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9285. }
  9286. else {
  9287. this._shadowMap.anisotropicFilteringLevel = 1;
  9288. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9289. }
  9290. },
  9291. enumerable: true,
  9292. configurable: true
  9293. });
  9294. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9295. get: function () {
  9296. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9297. },
  9298. set: function (value) {
  9299. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9305. get: function () {
  9306. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9307. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9308. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9309. },
  9310. set: function (value) {
  9311. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9312. },
  9313. enumerable: true,
  9314. configurable: true
  9315. });
  9316. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9317. get: function () {
  9318. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9319. },
  9320. set: function (value) {
  9321. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9327. var defines = [];
  9328. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9329. defines.push("#define VSM");
  9330. }
  9331. if (this.getLight().needCube()) {
  9332. defines.push("#define CUBEMAP");
  9333. }
  9334. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9335. var mesh = subMesh.getMesh();
  9336. var material = subMesh.getMaterial();
  9337. // Alpha test
  9338. if (material && material.needAlphaTesting()) {
  9339. defines.push("#define ALPHATEST");
  9340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9341. attribs.push(BABYLON.VertexBuffer.UVKind);
  9342. defines.push("#define UV1");
  9343. }
  9344. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9345. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9346. defines.push("#define UV2");
  9347. }
  9348. }
  9349. // Bones
  9350. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9353. if (mesh.numBoneInfluencers > 4) {
  9354. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9355. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9356. }
  9357. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9358. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9359. }
  9360. else {
  9361. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9362. }
  9363. // Instances
  9364. if (useInstances) {
  9365. defines.push("#define INSTANCES");
  9366. attribs.push("world0");
  9367. attribs.push("world1");
  9368. attribs.push("world2");
  9369. attribs.push("world3");
  9370. }
  9371. // Get correct effect
  9372. var join = defines.join("\n");
  9373. if (this._cachedDefines !== join) {
  9374. this._cachedDefines = join;
  9375. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9376. }
  9377. return this._effect.isReady();
  9378. };
  9379. ShadowGenerator.prototype.getShadowMap = function () {
  9380. return this._shadowMap;
  9381. };
  9382. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9383. if (this._shadowMap2) {
  9384. return this._shadowMap2;
  9385. }
  9386. return this._shadowMap;
  9387. };
  9388. ShadowGenerator.prototype.getLight = function () {
  9389. return this._light;
  9390. };
  9391. // Methods
  9392. ShadowGenerator.prototype.getTransformMatrix = function () {
  9393. var scene = this._scene;
  9394. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9395. return this._transformMatrix;
  9396. }
  9397. this._currentRenderID = scene.getRenderId();
  9398. this._currentFaceIndexCache = this._currentFaceIndex;
  9399. var lightPosition = this._light.position;
  9400. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9401. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9402. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9403. }
  9404. if (this._light.computeTransformedPosition()) {
  9405. lightPosition = this._light.transformedPosition;
  9406. }
  9407. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9408. this._cachedPosition = lightPosition.clone();
  9409. this._cachedDirection = this._lightDirection.clone();
  9410. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9411. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9412. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9413. }
  9414. return this._transformMatrix;
  9415. };
  9416. ShadowGenerator.prototype.getDarkness = function () {
  9417. return this._darkness;
  9418. };
  9419. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9420. if (darkness >= 1.0)
  9421. this._darkness = 1.0;
  9422. else if (darkness <= 0.0)
  9423. this._darkness = 0.0;
  9424. else
  9425. this._darkness = darkness;
  9426. };
  9427. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9428. this._transparencyShadow = hasShadow;
  9429. };
  9430. ShadowGenerator.prototype._packHalf = function (depth) {
  9431. var scale = depth * 255.0;
  9432. var fract = scale - Math.floor(scale);
  9433. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9434. };
  9435. ShadowGenerator.prototype.dispose = function () {
  9436. this._shadowMap.dispose();
  9437. if (this._shadowMap2) {
  9438. this._shadowMap2.dispose();
  9439. }
  9440. if (this._downSamplePostprocess) {
  9441. this._downSamplePostprocess.dispose();
  9442. }
  9443. if (this._boxBlurPostprocess) {
  9444. this._boxBlurPostprocess.dispose();
  9445. }
  9446. };
  9447. ShadowGenerator.prototype.serialize = function () {
  9448. var serializationObject = {};
  9449. serializationObject.lightId = this._light.id;
  9450. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9451. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9452. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9453. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9454. serializationObject.renderList = [];
  9455. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9456. var mesh = this.getShadowMap().renderList[meshIndex];
  9457. serializationObject.renderList.push(mesh.id);
  9458. }
  9459. return serializationObject;
  9460. };
  9461. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9462. //casting to point light, as light is missing the position attr and typescript complains.
  9463. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9464. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9465. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9466. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9467. shadowGenerator.getShadowMap().renderList.push(mesh);
  9468. }
  9469. if (parsedShadowGenerator.usePoissonSampling) {
  9470. shadowGenerator.usePoissonSampling = true;
  9471. }
  9472. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9473. shadowGenerator.useVarianceShadowMap = true;
  9474. }
  9475. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9476. shadowGenerator.useBlurVarianceShadowMap = true;
  9477. if (parsedShadowGenerator.blurScale) {
  9478. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9479. }
  9480. if (parsedShadowGenerator.blurBoxOffset) {
  9481. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9482. }
  9483. }
  9484. if (parsedShadowGenerator.bias !== undefined) {
  9485. shadowGenerator.bias = parsedShadowGenerator.bias;
  9486. }
  9487. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9488. return shadowGenerator;
  9489. };
  9490. ShadowGenerator._FILTER_NONE = 0;
  9491. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9492. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9493. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9494. return ShadowGenerator;
  9495. })();
  9496. BABYLON.ShadowGenerator = ShadowGenerator;
  9497. })(BABYLON || (BABYLON = {}));
  9498. var BABYLON;
  9499. (function (BABYLON) {
  9500. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9501. if (boxMin.x > sphereCenter.x + sphereRadius)
  9502. return false;
  9503. if (sphereCenter.x - sphereRadius > boxMax.x)
  9504. return false;
  9505. if (boxMin.y > sphereCenter.y + sphereRadius)
  9506. return false;
  9507. if (sphereCenter.y - sphereRadius > boxMax.y)
  9508. return false;
  9509. if (boxMin.z > sphereCenter.z + sphereRadius)
  9510. return false;
  9511. if (sphereCenter.z - sphereRadius > boxMax.z)
  9512. return false;
  9513. return true;
  9514. };
  9515. var getLowestRoot = function (a, b, c, maxR) {
  9516. var determinant = b * b - 4.0 * a * c;
  9517. var result = { root: 0, found: false };
  9518. if (determinant < 0)
  9519. return result;
  9520. var sqrtD = Math.sqrt(determinant);
  9521. var r1 = (-b - sqrtD) / (2.0 * a);
  9522. var r2 = (-b + sqrtD) / (2.0 * a);
  9523. if (r1 > r2) {
  9524. var temp = r2;
  9525. r2 = r1;
  9526. r1 = temp;
  9527. }
  9528. if (r1 > 0 && r1 < maxR) {
  9529. result.root = r1;
  9530. result.found = true;
  9531. return result;
  9532. }
  9533. if (r2 > 0 && r2 < maxR) {
  9534. result.root = r2;
  9535. result.found = true;
  9536. return result;
  9537. }
  9538. return result;
  9539. };
  9540. var Collider = (function () {
  9541. function Collider() {
  9542. this.radius = new BABYLON.Vector3(1, 1, 1);
  9543. this.retry = 0;
  9544. this.basePointWorld = BABYLON.Vector3.Zero();
  9545. this.velocityWorld = BABYLON.Vector3.Zero();
  9546. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9547. this._collisionPoint = BABYLON.Vector3.Zero();
  9548. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9549. this._tempVector = BABYLON.Vector3.Zero();
  9550. this._tempVector2 = BABYLON.Vector3.Zero();
  9551. this._tempVector3 = BABYLON.Vector3.Zero();
  9552. this._tempVector4 = BABYLON.Vector3.Zero();
  9553. this._edge = BABYLON.Vector3.Zero();
  9554. this._baseToVertex = BABYLON.Vector3.Zero();
  9555. this._destinationPoint = BABYLON.Vector3.Zero();
  9556. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9557. this._displacementVector = BABYLON.Vector3.Zero();
  9558. }
  9559. // Methods
  9560. Collider.prototype._initialize = function (source, dir, e) {
  9561. this.velocity = dir;
  9562. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9563. this.basePoint = source;
  9564. source.multiplyToRef(this.radius, this.basePointWorld);
  9565. dir.multiplyToRef(this.radius, this.velocityWorld);
  9566. this.velocityWorldLength = this.velocityWorld.length();
  9567. this.epsilon = e;
  9568. this.collisionFound = false;
  9569. };
  9570. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9571. pa.subtractToRef(point, this._tempVector);
  9572. pb.subtractToRef(point, this._tempVector2);
  9573. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9574. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9575. if (d < 0)
  9576. return false;
  9577. pc.subtractToRef(point, this._tempVector3);
  9578. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9579. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9580. if (d < 0)
  9581. return false;
  9582. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9583. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9584. return d >= 0;
  9585. };
  9586. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9587. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9588. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9589. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9590. return false;
  9591. }
  9592. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9593. return false;
  9594. return true;
  9595. };
  9596. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9597. var t0;
  9598. var embeddedInPlane = false;
  9599. //defensive programming, actually not needed.
  9600. if (!trianglePlaneArray) {
  9601. trianglePlaneArray = [];
  9602. }
  9603. if (!trianglePlaneArray[faceIndex]) {
  9604. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9605. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9606. }
  9607. var trianglePlane = trianglePlaneArray[faceIndex];
  9608. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9609. return;
  9610. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9611. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9612. if (normalDotVelocity == 0) {
  9613. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9614. return;
  9615. embeddedInPlane = true;
  9616. t0 = 0;
  9617. }
  9618. else {
  9619. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9620. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9621. if (t0 > t1) {
  9622. var temp = t1;
  9623. t1 = t0;
  9624. t0 = temp;
  9625. }
  9626. if (t0 > 1.0 || t1 < 0.0)
  9627. return;
  9628. if (t0 < 0)
  9629. t0 = 0;
  9630. if (t0 > 1.0)
  9631. t0 = 1.0;
  9632. }
  9633. this._collisionPoint.copyFromFloats(0, 0, 0);
  9634. var found = false;
  9635. var t = 1.0;
  9636. if (!embeddedInPlane) {
  9637. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9638. this.velocity.scaleToRef(t0, this._tempVector);
  9639. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9640. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9641. found = true;
  9642. t = t0;
  9643. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9644. }
  9645. }
  9646. if (!found) {
  9647. var velocitySquaredLength = this.velocity.lengthSquared();
  9648. var a = velocitySquaredLength;
  9649. this.basePoint.subtractToRef(p1, this._tempVector);
  9650. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9651. var c = this._tempVector.lengthSquared() - 1.0;
  9652. var lowestRoot = getLowestRoot(a, b, c, t);
  9653. if (lowestRoot.found) {
  9654. t = lowestRoot.root;
  9655. found = true;
  9656. this._collisionPoint.copyFrom(p1);
  9657. }
  9658. this.basePoint.subtractToRef(p2, this._tempVector);
  9659. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9660. c = this._tempVector.lengthSquared() - 1.0;
  9661. lowestRoot = getLowestRoot(a, b, c, t);
  9662. if (lowestRoot.found) {
  9663. t = lowestRoot.root;
  9664. found = true;
  9665. this._collisionPoint.copyFrom(p2);
  9666. }
  9667. this.basePoint.subtractToRef(p3, this._tempVector);
  9668. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9669. c = this._tempVector.lengthSquared() - 1.0;
  9670. lowestRoot = getLowestRoot(a, b, c, t);
  9671. if (lowestRoot.found) {
  9672. t = lowestRoot.root;
  9673. found = true;
  9674. this._collisionPoint.copyFrom(p3);
  9675. }
  9676. p2.subtractToRef(p1, this._edge);
  9677. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9678. var edgeSquaredLength = this._edge.lengthSquared();
  9679. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9680. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9681. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9682. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9683. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9684. lowestRoot = getLowestRoot(a, b, c, t);
  9685. if (lowestRoot.found) {
  9686. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9687. if (f >= 0.0 && f <= 1.0) {
  9688. t = lowestRoot.root;
  9689. found = true;
  9690. this._edge.scaleInPlace(f);
  9691. p1.addToRef(this._edge, this._collisionPoint);
  9692. }
  9693. }
  9694. p3.subtractToRef(p2, this._edge);
  9695. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9696. edgeSquaredLength = this._edge.lengthSquared();
  9697. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9698. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9699. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9700. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9701. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9702. lowestRoot = getLowestRoot(a, b, c, t);
  9703. if (lowestRoot.found) {
  9704. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9705. if (f >= 0.0 && f <= 1.0) {
  9706. t = lowestRoot.root;
  9707. found = true;
  9708. this._edge.scaleInPlace(f);
  9709. p2.addToRef(this._edge, this._collisionPoint);
  9710. }
  9711. }
  9712. p1.subtractToRef(p3, this._edge);
  9713. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9714. edgeSquaredLength = this._edge.lengthSquared();
  9715. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9716. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9717. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9718. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9719. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9720. lowestRoot = getLowestRoot(a, b, c, t);
  9721. if (lowestRoot.found) {
  9722. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9723. if (f >= 0.0 && f <= 1.0) {
  9724. t = lowestRoot.root;
  9725. found = true;
  9726. this._edge.scaleInPlace(f);
  9727. p3.addToRef(this._edge, this._collisionPoint);
  9728. }
  9729. }
  9730. }
  9731. if (found) {
  9732. var distToCollision = t * this.velocity.length();
  9733. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9734. if (!this.intersectionPoint) {
  9735. this.intersectionPoint = this._collisionPoint.clone();
  9736. }
  9737. else {
  9738. this.intersectionPoint.copyFrom(this._collisionPoint);
  9739. }
  9740. this.nearestDistance = distToCollision;
  9741. this.collisionFound = true;
  9742. }
  9743. }
  9744. };
  9745. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9746. for (var i = indexStart; i < indexEnd; i += 3) {
  9747. var p1 = pts[indices[i] - decal];
  9748. var p2 = pts[indices[i + 1] - decal];
  9749. var p3 = pts[indices[i + 2] - decal];
  9750. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9751. }
  9752. };
  9753. Collider.prototype._getResponse = function (pos, vel) {
  9754. pos.addToRef(vel, this._destinationPoint);
  9755. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9756. this.basePoint.addToRef(vel, pos);
  9757. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9758. this._slidePlaneNormal.normalize();
  9759. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9760. pos.addInPlace(this._displacementVector);
  9761. this.intersectionPoint.addInPlace(this._displacementVector);
  9762. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9763. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9764. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9765. };
  9766. return Collider;
  9767. })();
  9768. BABYLON.Collider = Collider;
  9769. })(BABYLON || (BABYLON = {}));
  9770. var BABYLON;
  9771. (function (BABYLON) {
  9772. //WebWorker code will be inserted to this variable.
  9773. BABYLON.CollisionWorker = "";
  9774. (function (WorkerTaskType) {
  9775. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9776. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9777. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9778. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9779. var WorkerTaskType = BABYLON.WorkerTaskType;
  9780. (function (WorkerReplyType) {
  9781. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9782. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9783. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9784. var WorkerReplyType = BABYLON.WorkerReplyType;
  9785. var CollisionCoordinatorWorker = (function () {
  9786. function CollisionCoordinatorWorker() {
  9787. var _this = this;
  9788. this._scaledPosition = BABYLON.Vector3.Zero();
  9789. this._scaledVelocity = BABYLON.Vector3.Zero();
  9790. this.onMeshUpdated = function (mesh) {
  9791. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9792. };
  9793. this.onGeometryUpdated = function (geometry) {
  9794. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9795. };
  9796. this._afterRender = function () {
  9797. if (!_this._init)
  9798. return;
  9799. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9800. return;
  9801. }
  9802. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9803. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9804. if (_this._runningUpdated > 4) {
  9805. return;
  9806. }
  9807. ++_this._runningUpdated;
  9808. var payload = {
  9809. updatedMeshes: _this._addUpdateMeshesList,
  9810. updatedGeometries: _this._addUpdateGeometriesList,
  9811. removedGeometries: _this._toRemoveGeometryArray,
  9812. removedMeshes: _this._toRemoveMeshesArray
  9813. };
  9814. var message = {
  9815. payload: payload,
  9816. taskType: WorkerTaskType.UPDATE
  9817. };
  9818. var serializable = [];
  9819. for (var id in payload.updatedGeometries) {
  9820. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9821. //prepare transferables
  9822. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9823. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9824. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9825. }
  9826. }
  9827. _this._worker.postMessage(message, serializable);
  9828. _this._addUpdateMeshesList = {};
  9829. _this._addUpdateGeometriesList = {};
  9830. _this._toRemoveGeometryArray = [];
  9831. _this._toRemoveMeshesArray = [];
  9832. };
  9833. this._onMessageFromWorker = function (e) {
  9834. var returnData = e.data;
  9835. if (returnData.error != WorkerReplyType.SUCCESS) {
  9836. //TODO what errors can be returned from the worker?
  9837. BABYLON.Tools.Warn("error returned from worker!");
  9838. return;
  9839. }
  9840. switch (returnData.taskType) {
  9841. case WorkerTaskType.INIT:
  9842. _this._init = true;
  9843. //Update the worked with ALL of the scene's current state
  9844. _this._scene.meshes.forEach(function (mesh) {
  9845. _this.onMeshAdded(mesh);
  9846. });
  9847. _this._scene.getGeometries().forEach(function (geometry) {
  9848. _this.onGeometryAdded(geometry);
  9849. });
  9850. break;
  9851. case WorkerTaskType.UPDATE:
  9852. _this._runningUpdated--;
  9853. break;
  9854. case WorkerTaskType.COLLIDE:
  9855. _this._runningCollisionTask = false;
  9856. var returnPayload = returnData.payload;
  9857. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9858. return;
  9859. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9860. //cleanup
  9861. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9862. break;
  9863. }
  9864. };
  9865. this._collisionsCallbackArray = [];
  9866. this._init = false;
  9867. this._runningUpdated = 0;
  9868. this._runningCollisionTask = false;
  9869. this._addUpdateMeshesList = {};
  9870. this._addUpdateGeometriesList = {};
  9871. this._toRemoveGeometryArray = [];
  9872. this._toRemoveMeshesArray = [];
  9873. }
  9874. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9875. if (!this._init)
  9876. return;
  9877. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9878. return;
  9879. position.divideToRef(collider.radius, this._scaledPosition);
  9880. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9881. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9882. var payload = {
  9883. collider: {
  9884. position: this._scaledPosition.asArray(),
  9885. velocity: this._scaledVelocity.asArray(),
  9886. radius: collider.radius.asArray()
  9887. },
  9888. collisionId: collisionIndex,
  9889. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9890. maximumRetry: maximumRetry
  9891. };
  9892. var message = {
  9893. payload: payload,
  9894. taskType: WorkerTaskType.COLLIDE
  9895. };
  9896. this._worker.postMessage(message);
  9897. };
  9898. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9899. this._scene = scene;
  9900. this._scene.registerAfterRender(this._afterRender);
  9901. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9902. this._worker = new Worker(workerUrl);
  9903. this._worker.onmessage = this._onMessageFromWorker;
  9904. var message = {
  9905. payload: {},
  9906. taskType: WorkerTaskType.INIT
  9907. };
  9908. this._worker.postMessage(message);
  9909. };
  9910. CollisionCoordinatorWorker.prototype.destroy = function () {
  9911. this._scene.unregisterAfterRender(this._afterRender);
  9912. this._worker.terminate();
  9913. };
  9914. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9915. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9916. this.onMeshUpdated(mesh);
  9917. };
  9918. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9919. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9920. };
  9921. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9922. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9923. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9924. this.onGeometryUpdated(geometry);
  9925. };
  9926. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9927. this._toRemoveGeometryArray.push(geometry.id);
  9928. };
  9929. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9930. var submeshes = [];
  9931. if (mesh.subMeshes) {
  9932. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9933. return {
  9934. position: idx,
  9935. verticesStart: sm.verticesStart,
  9936. verticesCount: sm.verticesCount,
  9937. indexStart: sm.indexStart,
  9938. indexCount: sm.indexCount,
  9939. hasMaterial: !!sm.getMaterial(),
  9940. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9941. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9942. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9943. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9944. };
  9945. });
  9946. }
  9947. var geometryId = null;
  9948. if (mesh instanceof BABYLON.Mesh) {
  9949. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9950. }
  9951. else if (mesh instanceof BABYLON.InstancedMesh) {
  9952. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9953. }
  9954. return {
  9955. uniqueId: mesh.uniqueId,
  9956. id: mesh.id,
  9957. name: mesh.name,
  9958. geometryId: geometryId,
  9959. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9960. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9961. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9962. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9963. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9964. subMeshes: submeshes,
  9965. checkCollisions: mesh.checkCollisions
  9966. };
  9967. };
  9968. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9969. return {
  9970. id: geometry.id,
  9971. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9972. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9973. indices: new Int32Array(geometry.getIndices() || []),
  9974. };
  9975. };
  9976. return CollisionCoordinatorWorker;
  9977. })();
  9978. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9979. var CollisionCoordinatorLegacy = (function () {
  9980. function CollisionCoordinatorLegacy() {
  9981. this._scaledPosition = BABYLON.Vector3.Zero();
  9982. this._scaledVelocity = BABYLON.Vector3.Zero();
  9983. this._finalPosition = BABYLON.Vector3.Zero();
  9984. }
  9985. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9986. position.divideToRef(collider.radius, this._scaledPosition);
  9987. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9988. collider.collidedMesh = null;
  9989. collider.retry = 0;
  9990. collider.initialVelocity = this._scaledVelocity;
  9991. collider.initialPosition = this._scaledPosition;
  9992. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9993. this._finalPosition.multiplyInPlace(collider.radius);
  9994. //run the callback
  9995. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9996. };
  9997. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9998. this._scene = scene;
  9999. };
  10000. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10001. //Legacy need no destruction method.
  10002. };
  10003. //No update in legacy mode
  10004. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10005. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10006. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10007. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10008. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10009. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10010. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10011. if (excludedMesh === void 0) { excludedMesh = null; }
  10012. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10013. if (collider.retry >= maximumRetry) {
  10014. finalPosition.copyFrom(position);
  10015. return;
  10016. }
  10017. collider._initialize(position, velocity, closeDistance);
  10018. // Check all meshes
  10019. for (var index = 0; index < this._scene.meshes.length; index++) {
  10020. var mesh = this._scene.meshes[index];
  10021. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10022. mesh._checkCollision(collider);
  10023. }
  10024. }
  10025. if (!collider.collisionFound) {
  10026. position.addToRef(velocity, finalPosition);
  10027. return;
  10028. }
  10029. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10030. collider._getResponse(position, velocity);
  10031. }
  10032. if (velocity.length() <= closeDistance) {
  10033. finalPosition.copyFrom(position);
  10034. return;
  10035. }
  10036. collider.retry++;
  10037. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10038. };
  10039. return CollisionCoordinatorLegacy;
  10040. })();
  10041. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10042. })(BABYLON || (BABYLON = {}));
  10043. var BABYLON;
  10044. (function (BABYLON) {
  10045. var VRCameraMetrics = (function () {
  10046. function VRCameraMetrics() {
  10047. this.compensateDistortion = true;
  10048. }
  10049. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  10050. get: function () {
  10051. return this.hResolution / (2 * this.vResolution);
  10052. },
  10053. enumerable: true,
  10054. configurable: true
  10055. });
  10056. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  10057. get: function () {
  10058. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  10064. get: function () {
  10065. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10066. var h = (4 * meters) / this.hScreenSize;
  10067. return BABYLON.Matrix.Translation(h, 0, 0);
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  10073. get: function () {
  10074. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10075. var h = (4 * meters) / this.hScreenSize;
  10076. return BABYLON.Matrix.Translation(-h, 0, 0);
  10077. },
  10078. enumerable: true,
  10079. configurable: true
  10080. });
  10081. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  10082. get: function () {
  10083. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  10084. },
  10085. enumerable: true,
  10086. configurable: true
  10087. });
  10088. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  10089. get: function () {
  10090. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. VRCameraMetrics.GetDefault = function () {
  10096. var result = new VRCameraMetrics();
  10097. result.hResolution = 1280;
  10098. result.vResolution = 800;
  10099. result.hScreenSize = 0.149759993;
  10100. result.vScreenSize = 0.0935999975;
  10101. result.vScreenCenter = 0.0467999987,
  10102. result.eyeToScreenDistance = 0.0410000011;
  10103. result.lensSeparationDistance = 0.0635000020;
  10104. result.interpupillaryDistance = 0.0640000030;
  10105. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  10106. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  10107. result.postProcessScaleFactor = 1.714605507808412;
  10108. result.lensCenterOffset = 0.151976421;
  10109. return result;
  10110. };
  10111. return VRCameraMetrics;
  10112. })();
  10113. BABYLON.VRCameraMetrics = VRCameraMetrics;
  10114. var Camera = (function (_super) {
  10115. __extends(Camera, _super);
  10116. function Camera(name, position, scene) {
  10117. _super.call(this, name, scene);
  10118. this.position = position;
  10119. // Members
  10120. this.upVector = BABYLON.Vector3.Up();
  10121. this.orthoLeft = null;
  10122. this.orthoRight = null;
  10123. this.orthoBottom = null;
  10124. this.orthoTop = null;
  10125. this.fov = 0.8;
  10126. this.minZ = 1.0;
  10127. this.maxZ = 10000.0;
  10128. this.inertia = 0.9;
  10129. this.mode = Camera.PERSPECTIVE_CAMERA;
  10130. this.isIntermediate = false;
  10131. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10132. this.layerMask = 0x0FFFFFFF;
  10133. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10134. // Camera rig members
  10135. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10136. this._rigCameras = new Array();
  10137. // Cache
  10138. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10139. this._projectionMatrix = new BABYLON.Matrix();
  10140. this._postProcesses = new Array();
  10141. this._postProcessesTakenIndices = [];
  10142. this._activeMeshes = new BABYLON.SmartArray(256);
  10143. this._globalPosition = BABYLON.Vector3.Zero();
  10144. scene.addCamera(this);
  10145. if (!scene.activeCamera) {
  10146. scene.activeCamera = this;
  10147. }
  10148. }
  10149. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10150. get: function () {
  10151. return Camera._PERSPECTIVE_CAMERA;
  10152. },
  10153. enumerable: true,
  10154. configurable: true
  10155. });
  10156. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10157. get: function () {
  10158. return Camera._ORTHOGRAPHIC_CAMERA;
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10164. get: function () {
  10165. return Camera._FOVMODE_VERTICAL_FIXED;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10171. get: function () {
  10172. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10178. get: function () {
  10179. return Camera._RIG_MODE_NONE;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10185. get: function () {
  10186. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10192. get: function () {
  10193. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10194. },
  10195. enumerable: true,
  10196. configurable: true
  10197. });
  10198. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10199. get: function () {
  10200. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10201. },
  10202. enumerable: true,
  10203. configurable: true
  10204. });
  10205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10206. get: function () {
  10207. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10208. },
  10209. enumerable: true,
  10210. configurable: true
  10211. });
  10212. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10213. get: function () {
  10214. return Camera._RIG_MODE_VR;
  10215. },
  10216. enumerable: true,
  10217. configurable: true
  10218. });
  10219. Object.defineProperty(Camera.prototype, "globalPosition", {
  10220. get: function () {
  10221. return this._globalPosition;
  10222. },
  10223. enumerable: true,
  10224. configurable: true
  10225. });
  10226. Camera.prototype.getActiveMeshes = function () {
  10227. return this._activeMeshes;
  10228. };
  10229. Camera.prototype.isActiveMesh = function (mesh) {
  10230. return (this._activeMeshes.indexOf(mesh) !== -1);
  10231. };
  10232. //Cache
  10233. Camera.prototype._initCache = function () {
  10234. _super.prototype._initCache.call(this);
  10235. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10236. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10237. this._cache.mode = undefined;
  10238. this._cache.minZ = undefined;
  10239. this._cache.maxZ = undefined;
  10240. this._cache.fov = undefined;
  10241. this._cache.aspectRatio = undefined;
  10242. this._cache.orthoLeft = undefined;
  10243. this._cache.orthoRight = undefined;
  10244. this._cache.orthoBottom = undefined;
  10245. this._cache.orthoTop = undefined;
  10246. this._cache.renderWidth = undefined;
  10247. this._cache.renderHeight = undefined;
  10248. };
  10249. Camera.prototype._updateCache = function (ignoreParentClass) {
  10250. if (!ignoreParentClass) {
  10251. _super.prototype._updateCache.call(this);
  10252. }
  10253. var engine = this.getEngine();
  10254. this._cache.position.copyFrom(this.position);
  10255. this._cache.upVector.copyFrom(this.upVector);
  10256. this._cache.mode = this.mode;
  10257. this._cache.minZ = this.minZ;
  10258. this._cache.maxZ = this.maxZ;
  10259. this._cache.fov = this.fov;
  10260. this._cache.aspectRatio = engine.getAspectRatio(this);
  10261. this._cache.orthoLeft = this.orthoLeft;
  10262. this._cache.orthoRight = this.orthoRight;
  10263. this._cache.orthoBottom = this.orthoBottom;
  10264. this._cache.orthoTop = this.orthoTop;
  10265. this._cache.renderWidth = engine.getRenderWidth();
  10266. this._cache.renderHeight = engine.getRenderHeight();
  10267. };
  10268. Camera.prototype._updateFromScene = function () {
  10269. this.updateCache();
  10270. this._update();
  10271. };
  10272. // Synchronized
  10273. Camera.prototype._isSynchronized = function () {
  10274. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10275. };
  10276. Camera.prototype._isSynchronizedViewMatrix = function () {
  10277. if (!_super.prototype._isSynchronized.call(this))
  10278. return false;
  10279. return this._cache.position.equals(this.position)
  10280. && this._cache.upVector.equals(this.upVector)
  10281. && this.isSynchronizedWithParent();
  10282. };
  10283. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10284. var check = this._cache.mode === this.mode
  10285. && this._cache.minZ === this.minZ
  10286. && this._cache.maxZ === this.maxZ;
  10287. if (!check) {
  10288. return false;
  10289. }
  10290. var engine = this.getEngine();
  10291. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10292. check = this._cache.fov === this.fov
  10293. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10294. }
  10295. else {
  10296. check = this._cache.orthoLeft === this.orthoLeft
  10297. && this._cache.orthoRight === this.orthoRight
  10298. && this._cache.orthoBottom === this.orthoBottom
  10299. && this._cache.orthoTop === this.orthoTop
  10300. && this._cache.renderWidth === engine.getRenderWidth()
  10301. && this._cache.renderHeight === engine.getRenderHeight();
  10302. }
  10303. return check;
  10304. };
  10305. // Controls
  10306. Camera.prototype.attachControl = function (element) {
  10307. };
  10308. Camera.prototype.detachControl = function (element) {
  10309. };
  10310. Camera.prototype._update = function () {
  10311. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10312. this._updateRigCameras();
  10313. }
  10314. this._checkInputs();
  10315. };
  10316. Camera.prototype._checkInputs = function () {
  10317. };
  10318. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10319. if (insertAt === void 0) { insertAt = null; }
  10320. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10321. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10322. return 0;
  10323. }
  10324. if (insertAt == null || insertAt < 0) {
  10325. this._postProcesses.push(postProcess);
  10326. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10327. return this._postProcesses.length - 1;
  10328. }
  10329. var add = 0;
  10330. var i;
  10331. var start;
  10332. if (this._postProcesses[insertAt]) {
  10333. start = this._postProcesses.length - 1;
  10334. for (i = start; i >= insertAt + 1; --i) {
  10335. this._postProcesses[i + 1] = this._postProcesses[i];
  10336. }
  10337. add = 1;
  10338. }
  10339. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10340. if (this._postProcessesTakenIndices[i] < insertAt) {
  10341. continue;
  10342. }
  10343. start = this._postProcessesTakenIndices.length - 1;
  10344. for (var j = start; j >= i; --j) {
  10345. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10346. }
  10347. this._postProcessesTakenIndices[i] = insertAt;
  10348. break;
  10349. }
  10350. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10351. this._postProcessesTakenIndices.push(insertAt);
  10352. }
  10353. var result = insertAt + add;
  10354. this._postProcesses[result] = postProcess;
  10355. return result;
  10356. };
  10357. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10358. if (atIndices === void 0) { atIndices = null; }
  10359. var result = [];
  10360. var i;
  10361. var index;
  10362. if (!atIndices) {
  10363. var length = this._postProcesses.length;
  10364. for (i = 0; i < length; i++) {
  10365. if (this._postProcesses[i] !== postProcess) {
  10366. continue;
  10367. }
  10368. delete this._postProcesses[i];
  10369. index = this._postProcessesTakenIndices.indexOf(i);
  10370. this._postProcessesTakenIndices.splice(index, 1);
  10371. }
  10372. }
  10373. else {
  10374. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10375. for (i = 0; i < atIndices.length; i++) {
  10376. var foundPostProcess = this._postProcesses[atIndices[i]];
  10377. if (foundPostProcess !== postProcess) {
  10378. result.push(i);
  10379. continue;
  10380. }
  10381. delete this._postProcesses[atIndices[i]];
  10382. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10383. this._postProcessesTakenIndices.splice(index, 1);
  10384. }
  10385. }
  10386. return result;
  10387. };
  10388. Camera.prototype.getWorldMatrix = function () {
  10389. if (!this._worldMatrix) {
  10390. this._worldMatrix = BABYLON.Matrix.Identity();
  10391. }
  10392. var viewMatrix = this.getViewMatrix();
  10393. viewMatrix.invertToRef(this._worldMatrix);
  10394. return this._worldMatrix;
  10395. };
  10396. Camera.prototype._getViewMatrix = function () {
  10397. return BABYLON.Matrix.Identity();
  10398. };
  10399. Camera.prototype.getViewMatrix = function (force) {
  10400. this._computedViewMatrix = this._computeViewMatrix(force);
  10401. if (!force && this._isSynchronizedViewMatrix()) {
  10402. return this._computedViewMatrix;
  10403. }
  10404. if (!this.parent || !this.parent.getWorldMatrix) {
  10405. this._globalPosition.copyFrom(this.position);
  10406. }
  10407. else {
  10408. if (!this._worldMatrix) {
  10409. this._worldMatrix = BABYLON.Matrix.Identity();
  10410. }
  10411. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10412. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10413. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10414. this._computedViewMatrix.invert();
  10415. this._markSyncedWithParent();
  10416. }
  10417. this._currentRenderId = this.getScene().getRenderId();
  10418. return this._computedViewMatrix;
  10419. };
  10420. Camera.prototype._computeViewMatrix = function (force) {
  10421. if (!force && this._isSynchronizedViewMatrix()) {
  10422. return this._computedViewMatrix;
  10423. }
  10424. this._computedViewMatrix = this._getViewMatrix();
  10425. this._currentRenderId = this.getScene().getRenderId();
  10426. return this._computedViewMatrix;
  10427. };
  10428. Camera.prototype.getProjectionMatrix = function (force) {
  10429. if (!force && this._isSynchronizedProjectionMatrix()) {
  10430. return this._projectionMatrix;
  10431. }
  10432. var engine = this.getEngine();
  10433. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10434. if (this.minZ <= 0) {
  10435. this.minZ = 0.1;
  10436. }
  10437. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10438. return this._projectionMatrix;
  10439. }
  10440. var halfWidth = engine.getRenderWidth() / 2.0;
  10441. var halfHeight = engine.getRenderHeight() / 2.0;
  10442. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10443. return this._projectionMatrix;
  10444. };
  10445. Camera.prototype.dispose = function () {
  10446. // Animations
  10447. this.getScene().stopAnimation(this);
  10448. // Remove from scene
  10449. this.getScene().removeCamera(this);
  10450. while (this._rigCameras.length > 0) {
  10451. this._rigCameras.pop().dispose();
  10452. }
  10453. // Postprocesses
  10454. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10455. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10456. }
  10457. };
  10458. // ---- Camera rigs section ----
  10459. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10460. while (this._rigCameras.length > 0) {
  10461. this._rigCameras.pop().dispose();
  10462. }
  10463. this.cameraRigMode = mode;
  10464. this._cameraRigParams = {};
  10465. switch (this.cameraRigMode) {
  10466. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10467. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10468. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10469. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10470. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10471. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10472. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10473. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10474. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10475. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10476. break;
  10477. }
  10478. var postProcesses = new Array();
  10479. switch (this.cameraRigMode) {
  10480. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10481. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10482. this._rigCameras[0].isIntermediate = true;
  10483. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10484. postProcesses[1].onApply = function (effect) {
  10485. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10486. };
  10487. break;
  10488. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10489. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10490. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10491. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10492. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10493. var secondCamIndex = 1 - firstCamIndex;
  10494. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10495. this._rigCameras[firstCamIndex].isIntermediate = true;
  10496. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10497. break;
  10498. case Camera.RIG_MODE_VR:
  10499. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10500. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10501. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10502. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10503. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10504. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10505. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10506. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10507. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10508. if (metrics.compensateDistortion) {
  10509. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10510. }
  10511. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10512. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10513. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10514. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10515. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10516. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10517. if (metrics.compensateDistortion) {
  10518. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10519. }
  10520. break;
  10521. }
  10522. this._update();
  10523. };
  10524. Camera.prototype._getVRProjectionMatrix = function () {
  10525. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10526. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10527. return this._projectionMatrix;
  10528. };
  10529. Camera.prototype.setCameraRigParameter = function (name, value) {
  10530. this._cameraRigParams[name] = value;
  10531. //provisionnally:
  10532. if (name === "interaxialDistance") {
  10533. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10534. }
  10535. };
  10536. /**
  10537. * May needs to be overridden by children so sub has required properties to be copied
  10538. */
  10539. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10540. return null;
  10541. };
  10542. /**
  10543. * May needs to be overridden by children
  10544. */
  10545. Camera.prototype._updateRigCameras = function () {
  10546. for (var i = 0; i < this._rigCameras.length; i++) {
  10547. this._rigCameras[i].minZ = this.minZ;
  10548. this._rigCameras[i].maxZ = this.maxZ;
  10549. this._rigCameras[i].fov = this.fov;
  10550. }
  10551. // only update viewport when ANAGLYPH
  10552. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10553. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10554. }
  10555. };
  10556. Camera.prototype.serialize = function () {
  10557. var serializationObject = {};
  10558. serializationObject.name = this.name;
  10559. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10560. serializationObject.id = this.id;
  10561. serializationObject.position = this.position.asArray();
  10562. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10563. // Parent
  10564. if (this.parent) {
  10565. serializationObject.parentId = this.parent.id;
  10566. }
  10567. serializationObject.fov = this.fov;
  10568. serializationObject.minZ = this.minZ;
  10569. serializationObject.maxZ = this.maxZ;
  10570. serializationObject.inertia = this.inertia;
  10571. // Animations
  10572. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10573. serializationObject.ranges = this.serializeAnimationRanges();
  10574. // Layer mask
  10575. serializationObject.layerMask = this.layerMask;
  10576. return serializationObject;
  10577. };
  10578. Camera.Parse = function (parsedCamera, scene) {
  10579. var camera;
  10580. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10581. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10582. var interaxial_distance;
  10583. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10584. var alpha = parsedCamera.alpha;
  10585. var beta = parsedCamera.beta;
  10586. var radius = parsedCamera.radius;
  10587. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10588. interaxial_distance = parsedCamera.interaxial_distance;
  10589. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10590. }
  10591. else {
  10592. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10593. }
  10594. }
  10595. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10596. interaxial_distance = parsedCamera.interaxial_distance;
  10597. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10598. }
  10599. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10600. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10601. }
  10602. else if (parsedCamera.type === "FollowCamera") {
  10603. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10604. camera.heightOffset = parsedCamera.heightOffset;
  10605. camera.radius = parsedCamera.radius;
  10606. camera.rotationOffset = parsedCamera.rotationOffset;
  10607. if (lockedTargetMesh)
  10608. camera.target = lockedTargetMesh;
  10609. }
  10610. else if (parsedCamera.type === "GamepadCamera") {
  10611. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10612. }
  10613. else if (parsedCamera.type === "TouchCamera") {
  10614. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10615. }
  10616. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10617. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10618. }
  10619. else if (parsedCamera.type === "WebVRFreeCamera") {
  10620. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10621. }
  10622. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10623. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10624. }
  10625. else if (parsedCamera.type === "FreeCamera") {
  10626. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
  10627. }
  10628. else {
  10629. // Universal Camera is the default value
  10630. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
  10631. }
  10632. // apply 3d rig, when found
  10633. if (parsedCamera.cameraRigMode) {
  10634. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10635. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10636. }
  10637. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10638. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10639. camera.lockedTarget = lockedTargetMesh;
  10640. }
  10641. camera.id = parsedCamera.id;
  10642. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10643. // Parent
  10644. if (parsedCamera.parentId) {
  10645. camera._waitingParentId = parsedCamera.parentId;
  10646. }
  10647. // Target
  10648. if (parsedCamera.target) {
  10649. if (camera.setTarget) {
  10650. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10651. }
  10652. else {
  10653. //For ArcRotate
  10654. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10655. }
  10656. }
  10657. else {
  10658. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10659. }
  10660. camera.fov = parsedCamera.fov;
  10661. camera.minZ = parsedCamera.minZ;
  10662. camera.maxZ = parsedCamera.maxZ;
  10663. camera.speed = parsedCamera.speed;
  10664. camera.inertia = parsedCamera.inertia;
  10665. camera.checkCollisions = parsedCamera.checkCollisions;
  10666. camera.applyGravity = parsedCamera.applyGravity;
  10667. if (parsedCamera.ellipsoid) {
  10668. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10669. }
  10670. // Animations
  10671. if (parsedCamera.animations) {
  10672. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10673. var parsedAnimation = parsedCamera.animations[animationIndex];
  10674. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10675. }
  10676. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10677. }
  10678. if (parsedCamera.autoAnimate) {
  10679. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10680. }
  10681. // Layer Mask
  10682. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10683. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10684. }
  10685. else {
  10686. camera.layerMask = 0x0FFFFFFF;
  10687. }
  10688. return camera;
  10689. };
  10690. // Statics
  10691. Camera._PERSPECTIVE_CAMERA = 0;
  10692. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10693. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10694. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10695. Camera._RIG_MODE_NONE = 0;
  10696. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10697. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10698. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10699. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10700. Camera._RIG_MODE_VR = 20;
  10701. return Camera;
  10702. })(BABYLON.Node);
  10703. BABYLON.Camera = Camera;
  10704. })(BABYLON || (BABYLON = {}));
  10705. var BABYLON;
  10706. (function (BABYLON) {
  10707. var TargetCamera = (function (_super) {
  10708. __extends(TargetCamera, _super);
  10709. function TargetCamera(name, position, scene) {
  10710. _super.call(this, name, position, scene);
  10711. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10712. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10713. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10714. this.speed = 2.0;
  10715. this.noRotationConstraint = false;
  10716. this.lockedTarget = null;
  10717. this._currentTarget = BABYLON.Vector3.Zero();
  10718. this._viewMatrix = BABYLON.Matrix.Zero();
  10719. this._camMatrix = BABYLON.Matrix.Zero();
  10720. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10721. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10722. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10723. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10724. this._lookAtTemp = BABYLON.Matrix.Zero();
  10725. this._tempMatrix = BABYLON.Matrix.Zero();
  10726. }
  10727. TargetCamera.prototype.getFrontPosition = function (distance) {
  10728. var direction = this.getTarget().subtract(this.position);
  10729. direction.normalize();
  10730. direction.scaleInPlace(distance);
  10731. return this.globalPosition.add(direction);
  10732. };
  10733. TargetCamera.prototype._getLockedTargetPosition = function () {
  10734. if (!this.lockedTarget) {
  10735. return null;
  10736. }
  10737. return this.lockedTarget.position || this.lockedTarget;
  10738. };
  10739. // Cache
  10740. TargetCamera.prototype._initCache = function () {
  10741. _super.prototype._initCache.call(this);
  10742. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10743. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10744. };
  10745. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10746. if (!ignoreParentClass) {
  10747. _super.prototype._updateCache.call(this);
  10748. }
  10749. var lockedTargetPosition = this._getLockedTargetPosition();
  10750. if (!lockedTargetPosition) {
  10751. this._cache.lockedTarget = null;
  10752. }
  10753. else {
  10754. if (!this._cache.lockedTarget) {
  10755. this._cache.lockedTarget = lockedTargetPosition.clone();
  10756. }
  10757. else {
  10758. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10759. }
  10760. }
  10761. this._cache.rotation.copyFrom(this.rotation);
  10762. };
  10763. // Synchronized
  10764. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10765. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10766. return false;
  10767. }
  10768. var lockedTargetPosition = this._getLockedTargetPosition();
  10769. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10770. && this._cache.rotation.equals(this.rotation);
  10771. };
  10772. // Methods
  10773. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10774. var engine = this.getEngine();
  10775. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10776. };
  10777. // Target
  10778. TargetCamera.prototype.setTarget = function (target) {
  10779. this.upVector.normalize();
  10780. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10781. this._camMatrix.invert();
  10782. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10783. var vDir = target.subtract(this.position);
  10784. if (vDir.x >= 0.0) {
  10785. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10786. }
  10787. else {
  10788. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10789. }
  10790. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10791. if (isNaN(this.rotation.x)) {
  10792. this.rotation.x = 0;
  10793. }
  10794. if (isNaN(this.rotation.y)) {
  10795. this.rotation.y = 0;
  10796. }
  10797. if (isNaN(this.rotation.z)) {
  10798. this.rotation.z = 0;
  10799. }
  10800. };
  10801. TargetCamera.prototype.getTarget = function () {
  10802. return this._currentTarget;
  10803. };
  10804. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10805. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10806. };
  10807. TargetCamera.prototype._updatePosition = function () {
  10808. this.position.addInPlace(this.cameraDirection);
  10809. };
  10810. TargetCamera.prototype._checkInputs = function () {
  10811. var needToMove = this._decideIfNeedsToMove();
  10812. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10813. // Move
  10814. if (needToMove) {
  10815. this._updatePosition();
  10816. }
  10817. // Rotate
  10818. if (needToRotate) {
  10819. this.rotation.x += this.cameraRotation.x;
  10820. this.rotation.y += this.cameraRotation.y;
  10821. if (!this.noRotationConstraint) {
  10822. var limit = (Math.PI / 2) * 0.95;
  10823. if (this.rotation.x > limit)
  10824. this.rotation.x = limit;
  10825. if (this.rotation.x < -limit)
  10826. this.rotation.x = -limit;
  10827. }
  10828. }
  10829. // Inertia
  10830. if (needToMove) {
  10831. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10832. this.cameraDirection.x = 0;
  10833. }
  10834. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10835. this.cameraDirection.y = 0;
  10836. }
  10837. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10838. this.cameraDirection.z = 0;
  10839. }
  10840. this.cameraDirection.scaleInPlace(this.inertia);
  10841. }
  10842. if (needToRotate) {
  10843. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10844. this.cameraRotation.x = 0;
  10845. }
  10846. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10847. this.cameraRotation.y = 0;
  10848. }
  10849. this.cameraRotation.scaleInPlace(this.inertia);
  10850. }
  10851. _super.prototype._checkInputs.call(this);
  10852. };
  10853. TargetCamera.prototype._getViewMatrix = function () {
  10854. if (!this.lockedTarget) {
  10855. // Compute
  10856. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10857. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10858. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10859. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10860. this._lookAtTemp.invert();
  10861. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10862. }
  10863. else {
  10864. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10865. }
  10866. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10867. // Computing target and final matrix
  10868. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10869. }
  10870. else {
  10871. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10872. }
  10873. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10874. return this._viewMatrix;
  10875. };
  10876. TargetCamera.prototype._getVRViewMatrix = function () {
  10877. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10878. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10879. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10880. // Computing target and final matrix
  10881. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10882. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10883. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10884. return this._viewMatrix;
  10885. };
  10886. /**
  10887. * @override
  10888. * Override Camera.createRigCamera
  10889. */
  10890. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10891. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10892. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10893. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10894. rigCamera._cameraRigParams = {};
  10895. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10896. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10897. }
  10898. return rigCamera;
  10899. }
  10900. return null;
  10901. };
  10902. /**
  10903. * @override
  10904. * Override Camera._updateRigCameras
  10905. */
  10906. TargetCamera.prototype._updateRigCameras = function () {
  10907. switch (this.cameraRigMode) {
  10908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10912. case BABYLON.Camera.RIG_MODE_VR:
  10913. var camLeft = this._rigCameras[0];
  10914. var camRight = this._rigCameras[1];
  10915. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10916. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10917. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10918. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10919. camLeft.position.copyFrom(this.position);
  10920. camRight.position.copyFrom(this.position);
  10921. }
  10922. else {
  10923. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10924. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10925. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10926. camLeft.setTarget(this.getTarget());
  10927. camRight.setTarget(this.getTarget());
  10928. }
  10929. break;
  10930. }
  10931. _super.prototype._updateRigCameras.call(this);
  10932. };
  10933. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10934. if (!this._rigCamTransformMatrix) {
  10935. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10936. }
  10937. var target = this.getTarget();
  10938. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10939. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10940. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10941. };
  10942. TargetCamera.prototype.serialize = function () {
  10943. var serializationObject = _super.prototype.serialize.call(this);
  10944. serializationObject.speed = this.speed;
  10945. if (this.rotation) {
  10946. serializationObject.rotation = this.rotation.asArray();
  10947. }
  10948. if (this.lockedTarget && this.lockedTarget.id) {
  10949. serializationObject.lockedTargetId = this.lockedTarget.id;
  10950. }
  10951. return serializationObject;
  10952. };
  10953. return TargetCamera;
  10954. })(BABYLON.Camera);
  10955. BABYLON.TargetCamera = TargetCamera;
  10956. })(BABYLON || (BABYLON = {}));
  10957. var BABYLON;
  10958. (function (BABYLON) {
  10959. var FreeCamera = (function (_super) {
  10960. __extends(FreeCamera, _super);
  10961. function FreeCamera(name, position, scene) {
  10962. var _this = this;
  10963. _super.call(this, name, position, scene);
  10964. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10965. this.keysUp = [38];
  10966. this.keysDown = [40];
  10967. this.keysLeft = [37];
  10968. this.keysRight = [39];
  10969. this.checkCollisions = false;
  10970. this.applyGravity = false;
  10971. this.angularSensibility = 2000.0;
  10972. this._keys = [];
  10973. this._collider = new BABYLON.Collider();
  10974. this._needMoveForGravity = false;
  10975. this._oldPosition = BABYLON.Vector3.Zero();
  10976. this._diffPosition = BABYLON.Vector3.Zero();
  10977. this._newPosition = BABYLON.Vector3.Zero();
  10978. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10979. if (collidedMesh === void 0) { collidedMesh = null; }
  10980. //TODO move this to the collision coordinator!
  10981. if (_this.getScene().workerCollisions)
  10982. newPosition.multiplyInPlace(_this._collider.radius);
  10983. var updatePosition = function (newPos) {
  10984. _this._newPosition.copyFrom(newPos);
  10985. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10986. var oldPosition = _this.position.clone();
  10987. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10988. _this.position.addInPlace(_this._diffPosition);
  10989. if (_this.onCollide && collidedMesh) {
  10990. _this.onCollide(collidedMesh);
  10991. }
  10992. }
  10993. };
  10994. updatePosition(newPosition);
  10995. };
  10996. }
  10997. FreeCamera.prototype._onLostFocus = function (e) {
  10998. this._keys = [];
  10999. };
  11000. // Controls
  11001. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11002. var _this = this;
  11003. var previousPosition;
  11004. var engine = this.getEngine();
  11005. if (this._attachedElement) {
  11006. return;
  11007. }
  11008. this._attachedElement = element;
  11009. if (this._onMouseDown === undefined) {
  11010. this._onMouseDown = function (evt) {
  11011. previousPosition = {
  11012. x: evt.clientX,
  11013. y: evt.clientY
  11014. };
  11015. if (!noPreventDefault) {
  11016. evt.preventDefault();
  11017. }
  11018. };
  11019. this._onMouseUp = function (evt) {
  11020. previousPosition = null;
  11021. if (!noPreventDefault) {
  11022. evt.preventDefault();
  11023. }
  11024. };
  11025. this._onMouseOut = function (evt) {
  11026. previousPosition = null;
  11027. _this._keys = [];
  11028. if (!noPreventDefault) {
  11029. evt.preventDefault();
  11030. }
  11031. };
  11032. this._onMouseMove = function (evt) {
  11033. if (!previousPosition && !engine.isPointerLock) {
  11034. return;
  11035. }
  11036. var offsetX;
  11037. var offsetY;
  11038. if (!engine.isPointerLock) {
  11039. offsetX = evt.clientX - previousPosition.x;
  11040. offsetY = evt.clientY - previousPosition.y;
  11041. }
  11042. else {
  11043. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11044. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11045. }
  11046. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11047. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11048. previousPosition = {
  11049. x: evt.clientX,
  11050. y: evt.clientY
  11051. };
  11052. if (!noPreventDefault) {
  11053. evt.preventDefault();
  11054. }
  11055. };
  11056. this._onKeyDown = function (evt) {
  11057. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11058. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11059. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11060. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11061. var index = _this._keys.indexOf(evt.keyCode);
  11062. if (index === -1) {
  11063. _this._keys.push(evt.keyCode);
  11064. }
  11065. if (!noPreventDefault) {
  11066. evt.preventDefault();
  11067. }
  11068. }
  11069. };
  11070. this._onKeyUp = function (evt) {
  11071. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11072. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11073. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11074. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11075. var index = _this._keys.indexOf(evt.keyCode);
  11076. if (index >= 0) {
  11077. _this._keys.splice(index, 1);
  11078. }
  11079. if (!noPreventDefault) {
  11080. evt.preventDefault();
  11081. }
  11082. }
  11083. };
  11084. this._reset = function () {
  11085. _this._keys = [];
  11086. previousPosition = null;
  11087. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11088. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11089. };
  11090. }
  11091. element.addEventListener("mousedown", this._onMouseDown, false);
  11092. element.addEventListener("mouseup", this._onMouseUp, false);
  11093. element.addEventListener("mouseout", this._onMouseOut, false);
  11094. element.addEventListener("mousemove", this._onMouseMove, false);
  11095. BABYLON.Tools.RegisterTopRootEvents([
  11096. { name: "keydown", handler: this._onKeyDown },
  11097. { name: "keyup", handler: this._onKeyUp },
  11098. { name: "blur", handler: this._onLostFocus }
  11099. ]);
  11100. };
  11101. FreeCamera.prototype.detachControl = function (element) {
  11102. if (this._attachedElement !== element) {
  11103. return;
  11104. }
  11105. element.removeEventListener("mousedown", this._onMouseDown);
  11106. element.removeEventListener("mouseup", this._onMouseUp);
  11107. element.removeEventListener("mouseout", this._onMouseOut);
  11108. element.removeEventListener("mousemove", this._onMouseMove);
  11109. BABYLON.Tools.UnregisterTopRootEvents([
  11110. { name: "keydown", handler: this._onKeyDown },
  11111. { name: "keyup", handler: this._onKeyUp },
  11112. { name: "blur", handler: this._onLostFocus }
  11113. ]);
  11114. this._attachedElement = null;
  11115. if (this._reset) {
  11116. this._reset();
  11117. }
  11118. };
  11119. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11120. var globalPosition;
  11121. if (this.parent) {
  11122. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11123. }
  11124. else {
  11125. globalPosition = this.position;
  11126. }
  11127. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11128. this._collider.radius = this.ellipsoid;
  11129. //no need for clone, as long as gravity is not on.
  11130. var actualVelocity = velocity;
  11131. //add gravity to the velocity to prevent the dual-collision checking
  11132. if (this.applyGravity) {
  11133. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11134. actualVelocity = velocity.add(this.getScene().gravity);
  11135. }
  11136. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11137. };
  11138. FreeCamera.prototype._checkInputs = function () {
  11139. if (!this._localDirection) {
  11140. this._localDirection = BABYLON.Vector3.Zero();
  11141. this._transformedDirection = BABYLON.Vector3.Zero();
  11142. }
  11143. // Keyboard
  11144. for (var index = 0; index < this._keys.length; index++) {
  11145. var keyCode = this._keys[index];
  11146. var speed = this._computeLocalCameraSpeed();
  11147. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11148. this._localDirection.copyFromFloats(-speed, 0, 0);
  11149. }
  11150. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11151. this._localDirection.copyFromFloats(0, 0, speed);
  11152. }
  11153. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11154. this._localDirection.copyFromFloats(speed, 0, 0);
  11155. }
  11156. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11157. this._localDirection.copyFromFloats(0, 0, -speed);
  11158. }
  11159. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11160. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11161. this.cameraDirection.addInPlace(this._transformedDirection);
  11162. }
  11163. _super.prototype._checkInputs.call(this);
  11164. };
  11165. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11166. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11167. };
  11168. FreeCamera.prototype._updatePosition = function () {
  11169. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11170. this._collideWithWorld(this.cameraDirection);
  11171. }
  11172. else {
  11173. this.position.addInPlace(this.cameraDirection);
  11174. }
  11175. };
  11176. FreeCamera.prototype.serialize = function () {
  11177. var serializationObject = _super.prototype.serialize.call(this);
  11178. serializationObject.checkCollisions = this.checkCollisions;
  11179. serializationObject.applyGravity = this.applyGravity;
  11180. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11181. return serializationObject;
  11182. };
  11183. return FreeCamera;
  11184. })(BABYLON.TargetCamera);
  11185. BABYLON.FreeCamera = FreeCamera;
  11186. })(BABYLON || (BABYLON = {}));
  11187. var BABYLON;
  11188. (function (BABYLON) {
  11189. var FollowCamera = (function (_super) {
  11190. __extends(FollowCamera, _super);
  11191. function FollowCamera(name, position, scene) {
  11192. _super.call(this, name, position, scene);
  11193. this.radius = 12;
  11194. this.rotationOffset = 0;
  11195. this.heightOffset = 4;
  11196. this.cameraAcceleration = 0.05;
  11197. this.maxCameraSpeed = 20;
  11198. }
  11199. FollowCamera.prototype.getRadians = function (degrees) {
  11200. return degrees * Math.PI / 180;
  11201. };
  11202. FollowCamera.prototype.follow = function (cameraTarget) {
  11203. if (!cameraTarget)
  11204. return;
  11205. var yRotation;
  11206. if (cameraTarget.rotationQuaternion) {
  11207. var rotMatrix = new BABYLON.Matrix();
  11208. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11209. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11210. }
  11211. else {
  11212. yRotation = cameraTarget.rotation.y;
  11213. }
  11214. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11215. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11216. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11217. var dx = targetX - this.position.x;
  11218. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11219. var dz = (targetZ) - this.position.z;
  11220. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11221. var vy = dy * this.cameraAcceleration;
  11222. var vz = dz * this.cameraAcceleration * 2;
  11223. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11224. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11225. }
  11226. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11227. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11228. }
  11229. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11230. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11231. }
  11232. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11233. this.setTarget(cameraTarget.position);
  11234. };
  11235. FollowCamera.prototype._checkInputs = function () {
  11236. _super.prototype._checkInputs.call(this);
  11237. this.follow(this.target);
  11238. };
  11239. FollowCamera.prototype.serialize = function () {
  11240. var serializationObject = _super.prototype.serialize.call(this);
  11241. serializationObject.radius = this.radius;
  11242. serializationObject.heightOffset = this.heightOffset;
  11243. serializationObject.rotationOffset = this.rotationOffset;
  11244. return serializationObject;
  11245. };
  11246. return FollowCamera;
  11247. })(BABYLON.TargetCamera);
  11248. BABYLON.FollowCamera = FollowCamera;
  11249. var ArcFollowCamera = (function (_super) {
  11250. __extends(ArcFollowCamera, _super);
  11251. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11252. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11253. this.alpha = alpha;
  11254. this.beta = beta;
  11255. this.radius = radius;
  11256. this.target = target;
  11257. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11258. this.follow();
  11259. }
  11260. ArcFollowCamera.prototype.follow = function () {
  11261. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11262. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11263. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11264. this.position = this.target.position.add(this._cartesianCoordinates);
  11265. this.setTarget(this.target.position);
  11266. };
  11267. ArcFollowCamera.prototype._checkInputs = function () {
  11268. _super.prototype._checkInputs.call(this);
  11269. this.follow();
  11270. };
  11271. ArcFollowCamera.prototype.serialize = function () {
  11272. var serializationObject = _super.prototype.serialize.call(this);
  11273. serializationObject.radius = this.radius;
  11274. return serializationObject;
  11275. };
  11276. return ArcFollowCamera;
  11277. })(BABYLON.TargetCamera);
  11278. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11279. })(BABYLON || (BABYLON = {}));
  11280. var BABYLON;
  11281. (function (BABYLON) {
  11282. // We're mainly based on the logic defined into the FreeCamera code
  11283. var TouchCamera = (function (_super) {
  11284. __extends(TouchCamera, _super);
  11285. function TouchCamera(name, position, scene) {
  11286. _super.call(this, name, position, scene);
  11287. this._offsetX = null;
  11288. this._offsetY = null;
  11289. this._pointerCount = 0;
  11290. this._pointerPressed = [];
  11291. this.touchAngularSensibility = 200000.0;
  11292. this.touchMoveSensibility = 250.0;
  11293. }
  11294. TouchCamera.prototype._onLostFocus = function (e) {
  11295. this._offsetX = null;
  11296. this._offsetY = null;
  11297. _super.prototype._onLostFocus.call(this, e);
  11298. };
  11299. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11300. var _this = this;
  11301. var previousPosition;
  11302. if (this._attachedCanvas) {
  11303. return;
  11304. }
  11305. if (this._onPointerDown === undefined) {
  11306. this._onPointerDown = function (evt) {
  11307. if (evt.pointerType === "mouse") {
  11308. return;
  11309. }
  11310. if (!noPreventDefault) {
  11311. evt.preventDefault();
  11312. }
  11313. _this._pointerPressed.push(evt.pointerId);
  11314. if (_this._pointerPressed.length !== 1) {
  11315. return;
  11316. }
  11317. previousPosition = {
  11318. x: evt.clientX,
  11319. y: evt.clientY
  11320. };
  11321. };
  11322. this._onPointerUp = function (evt) {
  11323. if (evt.pointerType === "mouse") {
  11324. return;
  11325. }
  11326. if (!noPreventDefault) {
  11327. evt.preventDefault();
  11328. }
  11329. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11330. if (index === -1) {
  11331. return;
  11332. }
  11333. _this._pointerPressed.splice(index, 1);
  11334. if (index != 0) {
  11335. return;
  11336. }
  11337. previousPosition = null;
  11338. _this._offsetX = null;
  11339. _this._offsetY = null;
  11340. };
  11341. this._onPointerMove = function (evt) {
  11342. if (evt.pointerType === "mouse") {
  11343. return;
  11344. }
  11345. if (!noPreventDefault) {
  11346. evt.preventDefault();
  11347. }
  11348. if (!previousPosition) {
  11349. return;
  11350. }
  11351. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11352. if (index != 0) {
  11353. return;
  11354. }
  11355. _this._offsetX = evt.clientX - previousPosition.x;
  11356. _this._offsetY = -(evt.clientY - previousPosition.y);
  11357. };
  11358. }
  11359. canvas.addEventListener("pointerdown", this._onPointerDown);
  11360. canvas.addEventListener("pointerup", this._onPointerUp);
  11361. canvas.addEventListener("pointerout", this._onPointerUp);
  11362. canvas.addEventListener("pointermove", this._onPointerMove);
  11363. _super.prototype.attachControl.call(this, canvas);
  11364. };
  11365. TouchCamera.prototype.detachControl = function (canvas) {
  11366. if (this._attachedCanvas !== canvas) {
  11367. return;
  11368. }
  11369. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11370. canvas.removeEventListener("pointerup", this._onPointerUp);
  11371. canvas.removeEventListener("pointerout", this._onPointerUp);
  11372. canvas.removeEventListener("pointermove", this._onPointerMove);
  11373. _super.prototype.detachControl.call(this, canvas);
  11374. };
  11375. TouchCamera.prototype._checkInputs = function () {
  11376. if (this._offsetX) {
  11377. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11378. if (this._pointerPressed.length > 1) {
  11379. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11380. }
  11381. else {
  11382. var speed = this._computeLocalCameraSpeed();
  11383. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11384. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11385. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11386. }
  11387. }
  11388. _super.prototype._checkInputs.call(this);
  11389. };
  11390. return TouchCamera;
  11391. })(BABYLON.FreeCamera);
  11392. BABYLON.TouchCamera = TouchCamera;
  11393. })(BABYLON || (BABYLON = {}));
  11394. var BABYLON;
  11395. (function (BABYLON) {
  11396. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11397. var ArcRotateCamera = (function (_super) {
  11398. __extends(ArcRotateCamera, _super);
  11399. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11400. var _this = this;
  11401. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11402. this.alpha = alpha;
  11403. this.beta = beta;
  11404. this.radius = radius;
  11405. this.target = target;
  11406. this.inertialAlphaOffset = 0;
  11407. this.inertialBetaOffset = 0;
  11408. this.inertialRadiusOffset = 0;
  11409. this.lowerAlphaLimit = null;
  11410. this.upperAlphaLimit = null;
  11411. this.lowerBetaLimit = 0.01;
  11412. this.upperBetaLimit = Math.PI;
  11413. this.lowerRadiusLimit = null;
  11414. this.upperRadiusLimit = null;
  11415. this.angularSensibilityX = 1000.0;
  11416. this.angularSensibilityY = 1000.0;
  11417. this.wheelPrecision = 3.0;
  11418. this.pinchPrecision = 2.0;
  11419. this.panningSensibility = 50.0;
  11420. this.inertialPanningX = 0;
  11421. this.inertialPanningY = 0;
  11422. this.keysUp = [38];
  11423. this.keysDown = [40];
  11424. this.keysLeft = [37];
  11425. this.keysRight = [39];
  11426. this.zoomOnFactor = 1;
  11427. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11428. this.pinchInwards = true;
  11429. this.allowUpsideDown = true;
  11430. this._keys = [];
  11431. this._viewMatrix = new BABYLON.Matrix();
  11432. // Panning
  11433. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11434. this._isRightClick = false;
  11435. this._isCtrlPushed = false;
  11436. this.checkCollisions = false;
  11437. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11438. this._collider = new BABYLON.Collider();
  11439. this._previousPosition = BABYLON.Vector3.Zero();
  11440. this._collisionVelocity = BABYLON.Vector3.Zero();
  11441. this._newPosition = BABYLON.Vector3.Zero();
  11442. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11443. if (collidedMesh === void 0) { collidedMesh = null; }
  11444. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11445. newPosition.multiplyInPlace(_this._collider.radius);
  11446. }
  11447. if (!collidedMesh) {
  11448. _this._previousPosition.copyFrom(_this.position);
  11449. }
  11450. else {
  11451. _this.setPosition(newPosition);
  11452. if (_this.onCollide) {
  11453. _this.onCollide(collidedMesh);
  11454. }
  11455. }
  11456. // Recompute because of constraints
  11457. var cosa = Math.cos(_this.alpha);
  11458. var sina = Math.sin(_this.alpha);
  11459. var cosb = Math.cos(_this.beta);
  11460. var sinb = Math.sin(_this.beta);
  11461. var target = _this._getTargetPosition();
  11462. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11463. _this.position.copyFrom(_this._newPosition);
  11464. var up = _this.upVector;
  11465. if (_this.allowUpsideDown && _this.beta < 0) {
  11466. up = up.clone();
  11467. up = up.negate();
  11468. }
  11469. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11470. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11471. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11472. _this._collisionTriggered = false;
  11473. };
  11474. if (!this.target) {
  11475. this.target = BABYLON.Vector3.Zero();
  11476. }
  11477. this.getViewMatrix();
  11478. }
  11479. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11480. //deprecated angularSensibility support
  11481. get: function () {
  11482. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11483. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11484. },
  11485. //deprecated angularSensibility support
  11486. set: function (value) {
  11487. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11488. this.angularSensibilityX = value;
  11489. this.angularSensibilityY = value;
  11490. },
  11491. enumerable: true,
  11492. configurable: true
  11493. });
  11494. ArcRotateCamera.prototype._getTargetPosition = function () {
  11495. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11496. };
  11497. // Cache
  11498. ArcRotateCamera.prototype._initCache = function () {
  11499. _super.prototype._initCache.call(this);
  11500. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11501. this._cache.alpha = undefined;
  11502. this._cache.beta = undefined;
  11503. this._cache.radius = undefined;
  11504. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11505. };
  11506. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11507. if (!ignoreParentClass) {
  11508. _super.prototype._updateCache.call(this);
  11509. }
  11510. this._cache.target.copyFrom(this._getTargetPosition());
  11511. this._cache.alpha = this.alpha;
  11512. this._cache.beta = this.beta;
  11513. this._cache.radius = this.radius;
  11514. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11515. };
  11516. // Synchronized
  11517. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11518. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11519. return false;
  11520. return this._cache.target.equals(this._getTargetPosition())
  11521. && this._cache.alpha === this.alpha
  11522. && this._cache.beta === this.beta
  11523. && this._cache.radius === this.radius
  11524. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11525. };
  11526. // Methods
  11527. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11528. var _this = this;
  11529. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11530. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11531. var previousPinchDistance = 0;
  11532. var pointers = new BABYLON.SmartCollection();
  11533. if (this._attachedElement) {
  11534. return;
  11535. }
  11536. this._attachedElement = element;
  11537. var engine = this.getEngine();
  11538. if (this._onPointerDown === undefined) {
  11539. this._onPointerDown = function (evt) {
  11540. // Manage panning with right click
  11541. _this._isRightClick = evt.button === 2;
  11542. // manage pointers
  11543. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11544. cacheSoloPointer = pointers.item(evt.pointerId);
  11545. if (!noPreventDefault) {
  11546. evt.preventDefault();
  11547. }
  11548. };
  11549. this._onPointerUp = function (evt) {
  11550. cacheSoloPointer = null;
  11551. previousPinchDistance = 0;
  11552. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11553. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11554. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11555. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11556. pointers.empty();
  11557. if (!noPreventDefault) {
  11558. evt.preventDefault();
  11559. }
  11560. };
  11561. this._onContextMenu = function (evt) {
  11562. evt.preventDefault();
  11563. };
  11564. this._onPointerMove = function (evt) {
  11565. if (!noPreventDefault) {
  11566. evt.preventDefault();
  11567. }
  11568. switch (pointers.count) {
  11569. case 1:
  11570. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11571. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11572. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11573. }
  11574. else {
  11575. var offsetX = evt.clientX - cacheSoloPointer.x;
  11576. var offsetY = evt.clientY - cacheSoloPointer.y;
  11577. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11578. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11579. }
  11580. cacheSoloPointer.x = evt.clientX;
  11581. cacheSoloPointer.y = evt.clientY;
  11582. break;
  11583. case 2:
  11584. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11585. pointers.item(evt.pointerId).x = evt.clientX;
  11586. pointers.item(evt.pointerId).y = evt.clientY;
  11587. var direction = _this.pinchInwards ? 1 : -1;
  11588. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11589. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11590. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11591. if (previousPinchDistance === 0) {
  11592. previousPinchDistance = pinchSquaredDistance;
  11593. return;
  11594. }
  11595. if (pinchSquaredDistance !== previousPinchDistance) {
  11596. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11597. previousPinchDistance = pinchSquaredDistance;
  11598. }
  11599. break;
  11600. default:
  11601. if (pointers.item(evt.pointerId)) {
  11602. pointers.item(evt.pointerId).x = evt.clientX;
  11603. pointers.item(evt.pointerId).y = evt.clientY;
  11604. }
  11605. }
  11606. };
  11607. this._onMouseMove = function (evt) {
  11608. if (!engine.isPointerLock) {
  11609. return;
  11610. }
  11611. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11612. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11613. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11614. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11615. if (!noPreventDefault) {
  11616. evt.preventDefault();
  11617. }
  11618. };
  11619. this._wheel = function (event) {
  11620. var delta = 0;
  11621. if (event.wheelDelta) {
  11622. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11623. }
  11624. else if (event.detail) {
  11625. delta = -event.detail / _this.wheelPrecision;
  11626. }
  11627. if (delta)
  11628. _this.inertialRadiusOffset += delta;
  11629. if (event.preventDefault) {
  11630. if (!noPreventDefault) {
  11631. event.preventDefault();
  11632. }
  11633. }
  11634. };
  11635. this._onKeyDown = function (evt) {
  11636. _this._isCtrlPushed = evt.ctrlKey;
  11637. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11638. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11639. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11640. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11641. var index = _this._keys.indexOf(evt.keyCode);
  11642. if (index === -1) {
  11643. _this._keys.push(evt.keyCode);
  11644. }
  11645. if (evt.preventDefault) {
  11646. if (!noPreventDefault) {
  11647. evt.preventDefault();
  11648. }
  11649. }
  11650. }
  11651. };
  11652. this._onKeyUp = function (evt) {
  11653. _this._isCtrlPushed = evt.ctrlKey;
  11654. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11655. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11656. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11657. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11658. var index = _this._keys.indexOf(evt.keyCode);
  11659. if (index >= 0) {
  11660. _this._keys.splice(index, 1);
  11661. }
  11662. if (evt.preventDefault) {
  11663. if (!noPreventDefault) {
  11664. evt.preventDefault();
  11665. }
  11666. }
  11667. }
  11668. };
  11669. this._onLostFocus = function () {
  11670. _this._keys = [];
  11671. pointers.empty();
  11672. previousPinchDistance = 0;
  11673. cacheSoloPointer = null;
  11674. };
  11675. this._onGestureStart = function (e) {
  11676. if (window.MSGesture === undefined) {
  11677. return;
  11678. }
  11679. if (!_this._MSGestureHandler) {
  11680. _this._MSGestureHandler = new MSGesture();
  11681. _this._MSGestureHandler.target = element;
  11682. }
  11683. _this._MSGestureHandler.addPointer(e.pointerId);
  11684. };
  11685. this._onGesture = function (e) {
  11686. _this.radius *= e.scale;
  11687. if (e.preventDefault) {
  11688. if (!noPreventDefault) {
  11689. e.stopPropagation();
  11690. e.preventDefault();
  11691. }
  11692. }
  11693. };
  11694. this._reset = function () {
  11695. _this._keys = [];
  11696. _this.inertialAlphaOffset = 0;
  11697. _this.inertialBetaOffset = 0;
  11698. _this.inertialRadiusOffset = 0;
  11699. pointers.empty();
  11700. previousPinchDistance = 0;
  11701. cacheSoloPointer = null;
  11702. };
  11703. }
  11704. if (!useCtrlForPanning) {
  11705. element.addEventListener("contextmenu", this._onContextMenu, false);
  11706. }
  11707. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11708. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11709. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11710. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11711. element.addEventListener("mousemove", this._onMouseMove, false);
  11712. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11713. element.addEventListener("MSGestureChange", this._onGesture, false);
  11714. element.addEventListener('mousewheel', this._wheel, false);
  11715. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11716. BABYLON.Tools.RegisterTopRootEvents([
  11717. { name: "keydown", handler: this._onKeyDown },
  11718. { name: "keyup", handler: this._onKeyUp },
  11719. { name: "blur", handler: this._onLostFocus }
  11720. ]);
  11721. };
  11722. ArcRotateCamera.prototype.detachControl = function (element) {
  11723. if (this._attachedElement !== element) {
  11724. return;
  11725. }
  11726. element.removeEventListener("contextmenu", this._onContextMenu);
  11727. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11728. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11729. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11730. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11731. element.removeEventListener("mousemove", this._onMouseMove);
  11732. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11733. element.removeEventListener("MSGestureChange", this._onGesture);
  11734. element.removeEventListener('mousewheel', this._wheel);
  11735. element.removeEventListener('DOMMouseScroll', this._wheel);
  11736. BABYLON.Tools.UnregisterTopRootEvents([
  11737. { name: "keydown", handler: this._onKeyDown },
  11738. { name: "keyup", handler: this._onKeyUp },
  11739. { name: "blur", handler: this._onLostFocus }
  11740. ]);
  11741. this._MSGestureHandler = null;
  11742. this._attachedElement = null;
  11743. if (this._reset) {
  11744. this._reset();
  11745. }
  11746. };
  11747. ArcRotateCamera.prototype._checkInputs = function () {
  11748. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11749. if (this._collisionTriggered) {
  11750. return;
  11751. }
  11752. // Keyboard
  11753. for (var index = 0; index < this._keys.length; index++) {
  11754. var keyCode = this._keys[index];
  11755. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11756. this.inertialAlphaOffset -= 0.01;
  11757. }
  11758. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11759. this.inertialBetaOffset -= 0.01;
  11760. }
  11761. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11762. this.inertialAlphaOffset += 0.01;
  11763. }
  11764. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11765. this.inertialBetaOffset += 0.01;
  11766. }
  11767. }
  11768. // Inertia
  11769. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11770. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11771. this.beta += this.inertialBetaOffset;
  11772. this.radius -= this.inertialRadiusOffset;
  11773. this.inertialAlphaOffset *= this.inertia;
  11774. this.inertialBetaOffset *= this.inertia;
  11775. this.inertialRadiusOffset *= this.inertia;
  11776. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11777. this.inertialAlphaOffset = 0;
  11778. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11779. this.inertialBetaOffset = 0;
  11780. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11781. this.inertialRadiusOffset = 0;
  11782. }
  11783. // Panning inertia
  11784. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11785. if (!this._localDirection) {
  11786. this._localDirection = BABYLON.Vector3.Zero();
  11787. this._transformedDirection = BABYLON.Vector3.Zero();
  11788. }
  11789. this.inertialPanningX *= this.inertia;
  11790. this.inertialPanningY *= this.inertia;
  11791. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11792. this.inertialPanningX = 0;
  11793. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11794. this.inertialPanningY = 0;
  11795. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11796. this._localDirection.multiplyInPlace(this.panningAxis);
  11797. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11798. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11799. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  11800. if (!this.panningAxis.y) {
  11801. this._transformedDirection.y = 0;
  11802. }
  11803. this.target.addInPlace(this._transformedDirection);
  11804. }
  11805. // Limits
  11806. this._checkLimits();
  11807. _super.prototype._checkInputs.call(this);
  11808. };
  11809. ArcRotateCamera.prototype._checkLimits = function () {
  11810. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11811. if (this.allowUpsideDown && this.beta > Math.PI) {
  11812. this.beta = this.beta - (2 * Math.PI);
  11813. }
  11814. }
  11815. else {
  11816. if (this.beta < this.lowerBetaLimit) {
  11817. this.beta = this.lowerBetaLimit;
  11818. }
  11819. }
  11820. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11821. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11822. this.beta = this.beta + (2 * Math.PI);
  11823. }
  11824. }
  11825. else {
  11826. if (this.beta > this.upperBetaLimit) {
  11827. this.beta = this.upperBetaLimit;
  11828. }
  11829. }
  11830. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11831. this.alpha = this.lowerAlphaLimit;
  11832. }
  11833. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11834. this.alpha = this.upperAlphaLimit;
  11835. }
  11836. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11837. this.radius = this.lowerRadiusLimit;
  11838. }
  11839. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11840. this.radius = this.upperRadiusLimit;
  11841. }
  11842. };
  11843. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  11844. var radiusv3 = this.position.subtract(this._getTargetPosition());
  11845. this.radius = radiusv3.length();
  11846. // Alpha
  11847. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11848. if (radiusv3.z < 0) {
  11849. this.alpha = 2 * Math.PI - this.alpha;
  11850. }
  11851. // Beta
  11852. this.beta = Math.acos(radiusv3.y / this.radius);
  11853. this._checkLimits();
  11854. };
  11855. ArcRotateCamera.prototype.setPosition = function (position) {
  11856. if (this.position.equals(position)) {
  11857. return;
  11858. }
  11859. this.position = position;
  11860. this.rebuildAnglesAndRadius();
  11861. };
  11862. ArcRotateCamera.prototype.setTarget = function (target) {
  11863. if (this.target.equals(target)) {
  11864. return;
  11865. }
  11866. this.target = target;
  11867. this.rebuildAnglesAndRadius();
  11868. };
  11869. ArcRotateCamera.prototype._getViewMatrix = function () {
  11870. // Compute
  11871. var cosa = Math.cos(this.alpha);
  11872. var sina = Math.sin(this.alpha);
  11873. var cosb = Math.cos(this.beta);
  11874. var sinb = Math.sin(this.beta);
  11875. var target = this._getTargetPosition();
  11876. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11877. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11878. this._collider.radius = this.collisionRadius;
  11879. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11880. this._collisionTriggered = true;
  11881. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11882. }
  11883. else {
  11884. this.position.copyFrom(this._newPosition);
  11885. var up = this.upVector;
  11886. if (this.allowUpsideDown && this.beta < 0) {
  11887. up = up.clone();
  11888. up = up.negate();
  11889. }
  11890. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11891. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11892. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11893. }
  11894. return this._viewMatrix;
  11895. };
  11896. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11897. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11898. meshes = meshes || this.getScene().meshes;
  11899. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11900. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11901. this.radius = distance * this.zoomOnFactor;
  11902. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11903. };
  11904. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11905. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11906. var meshesOrMinMaxVector;
  11907. var distance;
  11908. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11909. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11910. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11911. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11912. }
  11913. else {
  11914. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11915. distance = meshesOrMinMaxVectorAndDistance.distance;
  11916. }
  11917. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11918. if (!doNotUpdateMaxZ) {
  11919. this.maxZ = distance * 2;
  11920. }
  11921. };
  11922. /**
  11923. * @override
  11924. * Override Camera.createRigCamera
  11925. */
  11926. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11927. switch (this.cameraRigMode) {
  11928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11931. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11932. case BABYLON.Camera.RIG_MODE_VR:
  11933. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11934. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11935. }
  11936. return null;
  11937. };
  11938. /**
  11939. * @override
  11940. * Override Camera._updateRigCameras
  11941. */
  11942. ArcRotateCamera.prototype._updateRigCameras = function () {
  11943. switch (this.cameraRigMode) {
  11944. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11945. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11946. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11947. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11948. case BABYLON.Camera.RIG_MODE_VR:
  11949. var camLeft = this._rigCameras[0];
  11950. var camRight = this._rigCameras[1];
  11951. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11952. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11953. camLeft.beta = camRight.beta = this.beta;
  11954. camLeft.radius = camRight.radius = this.radius;
  11955. break;
  11956. }
  11957. _super.prototype._updateRigCameras.call(this);
  11958. };
  11959. ArcRotateCamera.prototype.serialize = function () {
  11960. var serializationObject = _super.prototype.serialize.call(this);
  11961. if (this.target instanceof BABYLON.Vector3) {
  11962. serializationObject.target = this.target.asArray();
  11963. }
  11964. if (this.target && this.target.id) {
  11965. serializationObject.lockedTargetId = this.target.id;
  11966. }
  11967. serializationObject.checkCollisions = this.checkCollisions;
  11968. serializationObject.alpha = this.alpha;
  11969. serializationObject.beta = this.beta;
  11970. serializationObject.radius = this.radius;
  11971. return serializationObject;
  11972. };
  11973. return ArcRotateCamera;
  11974. })(BABYLON.TargetCamera);
  11975. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11976. })(BABYLON || (BABYLON = {}));
  11977. var BABYLON;
  11978. (function (BABYLON) {
  11979. var RenderingManager = (function () {
  11980. function RenderingManager(scene) {
  11981. this._renderingGroups = new Array();
  11982. this._scene = scene;
  11983. }
  11984. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11985. if (this._scene._activeParticleSystems.length === 0) {
  11986. return;
  11987. }
  11988. // Particles
  11989. var activeCamera = this._scene.activeCamera;
  11990. var beforeParticlesDate = BABYLON.Tools.Now;
  11991. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11992. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11993. if (particleSystem.renderingGroupId !== index) {
  11994. continue;
  11995. }
  11996. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11997. continue;
  11998. }
  11999. this._clearDepthBuffer();
  12000. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12001. this._scene._activeParticles += particleSystem.render();
  12002. }
  12003. }
  12004. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12005. };
  12006. RenderingManager.prototype._renderSprites = function (index) {
  12007. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12008. return;
  12009. }
  12010. // Sprites
  12011. var activeCamera = this._scene.activeCamera;
  12012. var beforeSpritessDate = BABYLON.Tools.Now;
  12013. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12014. var spriteManager = this._scene.spriteManagers[id];
  12015. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12016. this._clearDepthBuffer();
  12017. spriteManager.render();
  12018. }
  12019. }
  12020. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12021. };
  12022. RenderingManager.prototype._clearDepthBuffer = function () {
  12023. if (this._depthBufferAlreadyCleaned) {
  12024. return;
  12025. }
  12026. this._scene.getEngine().clear(0, false, true);
  12027. this._depthBufferAlreadyCleaned = true;
  12028. };
  12029. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12030. if (this._currentRenderSprites) {
  12031. this._renderSprites(this._currentIndex);
  12032. }
  12033. if (this._currentRenderParticles) {
  12034. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12035. }
  12036. };
  12037. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12038. this._currentActiveMeshes = activeMeshes;
  12039. this._currentRenderParticles = renderParticles;
  12040. this._currentRenderSprites = renderSprites;
  12041. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12042. this._depthBufferAlreadyCleaned = index == 0;
  12043. var renderingGroup = this._renderingGroups[index];
  12044. var needToStepBack = false;
  12045. this._currentIndex = index;
  12046. if (renderingGroup) {
  12047. this._clearDepthBuffer();
  12048. if (!renderingGroup.onBeforeTransparentRendering) {
  12049. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12050. }
  12051. if (!renderingGroup.render(customRenderFunction)) {
  12052. this._renderingGroups.splice(index, 1);
  12053. needToStepBack = true;
  12054. this._renderSpritesAndParticles();
  12055. }
  12056. }
  12057. else {
  12058. this._renderSpritesAndParticles();
  12059. }
  12060. if (needToStepBack) {
  12061. index--;
  12062. }
  12063. }
  12064. };
  12065. RenderingManager.prototype.reset = function () {
  12066. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12067. if (renderingGroup) {
  12068. renderingGroup.prepare();
  12069. }
  12070. });
  12071. };
  12072. RenderingManager.prototype.dispatch = function (subMesh) {
  12073. var mesh = subMesh.getMesh();
  12074. var renderingGroupId = mesh.renderingGroupId || 0;
  12075. if (!this._renderingGroups[renderingGroupId]) {
  12076. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12077. }
  12078. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12079. };
  12080. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12081. return RenderingManager;
  12082. })();
  12083. BABYLON.RenderingManager = RenderingManager;
  12084. })(BABYLON || (BABYLON = {}));
  12085. var BABYLON;
  12086. (function (BABYLON) {
  12087. var RenderingGroup = (function () {
  12088. function RenderingGroup(index, scene) {
  12089. this.index = index;
  12090. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12091. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12092. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12093. this._scene = scene;
  12094. }
  12095. RenderingGroup.prototype.render = function (customRenderFunction) {
  12096. if (customRenderFunction) {
  12097. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12098. return true;
  12099. }
  12100. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12101. if (this.onBeforeTransparentRendering) {
  12102. this.onBeforeTransparentRendering();
  12103. }
  12104. return false;
  12105. }
  12106. var engine = this._scene.getEngine();
  12107. // Opaque
  12108. var subIndex;
  12109. var submesh;
  12110. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12111. submesh = this._opaqueSubMeshes.data[subIndex];
  12112. submesh.render(false);
  12113. }
  12114. // Alpha test
  12115. engine.setAlphaTesting(true);
  12116. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12117. submesh = this._alphaTestSubMeshes.data[subIndex];
  12118. submesh.render(false);
  12119. }
  12120. engine.setAlphaTesting(false);
  12121. if (this.onBeforeTransparentRendering) {
  12122. this.onBeforeTransparentRendering();
  12123. }
  12124. // Transparent
  12125. if (this._transparentSubMeshes.length) {
  12126. // Sorting
  12127. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12128. submesh = this._transparentSubMeshes.data[subIndex];
  12129. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12130. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12131. }
  12132. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12133. sortedArray.sort(function (a, b) {
  12134. // Alpha index first
  12135. if (a._alphaIndex > b._alphaIndex) {
  12136. return 1;
  12137. }
  12138. if (a._alphaIndex < b._alphaIndex) {
  12139. return -1;
  12140. }
  12141. // Then distance to camera
  12142. if (a._distanceToCamera < b._distanceToCamera) {
  12143. return 1;
  12144. }
  12145. if (a._distanceToCamera > b._distanceToCamera) {
  12146. return -1;
  12147. }
  12148. return 0;
  12149. });
  12150. // Rendering
  12151. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12152. submesh = sortedArray[subIndex];
  12153. submesh.render(true);
  12154. }
  12155. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12156. }
  12157. return true;
  12158. };
  12159. RenderingGroup.prototype.prepare = function () {
  12160. this._opaqueSubMeshes.reset();
  12161. this._transparentSubMeshes.reset();
  12162. this._alphaTestSubMeshes.reset();
  12163. };
  12164. RenderingGroup.prototype.dispatch = function (subMesh) {
  12165. var material = subMesh.getMaterial();
  12166. var mesh = subMesh.getMesh();
  12167. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12168. this._transparentSubMeshes.push(subMesh);
  12169. }
  12170. else if (material.needAlphaTesting()) {
  12171. this._alphaTestSubMeshes.push(subMesh);
  12172. }
  12173. else {
  12174. this._opaqueSubMeshes.push(subMesh); // Opaque
  12175. }
  12176. };
  12177. return RenderingGroup;
  12178. })();
  12179. BABYLON.RenderingGroup = RenderingGroup;
  12180. })(BABYLON || (BABYLON = {}));
  12181. var BABYLON;
  12182. (function (BABYLON) {
  12183. /**
  12184. * Represents a scene to be rendered by the engine.
  12185. * @see http://doc.babylonjs.com/page.php?p=21911
  12186. */
  12187. var Scene = (function () {
  12188. /**
  12189. * @constructor
  12190. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12191. */
  12192. function Scene(engine) {
  12193. // Members
  12194. this.autoClear = true;
  12195. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12196. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12197. this.forceWireframe = false;
  12198. this.forcePointsCloud = false;
  12199. this.forceShowBoundingBoxes = false;
  12200. this.animationsEnabled = true;
  12201. this.constantlyUpdateMeshUnderPointer = false;
  12202. 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
  12203. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12204. this._startingPointerTime = 0;
  12205. // Fog
  12206. /**
  12207. * is fog enabled on this scene.
  12208. * @type {boolean}
  12209. */
  12210. this.fogEnabled = true;
  12211. this.fogMode = Scene.FOGMODE_NONE;
  12212. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12213. this.fogDensity = 0.1;
  12214. this.fogStart = 0;
  12215. this.fogEnd = 1000.0;
  12216. // Lights
  12217. /**
  12218. * is shadow enabled on this scene.
  12219. * @type {boolean}
  12220. */
  12221. this.shadowsEnabled = true;
  12222. /**
  12223. * is light enabled on this scene.
  12224. * @type {boolean}
  12225. */
  12226. this.lightsEnabled = true;
  12227. /**
  12228. * All of the lights added to this scene.
  12229. * @see BABYLON.Light
  12230. * @type {BABYLON.Light[]}
  12231. */
  12232. this.lights = new Array();
  12233. // Cameras
  12234. /**
  12235. * All of the cameras added to this scene.
  12236. * @see BABYLON.Camera
  12237. * @type {BABYLON.Camera[]}
  12238. */
  12239. this.cameras = new Array();
  12240. this.activeCameras = new Array();
  12241. // Meshes
  12242. /**
  12243. * All of the (abstract) meshes added to this scene.
  12244. * @see BABYLON.AbstractMesh
  12245. * @type {BABYLON.AbstractMesh[]}
  12246. */
  12247. this.meshes = new Array();
  12248. // Geometries
  12249. this._geometries = new Array();
  12250. this.materials = new Array();
  12251. this.multiMaterials = new Array();
  12252. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12253. // Textures
  12254. this.texturesEnabled = true;
  12255. this.textures = new Array();
  12256. // Particles
  12257. this.particlesEnabled = true;
  12258. this.particleSystems = new Array();
  12259. // Sprites
  12260. this.spritesEnabled = true;
  12261. this.spriteManagers = new Array();
  12262. // Layers
  12263. this.layers = new Array();
  12264. // Skeletons
  12265. this.skeletonsEnabled = true;
  12266. this.skeletons = new Array();
  12267. // Lens flares
  12268. this.lensFlaresEnabled = true;
  12269. this.lensFlareSystems = new Array();
  12270. // Collisions
  12271. this.collisionsEnabled = true;
  12272. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12273. // Postprocesses
  12274. this.postProcessesEnabled = true;
  12275. // Customs render targets
  12276. this.renderTargetsEnabled = true;
  12277. this.dumpNextRenderTargets = false;
  12278. this.customRenderTargets = new Array();
  12279. // Imported meshes
  12280. this.importedMeshesFiles = new Array();
  12281. // Probes
  12282. this.probesEnabled = true;
  12283. this.reflectionProbes = new Array();
  12284. this._actionManagers = new Array();
  12285. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12286. // Procedural textures
  12287. this.proceduralTexturesEnabled = true;
  12288. this._proceduralTextures = new Array();
  12289. this.soundTracks = new Array();
  12290. this._audioEnabled = true;
  12291. this._headphone = false;
  12292. this._totalVertices = 0;
  12293. this._activeIndices = 0;
  12294. this._activeParticles = 0;
  12295. this._lastFrameDuration = 0;
  12296. this._evaluateActiveMeshesDuration = 0;
  12297. this._renderTargetsDuration = 0;
  12298. this._particlesDuration = 0;
  12299. this._renderDuration = 0;
  12300. this._spritesDuration = 0;
  12301. this._animationRatio = 0;
  12302. this._renderId = 0;
  12303. this._executeWhenReadyTimeoutId = -1;
  12304. this._toBeDisposed = new BABYLON.SmartArray(256);
  12305. this._onReadyCallbacks = new Array();
  12306. this._pendingData = []; //ANY
  12307. this._onBeforeRenderCallbacks = new Array();
  12308. this._onAfterRenderCallbacks = new Array();
  12309. this._activeMeshes = new BABYLON.SmartArray(256);
  12310. this._processedMaterials = new BABYLON.SmartArray(256);
  12311. this._renderTargets = new BABYLON.SmartArray(256);
  12312. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12313. this._activeSkeletons = new BABYLON.SmartArray(32);
  12314. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12315. this._activeBones = 0;
  12316. this._activeAnimatables = new Array();
  12317. this._transformMatrix = BABYLON.Matrix.Zero();
  12318. this._edgesRenderers = new BABYLON.SmartArray(16);
  12319. this._uniqueIdCounter = 0;
  12320. this._engine = engine;
  12321. engine.scenes.push(this);
  12322. this._renderingManager = new BABYLON.RenderingManager(this);
  12323. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12324. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12325. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12326. if (BABYLON.OutlineRenderer) {
  12327. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12328. }
  12329. this.attachControl();
  12330. this._debugLayer = new BABYLON.DebugLayer(this);
  12331. if (BABYLON.SoundTrack) {
  12332. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12333. }
  12334. //simplification queue
  12335. if (BABYLON.SimplificationQueue) {
  12336. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12337. }
  12338. //collision coordinator initialization. For now legacy per default.
  12339. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12340. }
  12341. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12342. get: function () {
  12343. return Scene._FOGMODE_NONE;
  12344. },
  12345. enumerable: true,
  12346. configurable: true
  12347. });
  12348. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12349. get: function () {
  12350. return Scene._FOGMODE_EXP;
  12351. },
  12352. enumerable: true,
  12353. configurable: true
  12354. });
  12355. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12356. get: function () {
  12357. return Scene._FOGMODE_EXP2;
  12358. },
  12359. enumerable: true,
  12360. configurable: true
  12361. });
  12362. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12363. get: function () {
  12364. return Scene._FOGMODE_LINEAR;
  12365. },
  12366. enumerable: true,
  12367. configurable: true
  12368. });
  12369. Object.defineProperty(Scene.prototype, "debugLayer", {
  12370. // Properties
  12371. get: function () {
  12372. return this._debugLayer;
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12378. get: function () {
  12379. return this._workerCollisions;
  12380. },
  12381. set: function (enabled) {
  12382. enabled = (enabled && !!Worker);
  12383. this._workerCollisions = enabled;
  12384. if (this.collisionCoordinator) {
  12385. this.collisionCoordinator.destroy();
  12386. }
  12387. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12388. this.collisionCoordinator.init(this);
  12389. },
  12390. enumerable: true,
  12391. configurable: true
  12392. });
  12393. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12394. get: function () {
  12395. return this._selectionOctree;
  12396. },
  12397. enumerable: true,
  12398. configurable: true
  12399. });
  12400. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12401. /**
  12402. * The mesh that is currently under the pointer.
  12403. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12404. */
  12405. get: function () {
  12406. return this._pointerOverMesh;
  12407. },
  12408. enumerable: true,
  12409. configurable: true
  12410. });
  12411. Object.defineProperty(Scene.prototype, "pointerX", {
  12412. /**
  12413. * Current on-screen X position of the pointer
  12414. * @return {number} X position of the pointer
  12415. */
  12416. get: function () {
  12417. return this._pointerX;
  12418. },
  12419. enumerable: true,
  12420. configurable: true
  12421. });
  12422. Object.defineProperty(Scene.prototype, "pointerY", {
  12423. /**
  12424. * Current on-screen Y position of the pointer
  12425. * @return {number} Y position of the pointer
  12426. */
  12427. get: function () {
  12428. return this._pointerY;
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. Scene.prototype.getCachedMaterial = function () {
  12434. return this._cachedMaterial;
  12435. };
  12436. Scene.prototype.getBoundingBoxRenderer = function () {
  12437. return this._boundingBoxRenderer;
  12438. };
  12439. Scene.prototype.getOutlineRenderer = function () {
  12440. return this._outlineRenderer;
  12441. };
  12442. Scene.prototype.getEngine = function () {
  12443. return this._engine;
  12444. };
  12445. Scene.prototype.getTotalVertices = function () {
  12446. return this._totalVertices;
  12447. };
  12448. Scene.prototype.getActiveIndices = function () {
  12449. return this._activeIndices;
  12450. };
  12451. Scene.prototype.getActiveParticles = function () {
  12452. return this._activeParticles;
  12453. };
  12454. Scene.prototype.getActiveBones = function () {
  12455. return this._activeBones;
  12456. };
  12457. // Stats
  12458. Scene.prototype.getLastFrameDuration = function () {
  12459. return this._lastFrameDuration;
  12460. };
  12461. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12462. return this._evaluateActiveMeshesDuration;
  12463. };
  12464. Scene.prototype.getActiveMeshes = function () {
  12465. return this._activeMeshes;
  12466. };
  12467. Scene.prototype.getRenderTargetsDuration = function () {
  12468. return this._renderTargetsDuration;
  12469. };
  12470. Scene.prototype.getRenderDuration = function () {
  12471. return this._renderDuration;
  12472. };
  12473. Scene.prototype.getParticlesDuration = function () {
  12474. return this._particlesDuration;
  12475. };
  12476. Scene.prototype.getSpritesDuration = function () {
  12477. return this._spritesDuration;
  12478. };
  12479. Scene.prototype.getAnimationRatio = function () {
  12480. return this._animationRatio;
  12481. };
  12482. Scene.prototype.getRenderId = function () {
  12483. return this._renderId;
  12484. };
  12485. Scene.prototype.incrementRenderId = function () {
  12486. this._renderId++;
  12487. };
  12488. Scene.prototype._updatePointerPosition = function (evt) {
  12489. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12490. this._pointerX = evt.clientX - canvasRect.left;
  12491. this._pointerY = evt.clientY - canvasRect.top;
  12492. if (this.cameraToUseForPointers) {
  12493. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12494. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12495. }
  12496. };
  12497. // Pointers handling
  12498. Scene.prototype.attachControl = function () {
  12499. var _this = this;
  12500. var spritePredicate = function (sprite) {
  12501. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12502. };
  12503. this._onPointerMove = function (evt) {
  12504. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12505. return;
  12506. }
  12507. var canvas = _this._engine.getRenderingCanvas();
  12508. _this._updatePointerPosition(evt);
  12509. // Meshes
  12510. 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);
  12511. if (pickResult.hit && pickResult.pickedMesh) {
  12512. _this.setPointerOverSprite(null);
  12513. _this.setPointerOverMesh(pickResult.pickedMesh);
  12514. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12515. canvas.style.cursor = "pointer";
  12516. }
  12517. else {
  12518. canvas.style.cursor = "";
  12519. }
  12520. }
  12521. else {
  12522. _this.setPointerOverMesh(null);
  12523. // Sprites
  12524. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12525. if (pickResult.hit && pickResult.pickedSprite) {
  12526. canvas.style.cursor = "pointer";
  12527. _this.setPointerOverSprite(pickResult.pickedSprite);
  12528. }
  12529. else {
  12530. _this.setPointerOverSprite(null);
  12531. // Restore pointer
  12532. canvas.style.cursor = "";
  12533. }
  12534. }
  12535. if (_this.onPointerMove) {
  12536. _this.onPointerMove(evt, pickResult);
  12537. }
  12538. };
  12539. this._onPointerDown = function (evt) {
  12540. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12541. return;
  12542. }
  12543. _this._updatePointerPosition(evt);
  12544. _this._startingPointerPosition.x = _this._pointerX;
  12545. _this._startingPointerPosition.y = _this._pointerY;
  12546. _this._startingPointerTime = new Date().getTime();
  12547. var predicate = null;
  12548. // Meshes
  12549. _this._pickedDownMesh = null;
  12550. if (!_this.onPointerDown && !_this.onPointerPick) {
  12551. predicate = function (mesh) {
  12552. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12553. };
  12554. }
  12555. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12556. if (pickResult.hit && pickResult.pickedMesh) {
  12557. if (pickResult.pickedMesh.actionManager) {
  12558. _this._pickedDownMesh = pickResult.pickedMesh;
  12559. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12560. switch (evt.button) {
  12561. case 0:
  12562. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12563. break;
  12564. case 1:
  12565. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12566. break;
  12567. case 2:
  12568. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12569. break;
  12570. }
  12571. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12572. }
  12573. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12574. var that = _this;
  12575. window.setTimeout(function () {
  12576. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12577. if (pickResult.hit && pickResult.pickedMesh) {
  12578. if (pickResult.pickedMesh.actionManager) {
  12579. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12580. that._startingPointerTime = 0;
  12581. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12582. }
  12583. }
  12584. }
  12585. }, BABYLON.ActionManager.LongPressDelay);
  12586. }
  12587. }
  12588. }
  12589. if (_this.onPointerDown) {
  12590. _this.onPointerDown(evt, pickResult);
  12591. }
  12592. // Sprites
  12593. _this._pickedDownSprite = null;
  12594. if (_this.spriteManagers.length > 0) {
  12595. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12596. if (pickResult.hit && pickResult.pickedSprite) {
  12597. if (pickResult.pickedSprite.actionManager) {
  12598. _this._pickedDownSprite = pickResult.pickedSprite;
  12599. switch (evt.button) {
  12600. case 0:
  12601. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12602. break;
  12603. case 1:
  12604. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12605. break;
  12606. case 2:
  12607. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12608. break;
  12609. }
  12610. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12611. }
  12612. }
  12613. }
  12614. };
  12615. this._onPointerUp = function (evt) {
  12616. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12617. return;
  12618. }
  12619. var predicate = null;
  12620. _this._updatePointerPosition(evt);
  12621. if (!_this.onPointerUp && !_this.onPointerPick) {
  12622. predicate = function (mesh) {
  12623. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12624. };
  12625. }
  12626. // Meshes
  12627. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12628. if (pickResult.hit && pickResult.pickedMesh) {
  12629. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12630. _this.onPointerPick(evt, pickResult);
  12631. }
  12632. if (pickResult.pickedMesh.actionManager) {
  12633. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12634. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12635. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12636. }
  12637. }
  12638. }
  12639. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12640. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12641. }
  12642. if (_this.onPointerUp) {
  12643. _this.onPointerUp(evt, pickResult);
  12644. }
  12645. _this._startingPointerTime = 0;
  12646. // Sprites
  12647. if (_this.spriteManagers.length > 0) {
  12648. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12649. if (pickResult.hit && pickResult.pickedSprite) {
  12650. if (pickResult.pickedSprite.actionManager) {
  12651. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12652. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12654. }
  12655. }
  12656. }
  12657. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12658. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12659. }
  12660. }
  12661. };
  12662. this._onKeyDown = function (evt) {
  12663. if (_this.actionManager) {
  12664. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12665. }
  12666. };
  12667. this._onKeyUp = function (evt) {
  12668. if (_this.actionManager) {
  12669. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12670. }
  12671. };
  12672. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12673. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12674. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12675. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12676. // Wheel
  12677. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12678. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12679. BABYLON.Tools.RegisterTopRootEvents([
  12680. { name: "keydown", handler: this._onKeyDown },
  12681. { name: "keyup", handler: this._onKeyUp }
  12682. ]);
  12683. };
  12684. Scene.prototype.detachControl = function () {
  12685. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12686. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12687. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12688. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12689. // Wheel
  12690. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12691. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12692. BABYLON.Tools.UnregisterTopRootEvents([
  12693. { name: "keydown", handler: this._onKeyDown },
  12694. { name: "keyup", handler: this._onKeyUp }
  12695. ]);
  12696. };
  12697. // Ready
  12698. Scene.prototype.isReady = function () {
  12699. if (this._pendingData.length > 0) {
  12700. return false;
  12701. }
  12702. var index;
  12703. for (index = 0; index < this._geometries.length; index++) {
  12704. var geometry = this._geometries[index];
  12705. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12706. return false;
  12707. }
  12708. }
  12709. for (index = 0; index < this.meshes.length; index++) {
  12710. var mesh = this.meshes[index];
  12711. if (!mesh.isReady()) {
  12712. return false;
  12713. }
  12714. var mat = mesh.material;
  12715. if (mat) {
  12716. if (!mat.isReady(mesh)) {
  12717. return false;
  12718. }
  12719. }
  12720. }
  12721. return true;
  12722. };
  12723. Scene.prototype.resetCachedMaterial = function () {
  12724. this._cachedMaterial = null;
  12725. };
  12726. Scene.prototype.registerBeforeRender = function (func) {
  12727. this._onBeforeRenderCallbacks.push(func);
  12728. };
  12729. Scene.prototype.unregisterBeforeRender = function (func) {
  12730. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12731. if (index > -1) {
  12732. this._onBeforeRenderCallbacks.splice(index, 1);
  12733. }
  12734. };
  12735. Scene.prototype.registerAfterRender = function (func) {
  12736. this._onAfterRenderCallbacks.push(func);
  12737. };
  12738. Scene.prototype.unregisterAfterRender = function (func) {
  12739. var index = this._onAfterRenderCallbacks.indexOf(func);
  12740. if (index > -1) {
  12741. this._onAfterRenderCallbacks.splice(index, 1);
  12742. }
  12743. };
  12744. Scene.prototype._addPendingData = function (data) {
  12745. this._pendingData.push(data);
  12746. };
  12747. Scene.prototype._removePendingData = function (data) {
  12748. var index = this._pendingData.indexOf(data);
  12749. if (index !== -1) {
  12750. this._pendingData.splice(index, 1);
  12751. }
  12752. };
  12753. Scene.prototype.getWaitingItemsCount = function () {
  12754. return this._pendingData.length;
  12755. };
  12756. /**
  12757. * Registers a function to be executed when the scene is ready.
  12758. * @param {Function} func - the function to be executed.
  12759. */
  12760. Scene.prototype.executeWhenReady = function (func) {
  12761. var _this = this;
  12762. this._onReadyCallbacks.push(func);
  12763. if (this._executeWhenReadyTimeoutId !== -1) {
  12764. return;
  12765. }
  12766. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12767. _this._checkIsReady();
  12768. }, 150);
  12769. };
  12770. Scene.prototype._checkIsReady = function () {
  12771. var _this = this;
  12772. if (this.isReady()) {
  12773. this._onReadyCallbacks.forEach(function (func) {
  12774. func();
  12775. });
  12776. this._onReadyCallbacks = [];
  12777. this._executeWhenReadyTimeoutId = -1;
  12778. return;
  12779. }
  12780. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12781. _this._checkIsReady();
  12782. }, 150);
  12783. };
  12784. // Animations
  12785. /**
  12786. * Will start the animation sequence of a given target
  12787. * @param target - the target
  12788. * @param {number} from - from which frame should animation start
  12789. * @param {number} to - till which frame should animation run.
  12790. * @param {boolean} [loop] - should the animation loop
  12791. * @param {number} [speedRatio] - the speed in which to run the animation
  12792. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12793. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12794. * @return {BABYLON.Animatable} the animatable object created for this animation
  12795. * @see BABYLON.Animatable
  12796. * @see http://doc.babylonjs.com/page.php?p=22081
  12797. */
  12798. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12799. if (speedRatio === void 0) { speedRatio = 1.0; }
  12800. this.stopAnimation(target);
  12801. if (!animatable) {
  12802. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12803. }
  12804. // Local animations
  12805. if (target.animations) {
  12806. animatable.appendAnimations(target, target.animations);
  12807. }
  12808. // Children animations
  12809. if (target.getAnimatables) {
  12810. var animatables = target.getAnimatables();
  12811. for (var index = 0; index < animatables.length; index++) {
  12812. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12813. }
  12814. }
  12815. return animatable;
  12816. };
  12817. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12818. if (speedRatio === undefined) {
  12819. speedRatio = 1.0;
  12820. }
  12821. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12822. return animatable;
  12823. };
  12824. Scene.prototype.getAnimatableByTarget = function (target) {
  12825. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12826. if (this._activeAnimatables[index].target === target) {
  12827. return this._activeAnimatables[index];
  12828. }
  12829. }
  12830. return null;
  12831. };
  12832. Object.defineProperty(Scene.prototype, "Animatables", {
  12833. get: function () {
  12834. return this._activeAnimatables;
  12835. },
  12836. enumerable: true,
  12837. configurable: true
  12838. });
  12839. /**
  12840. * Will stop the animation of the given target
  12841. * @param target - the target
  12842. * @see beginAnimation
  12843. */
  12844. Scene.prototype.stopAnimation = function (target) {
  12845. var animatable = this.getAnimatableByTarget(target);
  12846. if (animatable) {
  12847. animatable.stop();
  12848. }
  12849. };
  12850. Scene.prototype._animate = function () {
  12851. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12852. return;
  12853. }
  12854. if (!this._animationStartDate) {
  12855. if (this._pendingData.length > 0) {
  12856. return;
  12857. }
  12858. this._animationStartDate = BABYLON.Tools.Now;
  12859. }
  12860. // Getting time
  12861. var now = BABYLON.Tools.Now;
  12862. var delay = now - this._animationStartDate;
  12863. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12864. this._activeAnimatables[index]._animate(delay);
  12865. }
  12866. };
  12867. // Matrix
  12868. Scene.prototype.getViewMatrix = function () {
  12869. return this._viewMatrix;
  12870. };
  12871. Scene.prototype.getProjectionMatrix = function () {
  12872. return this._projectionMatrix;
  12873. };
  12874. Scene.prototype.getTransformMatrix = function () {
  12875. return this._transformMatrix;
  12876. };
  12877. Scene.prototype.setTransformMatrix = function (view, projection) {
  12878. this._viewMatrix = view;
  12879. this._projectionMatrix = projection;
  12880. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12881. };
  12882. // Methods
  12883. Scene.prototype.addMesh = function (newMesh) {
  12884. newMesh.uniqueId = this._uniqueIdCounter++;
  12885. var position = this.meshes.push(newMesh);
  12886. //notify the collision coordinator
  12887. this.collisionCoordinator.onMeshAdded(newMesh);
  12888. if (this.onNewMeshAdded) {
  12889. this.onNewMeshAdded(newMesh, position, this);
  12890. }
  12891. };
  12892. Scene.prototype.removeMesh = function (toRemove) {
  12893. var index = this.meshes.indexOf(toRemove);
  12894. if (index !== -1) {
  12895. // Remove from the scene if mesh found
  12896. this.meshes.splice(index, 1);
  12897. }
  12898. //notify the collision coordinator
  12899. this.collisionCoordinator.onMeshRemoved(toRemove);
  12900. if (this.onMeshRemoved) {
  12901. this.onMeshRemoved(toRemove);
  12902. }
  12903. return index;
  12904. };
  12905. Scene.prototype.removeSkeleton = function (toRemove) {
  12906. var index = this.skeletons.indexOf(toRemove);
  12907. if (index !== -1) {
  12908. // Remove from the scene if mesh found
  12909. this.skeletons.splice(index, 1);
  12910. }
  12911. return index;
  12912. };
  12913. Scene.prototype.removeLight = function (toRemove) {
  12914. var index = this.lights.indexOf(toRemove);
  12915. if (index !== -1) {
  12916. // Remove from the scene if mesh found
  12917. this.lights.splice(index, 1);
  12918. }
  12919. if (this.onLightRemoved) {
  12920. this.onLightRemoved(toRemove);
  12921. }
  12922. return index;
  12923. };
  12924. Scene.prototype.removeCamera = function (toRemove) {
  12925. var index = this.cameras.indexOf(toRemove);
  12926. if (index !== -1) {
  12927. // Remove from the scene if mesh found
  12928. this.cameras.splice(index, 1);
  12929. }
  12930. // Remove from activeCameras
  12931. var index2 = this.activeCameras.indexOf(toRemove);
  12932. if (index2 !== -1) {
  12933. // Remove from the scene if mesh found
  12934. this.activeCameras.splice(index2, 1);
  12935. }
  12936. // Reset the activeCamera
  12937. if (this.activeCamera === toRemove) {
  12938. if (this.cameras.length > 0) {
  12939. this.activeCamera = this.cameras[0];
  12940. }
  12941. else {
  12942. this.activeCamera = null;
  12943. }
  12944. }
  12945. if (this.onCameraRemoved) {
  12946. this.onCameraRemoved(toRemove);
  12947. }
  12948. return index;
  12949. };
  12950. Scene.prototype.addLight = function (newLight) {
  12951. newLight.uniqueId = this._uniqueIdCounter++;
  12952. var position = this.lights.push(newLight);
  12953. if (this.onNewLightAdded) {
  12954. this.onNewLightAdded(newLight, position, this);
  12955. }
  12956. };
  12957. Scene.prototype.addCamera = function (newCamera) {
  12958. newCamera.uniqueId = this._uniqueIdCounter++;
  12959. var position = this.cameras.push(newCamera);
  12960. if (this.onNewCameraAdded) {
  12961. this.onNewCameraAdded(newCamera, position, this);
  12962. }
  12963. };
  12964. /**
  12965. * Switch active camera
  12966. * @param {Camera} newCamera - new active camera
  12967. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  12968. */
  12969. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  12970. if (attachControl === void 0) { attachControl = true; }
  12971. var canvas = this._engine.getRenderingCanvas();
  12972. this.activeCamera.detachControl(canvas);
  12973. this.activeCamera = newCamera;
  12974. if (attachControl) {
  12975. newCamera.attachControl(canvas);
  12976. }
  12977. };
  12978. /**
  12979. * sets the active camera of the scene using its ID
  12980. * @param {string} id - the camera's ID
  12981. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12982. * @see activeCamera
  12983. */
  12984. Scene.prototype.setActiveCameraByID = function (id) {
  12985. var camera = this.getCameraByID(id);
  12986. if (camera) {
  12987. this.activeCamera = camera;
  12988. return camera;
  12989. }
  12990. return null;
  12991. };
  12992. /**
  12993. * sets the active camera of the scene using its name
  12994. * @param {string} name - the camera's name
  12995. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12996. * @see activeCamera
  12997. */
  12998. Scene.prototype.setActiveCameraByName = function (name) {
  12999. var camera = this.getCameraByName(name);
  13000. if (camera) {
  13001. this.activeCamera = camera;
  13002. return camera;
  13003. }
  13004. return null;
  13005. };
  13006. /**
  13007. * get a material using its id
  13008. * @param {string} the material's ID
  13009. * @return {BABYLON.Material|null} the material or null if none found.
  13010. */
  13011. Scene.prototype.getMaterialByID = function (id) {
  13012. for (var index = 0; index < this.materials.length; index++) {
  13013. if (this.materials[index].id === id) {
  13014. return this.materials[index];
  13015. }
  13016. }
  13017. return null;
  13018. };
  13019. /**
  13020. * get a material using its name
  13021. * @param {string} the material's name
  13022. * @return {BABYLON.Material|null} the material or null if none found.
  13023. */
  13024. Scene.prototype.getMaterialByName = function (name) {
  13025. for (var index = 0; index < this.materials.length; index++) {
  13026. if (this.materials[index].name === name) {
  13027. return this.materials[index];
  13028. }
  13029. }
  13030. return null;
  13031. };
  13032. Scene.prototype.getLensFlareSystemByName = function (name) {
  13033. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13034. if (this.lensFlareSystems[index].name === name) {
  13035. return this.lensFlareSystems[index];
  13036. }
  13037. }
  13038. return null;
  13039. };
  13040. Scene.prototype.getCameraByID = function (id) {
  13041. for (var index = 0; index < this.cameras.length; index++) {
  13042. if (this.cameras[index].id === id) {
  13043. return this.cameras[index];
  13044. }
  13045. }
  13046. return null;
  13047. };
  13048. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13049. for (var index = 0; index < this.cameras.length; index++) {
  13050. if (this.cameras[index].uniqueId === uniqueId) {
  13051. return this.cameras[index];
  13052. }
  13053. }
  13054. return null;
  13055. };
  13056. /**
  13057. * get a camera using its name
  13058. * @param {string} the camera's name
  13059. * @return {BABYLON.Camera|null} the camera or null if none found.
  13060. */
  13061. Scene.prototype.getCameraByName = function (name) {
  13062. for (var index = 0; index < this.cameras.length; index++) {
  13063. if (this.cameras[index].name === name) {
  13064. return this.cameras[index];
  13065. }
  13066. }
  13067. return null;
  13068. };
  13069. /**
  13070. * get a bone using its id
  13071. * @param {string} the bone's id
  13072. * @return {BABYLON.Bone|null} the bone or null if not found
  13073. */
  13074. Scene.prototype.getBoneByID = function (id) {
  13075. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13076. var skeleton = this.skeletons[skeletonIndex];
  13077. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13078. if (skeleton.bones[boneIndex].id === id) {
  13079. return skeleton.bones[boneIndex];
  13080. }
  13081. }
  13082. }
  13083. return null;
  13084. };
  13085. /**
  13086. * get a bone using its id
  13087. * @param {string} the bone's name
  13088. * @return {BABYLON.Bone|null} the bone or null if not found
  13089. */
  13090. Scene.prototype.getBoneByName = function (name) {
  13091. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13092. var skeleton = this.skeletons[skeletonIndex];
  13093. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13094. if (skeleton.bones[boneIndex].name === name) {
  13095. return skeleton.bones[boneIndex];
  13096. }
  13097. }
  13098. }
  13099. return null;
  13100. };
  13101. /**
  13102. * get a light node using its name
  13103. * @param {string} the light's name
  13104. * @return {BABYLON.Light|null} the light or null if none found.
  13105. */
  13106. Scene.prototype.getLightByName = function (name) {
  13107. for (var index = 0; index < this.lights.length; index++) {
  13108. if (this.lights[index].name === name) {
  13109. return this.lights[index];
  13110. }
  13111. }
  13112. return null;
  13113. };
  13114. /**
  13115. * get a light node using its ID
  13116. * @param {string} the light's id
  13117. * @return {BABYLON.Light|null} the light or null if none found.
  13118. */
  13119. Scene.prototype.getLightByID = function (id) {
  13120. for (var index = 0; index < this.lights.length; index++) {
  13121. if (this.lights[index].id === id) {
  13122. return this.lights[index];
  13123. }
  13124. }
  13125. return null;
  13126. };
  13127. /**
  13128. * get a light node using its scene-generated unique ID
  13129. * @param {number} the light's unique id
  13130. * @return {BABYLON.Light|null} the light or null if none found.
  13131. */
  13132. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13133. for (var index = 0; index < this.lights.length; index++) {
  13134. if (this.lights[index].uniqueId === uniqueId) {
  13135. return this.lights[index];
  13136. }
  13137. }
  13138. return null;
  13139. };
  13140. /**
  13141. * get a particle system by id
  13142. * @param id {number} the particle system id
  13143. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13144. */
  13145. Scene.prototype.getParticleSystemByID = function (id) {
  13146. for (var index = 0; index < this.particleSystems.length; index++) {
  13147. if (this.particleSystems[index].id === id) {
  13148. return this.particleSystems[index];
  13149. }
  13150. }
  13151. return null;
  13152. };
  13153. /**
  13154. * get a geometry using its ID
  13155. * @param {string} the geometry's id
  13156. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13157. */
  13158. Scene.prototype.getGeometryByID = function (id) {
  13159. for (var index = 0; index < this._geometries.length; index++) {
  13160. if (this._geometries[index].id === id) {
  13161. return this._geometries[index];
  13162. }
  13163. }
  13164. return null;
  13165. };
  13166. /**
  13167. * add a new geometry to this scene.
  13168. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13169. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13170. * @return {boolean} was the geometry added or not
  13171. */
  13172. Scene.prototype.pushGeometry = function (geometry, force) {
  13173. if (!force && this.getGeometryByID(geometry.id)) {
  13174. return false;
  13175. }
  13176. this._geometries.push(geometry);
  13177. //notify the collision coordinator
  13178. this.collisionCoordinator.onGeometryAdded(geometry);
  13179. if (this.onGeometryAdded) {
  13180. this.onGeometryAdded(geometry);
  13181. }
  13182. return true;
  13183. };
  13184. /**
  13185. * Removes an existing geometry
  13186. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13187. * @return {boolean} was the geometry removed or not
  13188. */
  13189. Scene.prototype.removeGeometry = function (geometry) {
  13190. var index = this._geometries.indexOf(geometry);
  13191. if (index > -1) {
  13192. this._geometries.splice(index, 1);
  13193. //notify the collision coordinator
  13194. this.collisionCoordinator.onGeometryDeleted(geometry);
  13195. if (this.onGeometryRemoved) {
  13196. this.onGeometryRemoved(geometry);
  13197. }
  13198. return true;
  13199. }
  13200. return false;
  13201. };
  13202. Scene.prototype.getGeometries = function () {
  13203. return this._geometries;
  13204. };
  13205. /**
  13206. * Get the first added mesh found of a given ID
  13207. * @param {string} id - the id to search for
  13208. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13209. */
  13210. Scene.prototype.getMeshByID = function (id) {
  13211. for (var index = 0; index < this.meshes.length; index++) {
  13212. if (this.meshes[index].id === id) {
  13213. return this.meshes[index];
  13214. }
  13215. }
  13216. return null;
  13217. };
  13218. /**
  13219. * Get a mesh with its auto-generated unique id
  13220. * @param {number} uniqueId - the unique id to search for
  13221. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13222. */
  13223. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13224. for (var index = 0; index < this.meshes.length; index++) {
  13225. if (this.meshes[index].uniqueId === uniqueId) {
  13226. return this.meshes[index];
  13227. }
  13228. }
  13229. return null;
  13230. };
  13231. /**
  13232. * Get a the last added mesh found of a given ID
  13233. * @param {string} id - the id to search for
  13234. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13235. */
  13236. Scene.prototype.getLastMeshByID = function (id) {
  13237. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13238. if (this.meshes[index].id === id) {
  13239. return this.meshes[index];
  13240. }
  13241. }
  13242. return null;
  13243. };
  13244. /**
  13245. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13246. * @param {string} id - the id to search for
  13247. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13248. */
  13249. Scene.prototype.getLastEntryByID = function (id) {
  13250. var index;
  13251. for (index = this.meshes.length - 1; index >= 0; index--) {
  13252. if (this.meshes[index].id === id) {
  13253. return this.meshes[index];
  13254. }
  13255. }
  13256. for (index = this.cameras.length - 1; index >= 0; index--) {
  13257. if (this.cameras[index].id === id) {
  13258. return this.cameras[index];
  13259. }
  13260. }
  13261. for (index = this.lights.length - 1; index >= 0; index--) {
  13262. if (this.lights[index].id === id) {
  13263. return this.lights[index];
  13264. }
  13265. }
  13266. return null;
  13267. };
  13268. Scene.prototype.getNodeByID = function (id) {
  13269. var mesh = this.getMeshByID(id);
  13270. if (mesh) {
  13271. return mesh;
  13272. }
  13273. var light = this.getLightByID(id);
  13274. if (light) {
  13275. return light;
  13276. }
  13277. var camera = this.getCameraByID(id);
  13278. if (camera) {
  13279. return camera;
  13280. }
  13281. var bone = this.getBoneByID(id);
  13282. return bone;
  13283. };
  13284. Scene.prototype.getNodeByName = function (name) {
  13285. var mesh = this.getMeshByName(name);
  13286. if (mesh) {
  13287. return mesh;
  13288. }
  13289. var light = this.getLightByName(name);
  13290. if (light) {
  13291. return light;
  13292. }
  13293. var camera = this.getCameraByName(name);
  13294. if (camera) {
  13295. return camera;
  13296. }
  13297. var bone = this.getBoneByName(name);
  13298. return bone;
  13299. };
  13300. Scene.prototype.getMeshByName = function (name) {
  13301. for (var index = 0; index < this.meshes.length; index++) {
  13302. if (this.meshes[index].name === name) {
  13303. return this.meshes[index];
  13304. }
  13305. }
  13306. return null;
  13307. };
  13308. Scene.prototype.getSoundByName = function (name) {
  13309. var index;
  13310. if (BABYLON.AudioEngine) {
  13311. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13312. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13313. return this.mainSoundTrack.soundCollection[index];
  13314. }
  13315. }
  13316. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13317. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13318. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13319. return this.soundTracks[sdIndex].soundCollection[index];
  13320. }
  13321. }
  13322. }
  13323. }
  13324. return null;
  13325. };
  13326. Scene.prototype.getLastSkeletonByID = function (id) {
  13327. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13328. if (this.skeletons[index].id === id) {
  13329. return this.skeletons[index];
  13330. }
  13331. }
  13332. return null;
  13333. };
  13334. Scene.prototype.getSkeletonById = function (id) {
  13335. for (var index = 0; index < this.skeletons.length; index++) {
  13336. if (this.skeletons[index].id === id) {
  13337. return this.skeletons[index];
  13338. }
  13339. }
  13340. return null;
  13341. };
  13342. Scene.prototype.getSkeletonByName = function (name) {
  13343. for (var index = 0; index < this.skeletons.length; index++) {
  13344. if (this.skeletons[index].name === name) {
  13345. return this.skeletons[index];
  13346. }
  13347. }
  13348. return null;
  13349. };
  13350. Scene.prototype.isActiveMesh = function (mesh) {
  13351. return (this._activeMeshes.indexOf(mesh) !== -1);
  13352. };
  13353. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13354. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13355. var material = subMesh.getMaterial();
  13356. if (mesh.showSubMeshesBoundingBox) {
  13357. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13358. }
  13359. if (material) {
  13360. // Render targets
  13361. if (material.getRenderTargetTextures) {
  13362. if (this._processedMaterials.indexOf(material) === -1) {
  13363. this._processedMaterials.push(material);
  13364. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13365. }
  13366. }
  13367. // Dispatch
  13368. this._activeIndices += subMesh.indexCount;
  13369. this._renderingManager.dispatch(subMesh);
  13370. }
  13371. }
  13372. };
  13373. Scene.prototype._evaluateActiveMeshes = function () {
  13374. this.activeCamera._activeMeshes.reset();
  13375. this._activeMeshes.reset();
  13376. this._renderingManager.reset();
  13377. this._processedMaterials.reset();
  13378. this._activeParticleSystems.reset();
  13379. this._activeSkeletons.reset();
  13380. this._softwareSkinnedMeshes.reset();
  13381. this._boundingBoxRenderer.reset();
  13382. this._edgesRenderers.reset();
  13383. if (!this._frustumPlanes) {
  13384. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13385. }
  13386. else {
  13387. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13388. }
  13389. // Meshes
  13390. var meshes;
  13391. var len;
  13392. if (this._selectionOctree) {
  13393. var selection = this._selectionOctree.select(this._frustumPlanes);
  13394. meshes = selection.data;
  13395. len = selection.length;
  13396. }
  13397. else {
  13398. len = this.meshes.length;
  13399. meshes = this.meshes;
  13400. }
  13401. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13402. var mesh = meshes[meshIndex];
  13403. if (mesh.isBlocked) {
  13404. continue;
  13405. }
  13406. this._totalVertices += mesh.getTotalVertices();
  13407. if (!mesh.isReady() || !mesh.isEnabled()) {
  13408. continue;
  13409. }
  13410. mesh.computeWorldMatrix();
  13411. // Intersections
  13412. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13413. this._meshesForIntersections.pushNoDuplicate(mesh);
  13414. }
  13415. // Switch to current LOD
  13416. var meshLOD = mesh.getLOD(this.activeCamera);
  13417. if (!meshLOD) {
  13418. continue;
  13419. }
  13420. mesh._preActivate();
  13421. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13422. this._activeMeshes.push(mesh);
  13423. this.activeCamera._activeMeshes.push(mesh);
  13424. mesh._activate(this._renderId);
  13425. this._activeMesh(meshLOD);
  13426. }
  13427. }
  13428. // Particle systems
  13429. var beforeParticlesDate = BABYLON.Tools.Now;
  13430. if (this.particlesEnabled) {
  13431. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13432. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13433. var particleSystem = this.particleSystems[particleIndex];
  13434. if (!particleSystem.isStarted()) {
  13435. continue;
  13436. }
  13437. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13438. this._activeParticleSystems.push(particleSystem);
  13439. particleSystem.animate();
  13440. }
  13441. }
  13442. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13443. }
  13444. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13445. };
  13446. Scene.prototype._activeMesh = function (mesh) {
  13447. if (mesh.skeleton && this.skeletonsEnabled) {
  13448. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13449. if (!mesh.computeBonesUsingShaders) {
  13450. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13451. }
  13452. }
  13453. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13454. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13455. }
  13456. if (mesh._edgesRenderer) {
  13457. this._edgesRenderers.push(mesh._edgesRenderer);
  13458. }
  13459. if (mesh && mesh.subMeshes) {
  13460. // Submeshes Octrees
  13461. var len;
  13462. var subMeshes;
  13463. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13464. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13465. len = intersections.length;
  13466. subMeshes = intersections.data;
  13467. }
  13468. else {
  13469. subMeshes = mesh.subMeshes;
  13470. len = subMeshes.length;
  13471. }
  13472. for (var subIndex = 0; subIndex < len; subIndex++) {
  13473. var subMesh = subMeshes[subIndex];
  13474. this._evaluateSubMesh(subMesh, mesh);
  13475. }
  13476. }
  13477. };
  13478. Scene.prototype.updateTransformMatrix = function (force) {
  13479. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13480. };
  13481. Scene.prototype._renderForCamera = function (camera) {
  13482. var engine = this._engine;
  13483. this.activeCamera = camera;
  13484. if (!this.activeCamera)
  13485. throw new Error("Active camera not set");
  13486. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13487. // Viewport
  13488. engine.setViewport(this.activeCamera.viewport);
  13489. // Camera
  13490. this.resetCachedMaterial();
  13491. this._renderId++;
  13492. this.updateTransformMatrix();
  13493. if (this.beforeCameraRender) {
  13494. this.beforeCameraRender(this.activeCamera);
  13495. }
  13496. // Meshes
  13497. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13498. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13499. this._evaluateActiveMeshes();
  13500. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13501. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13502. // Skeletons
  13503. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13504. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13505. skeleton.prepare();
  13506. }
  13507. // Software skinning
  13508. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13509. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13510. mesh.applySkeleton(mesh.skeleton);
  13511. }
  13512. // Render targets
  13513. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13514. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13515. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13516. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13517. var renderTarget = this._renderTargets.data[renderIndex];
  13518. if (renderTarget._shouldRender()) {
  13519. this._renderId++;
  13520. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13521. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13522. }
  13523. }
  13524. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13525. this._renderId++;
  13526. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13527. }
  13528. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13529. // Prepare Frame
  13530. this.postProcessManager._prepareFrame();
  13531. var beforeRenderDate = BABYLON.Tools.Now;
  13532. // Backgrounds
  13533. var layerIndex;
  13534. var layer;
  13535. if (this.layers.length) {
  13536. engine.setDepthBuffer(false);
  13537. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13538. layer = this.layers[layerIndex];
  13539. if (layer.isBackground) {
  13540. layer.render();
  13541. }
  13542. }
  13543. engine.setDepthBuffer(true);
  13544. }
  13545. // Render
  13546. BABYLON.Tools.StartPerformanceCounter("Main render");
  13547. this._renderingManager.render(null, null, true, true);
  13548. BABYLON.Tools.EndPerformanceCounter("Main render");
  13549. // Bounding boxes
  13550. this._boundingBoxRenderer.render();
  13551. // Edges
  13552. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13553. this._edgesRenderers.data[edgesRendererIndex].render();
  13554. }
  13555. // Lens flares
  13556. if (this.lensFlaresEnabled) {
  13557. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13558. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13559. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13560. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13561. lensFlareSystem.render();
  13562. }
  13563. }
  13564. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13565. }
  13566. // Foregrounds
  13567. if (this.layers.length) {
  13568. engine.setDepthBuffer(false);
  13569. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13570. layer = this.layers[layerIndex];
  13571. if (!layer.isBackground) {
  13572. layer.render();
  13573. }
  13574. }
  13575. engine.setDepthBuffer(true);
  13576. }
  13577. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13578. // Finalize frame
  13579. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13580. // Update camera
  13581. this.activeCamera._updateFromScene();
  13582. // Reset some special arrays
  13583. this._renderTargets.reset();
  13584. if (this.afterCameraRender) {
  13585. this.afterCameraRender(this.activeCamera);
  13586. }
  13587. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13588. };
  13589. Scene.prototype._processSubCameras = function (camera) {
  13590. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13591. this._renderForCamera(camera);
  13592. return;
  13593. }
  13594. // rig cameras
  13595. for (var index = 0; index < camera._rigCameras.length; index++) {
  13596. this._renderForCamera(camera._rigCameras[index]);
  13597. }
  13598. this.activeCamera = camera;
  13599. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13600. // Update camera
  13601. this.activeCamera._updateFromScene();
  13602. };
  13603. Scene.prototype._checkIntersections = function () {
  13604. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13605. var sourceMesh = this._meshesForIntersections.data[index];
  13606. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13607. var action = sourceMesh.actionManager.actions[actionIndex];
  13608. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13609. var parameters = action.getTriggerParameter();
  13610. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13611. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13612. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13613. if (areIntersecting && currentIntersectionInProgress === -1) {
  13614. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13615. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13616. sourceMesh._intersectionsInProgress.push(otherMesh);
  13617. }
  13618. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13619. sourceMesh._intersectionsInProgress.push(otherMesh);
  13620. }
  13621. }
  13622. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13623. //They intersected, and now they don't.
  13624. //is this trigger an exit trigger? execute an event.
  13625. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13626. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13627. }
  13628. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13629. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13630. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13631. }
  13632. }
  13633. }
  13634. }
  13635. }
  13636. };
  13637. Scene.prototype.render = function () {
  13638. var startDate = BABYLON.Tools.Now;
  13639. this._particlesDuration = 0;
  13640. this._spritesDuration = 0;
  13641. this._activeParticles = 0;
  13642. this._renderDuration = 0;
  13643. this._renderTargetsDuration = 0;
  13644. this._evaluateActiveMeshesDuration = 0;
  13645. this._totalVertices = 0;
  13646. this._activeIndices = 0;
  13647. this._activeBones = 0;
  13648. this.getEngine().resetDrawCalls();
  13649. this._meshesForIntersections.reset();
  13650. this.resetCachedMaterial();
  13651. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13652. // Actions
  13653. if (this.actionManager) {
  13654. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13655. }
  13656. //Simplification Queue
  13657. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13658. this.simplificationQueue.executeNext();
  13659. }
  13660. // Animations
  13661. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13662. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13663. this._animate();
  13664. // Physics
  13665. if (this._physicsEngine) {
  13666. BABYLON.Tools.StartPerformanceCounter("Physics");
  13667. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13668. BABYLON.Tools.EndPerformanceCounter("Physics");
  13669. }
  13670. // Before render
  13671. if (this.beforeRender) {
  13672. this.beforeRender();
  13673. }
  13674. var callbackIndex;
  13675. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13676. this._onBeforeRenderCallbacks[callbackIndex]();
  13677. }
  13678. // Customs render targets
  13679. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13680. var engine = this.getEngine();
  13681. var currentActiveCamera = this.activeCamera;
  13682. if (this.renderTargetsEnabled) {
  13683. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13684. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13685. var renderTarget = this.customRenderTargets[customIndex];
  13686. if (renderTarget._shouldRender()) {
  13687. this._renderId++;
  13688. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13689. if (!this.activeCamera)
  13690. throw new Error("Active camera not set");
  13691. // Viewport
  13692. engine.setViewport(this.activeCamera.viewport);
  13693. // Camera
  13694. this.updateTransformMatrix();
  13695. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13696. }
  13697. }
  13698. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13699. this._renderId++;
  13700. }
  13701. if (this.customRenderTargets.length > 0) {
  13702. engine.restoreDefaultFramebuffer();
  13703. }
  13704. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13705. this.activeCamera = currentActiveCamera;
  13706. // Procedural textures
  13707. if (this.proceduralTexturesEnabled) {
  13708. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13709. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13710. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13711. if (proceduralTexture._shouldRender()) {
  13712. proceduralTexture.render();
  13713. }
  13714. }
  13715. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13716. }
  13717. // Clear
  13718. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13719. // Shadows
  13720. if (this.shadowsEnabled) {
  13721. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13722. var light = this.lights[lightIndex];
  13723. var shadowGenerator = light.getShadowGenerator();
  13724. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13725. this._renderTargets.push(shadowGenerator.getShadowMap());
  13726. }
  13727. }
  13728. }
  13729. // Depth renderer
  13730. if (this._depthRenderer) {
  13731. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13732. }
  13733. // RenderPipeline
  13734. this.postProcessRenderPipelineManager.update();
  13735. // Multi-cameras?
  13736. if (this.activeCameras.length > 0) {
  13737. var currentRenderId = this._renderId;
  13738. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13739. this._renderId = currentRenderId;
  13740. if (cameraIndex > 0) {
  13741. this._engine.clear(0, false, true);
  13742. }
  13743. this._processSubCameras(this.activeCameras[cameraIndex]);
  13744. }
  13745. }
  13746. else {
  13747. if (!this.activeCamera) {
  13748. throw new Error("No camera defined");
  13749. }
  13750. this._processSubCameras(this.activeCamera);
  13751. }
  13752. // Intersection checks
  13753. this._checkIntersections();
  13754. // Update the audio listener attached to the camera
  13755. if (BABYLON.AudioEngine) {
  13756. this._updateAudioParameters();
  13757. }
  13758. // After render
  13759. if (this.afterRender) {
  13760. this.afterRender();
  13761. }
  13762. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13763. this._onAfterRenderCallbacks[callbackIndex]();
  13764. }
  13765. // Cleaning
  13766. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13767. this._toBeDisposed.data[index].dispose();
  13768. this._toBeDisposed[index] = null;
  13769. }
  13770. this._toBeDisposed.reset();
  13771. if (this.dumpNextRenderTargets) {
  13772. this.dumpNextRenderTargets = false;
  13773. }
  13774. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13775. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13776. };
  13777. Scene.prototype._updateAudioParameters = function () {
  13778. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13779. return;
  13780. }
  13781. var listeningCamera;
  13782. var audioEngine = BABYLON.Engine.audioEngine;
  13783. if (this.activeCameras.length > 0) {
  13784. listeningCamera = this.activeCameras[0];
  13785. }
  13786. else {
  13787. listeningCamera = this.activeCamera;
  13788. }
  13789. if (listeningCamera && audioEngine.canUseWebAudio) {
  13790. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13791. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13792. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13793. cameraDirection.normalize();
  13794. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13795. var i;
  13796. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13797. var sound = this.mainSoundTrack.soundCollection[i];
  13798. if (sound.useCustomAttenuation) {
  13799. sound.updateDistanceFromListener();
  13800. }
  13801. }
  13802. for (i = 0; i < this.soundTracks.length; i++) {
  13803. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13804. sound = this.soundTracks[i].soundCollection[j];
  13805. if (sound.useCustomAttenuation) {
  13806. sound.updateDistanceFromListener();
  13807. }
  13808. }
  13809. }
  13810. }
  13811. };
  13812. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13813. // Audio
  13814. get: function () {
  13815. return this._audioEnabled;
  13816. },
  13817. set: function (value) {
  13818. this._audioEnabled = value;
  13819. if (BABYLON.AudioEngine) {
  13820. if (this._audioEnabled) {
  13821. this._enableAudio();
  13822. }
  13823. else {
  13824. this._disableAudio();
  13825. }
  13826. }
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Scene.prototype._disableAudio = function () {
  13832. var i;
  13833. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13834. this.mainSoundTrack.soundCollection[i].pause();
  13835. }
  13836. for (i = 0; i < this.soundTracks.length; i++) {
  13837. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13838. this.soundTracks[i].soundCollection[j].pause();
  13839. }
  13840. }
  13841. };
  13842. Scene.prototype._enableAudio = function () {
  13843. var i;
  13844. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13845. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13846. this.mainSoundTrack.soundCollection[i].play();
  13847. }
  13848. }
  13849. for (i = 0; i < this.soundTracks.length; i++) {
  13850. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13851. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13852. this.soundTracks[i].soundCollection[j].play();
  13853. }
  13854. }
  13855. }
  13856. };
  13857. Object.defineProperty(Scene.prototype, "headphone", {
  13858. get: function () {
  13859. return this._headphone;
  13860. },
  13861. set: function (value) {
  13862. this._headphone = value;
  13863. if (BABYLON.AudioEngine) {
  13864. if (this._headphone) {
  13865. this._switchAudioModeForHeadphones();
  13866. }
  13867. else {
  13868. this._switchAudioModeForNormalSpeakers();
  13869. }
  13870. }
  13871. },
  13872. enumerable: true,
  13873. configurable: true
  13874. });
  13875. Scene.prototype._switchAudioModeForHeadphones = function () {
  13876. this.mainSoundTrack.switchPanningModelToHRTF();
  13877. for (var i = 0; i < this.soundTracks.length; i++) {
  13878. this.soundTracks[i].switchPanningModelToHRTF();
  13879. }
  13880. };
  13881. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13882. this.mainSoundTrack.switchPanningModelToEqualPower();
  13883. for (var i = 0; i < this.soundTracks.length; i++) {
  13884. this.soundTracks[i].switchPanningModelToEqualPower();
  13885. }
  13886. };
  13887. Scene.prototype.enableDepthRenderer = function () {
  13888. if (this._depthRenderer) {
  13889. return this._depthRenderer;
  13890. }
  13891. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13892. return this._depthRenderer;
  13893. };
  13894. Scene.prototype.disableDepthRenderer = function () {
  13895. if (!this._depthRenderer) {
  13896. return;
  13897. }
  13898. this._depthRenderer.dispose();
  13899. this._depthRenderer = null;
  13900. };
  13901. Scene.prototype.freezeMaterials = function () {
  13902. for (var i = 0; i < this.materials.length; i++) {
  13903. this.materials[i].freeze();
  13904. }
  13905. };
  13906. Scene.prototype.unfreezeMaterials = function () {
  13907. for (var i = 0; i < this.materials.length; i++) {
  13908. this.materials[i].unfreeze();
  13909. }
  13910. };
  13911. Scene.prototype.dispose = function () {
  13912. this.beforeRender = null;
  13913. this.afterRender = null;
  13914. this.skeletons = [];
  13915. this._boundingBoxRenderer.dispose();
  13916. if (this._depthRenderer) {
  13917. this._depthRenderer.dispose();
  13918. }
  13919. // Debug layer
  13920. this.debugLayer.hide();
  13921. // Events
  13922. if (this.onDispose) {
  13923. this.onDispose();
  13924. }
  13925. this._onBeforeRenderCallbacks = [];
  13926. this._onAfterRenderCallbacks = [];
  13927. this.detachControl();
  13928. // Release sounds & sounds tracks
  13929. if (BABYLON.AudioEngine) {
  13930. this.disposeSounds();
  13931. }
  13932. // Detach cameras
  13933. var canvas = this._engine.getRenderingCanvas();
  13934. var index;
  13935. for (index = 0; index < this.cameras.length; index++) {
  13936. this.cameras[index].detachControl(canvas);
  13937. }
  13938. // Release lights
  13939. while (this.lights.length) {
  13940. this.lights[0].dispose();
  13941. }
  13942. // Release meshes
  13943. while (this.meshes.length) {
  13944. this.meshes[0].dispose(true);
  13945. }
  13946. // Release cameras
  13947. while (this.cameras.length) {
  13948. this.cameras[0].dispose();
  13949. }
  13950. // Release materials
  13951. while (this.materials.length) {
  13952. this.materials[0].dispose();
  13953. }
  13954. // Release particles
  13955. while (this.particleSystems.length) {
  13956. this.particleSystems[0].dispose();
  13957. }
  13958. // Release sprites
  13959. while (this.spriteManagers.length) {
  13960. this.spriteManagers[0].dispose();
  13961. }
  13962. // Release layers
  13963. while (this.layers.length) {
  13964. this.layers[0].dispose();
  13965. }
  13966. // Release textures
  13967. while (this.textures.length) {
  13968. this.textures[0].dispose();
  13969. }
  13970. // Post-processes
  13971. this.postProcessManager.dispose();
  13972. // Physics
  13973. if (this._physicsEngine) {
  13974. this.disablePhysicsEngine();
  13975. }
  13976. // Remove from engine
  13977. index = this._engine.scenes.indexOf(this);
  13978. if (index > -1) {
  13979. this._engine.scenes.splice(index, 1);
  13980. }
  13981. this._engine.wipeCaches();
  13982. };
  13983. // Release sounds & sounds tracks
  13984. Scene.prototype.disposeSounds = function () {
  13985. this.mainSoundTrack.dispose();
  13986. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13987. this.soundTracks[scIndex].dispose();
  13988. }
  13989. };
  13990. // Octrees
  13991. Scene.prototype.getWorldExtends = function () {
  13992. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13993. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13994. for (var index = 0; index < this.meshes.length; index++) {
  13995. var mesh = this.meshes[index];
  13996. mesh.computeWorldMatrix(true);
  13997. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13998. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13999. BABYLON.Tools.CheckExtends(minBox, min, max);
  14000. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14001. }
  14002. return {
  14003. min: min,
  14004. max: max
  14005. };
  14006. };
  14007. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14008. if (maxCapacity === void 0) { maxCapacity = 64; }
  14009. if (maxDepth === void 0) { maxDepth = 2; }
  14010. if (!this._selectionOctree) {
  14011. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14012. }
  14013. var worldExtends = this.getWorldExtends();
  14014. // Update octree
  14015. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14016. return this._selectionOctree;
  14017. };
  14018. // Picking
  14019. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14020. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14021. var engine = this._engine;
  14022. if (!camera) {
  14023. if (!this.activeCamera)
  14024. throw new Error("Active camera not set");
  14025. camera = this.activeCamera;
  14026. }
  14027. var cameraViewport = camera.viewport;
  14028. var viewport = cameraViewport.toGlobal(engine);
  14029. // Moving coordinates to local viewport world
  14030. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14031. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14032. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14033. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14034. };
  14035. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14036. var engine = this._engine;
  14037. if (!camera) {
  14038. if (!this.activeCamera)
  14039. throw new Error("Active camera not set");
  14040. camera = this.activeCamera;
  14041. }
  14042. var cameraViewport = camera.viewport;
  14043. var viewport = cameraViewport.toGlobal(engine);
  14044. var identity = BABYLON.Matrix.Identity();
  14045. // Moving coordinates to local viewport world
  14046. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14047. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14048. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14049. };
  14050. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14051. var pickingInfo = null;
  14052. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14053. var mesh = this.meshes[meshIndex];
  14054. if (predicate) {
  14055. if (!predicate(mesh)) {
  14056. continue;
  14057. }
  14058. }
  14059. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14060. continue;
  14061. }
  14062. var world = mesh.getWorldMatrix();
  14063. var ray = rayFunction(world);
  14064. var result = mesh.intersects(ray, fastCheck);
  14065. if (!result || !result.hit)
  14066. continue;
  14067. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14068. continue;
  14069. pickingInfo = result;
  14070. if (fastCheck) {
  14071. break;
  14072. }
  14073. }
  14074. return pickingInfo || new BABYLON.PickingInfo();
  14075. };
  14076. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14077. var pickingInfo = null;
  14078. camera = camera || this.activeCamera;
  14079. if (this.spriteManagers.length > 0) {
  14080. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14081. var spriteManager = this.spriteManagers[spriteIndex];
  14082. if (!spriteManager.isPickable) {
  14083. continue;
  14084. }
  14085. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14086. if (!result || !result.hit)
  14087. continue;
  14088. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14089. continue;
  14090. pickingInfo = result;
  14091. if (fastCheck) {
  14092. break;
  14093. }
  14094. }
  14095. }
  14096. return pickingInfo || new BABYLON.PickingInfo();
  14097. };
  14098. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14099. var _this = this;
  14100. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14101. /// <param name="x">X position on screen</param>
  14102. /// <param name="y">Y position on screen</param>
  14103. /// <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>
  14104. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14105. /// <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>
  14106. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14107. };
  14108. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14109. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14110. /// <param name="x">X position on screen</param>
  14111. /// <param name="y">Y position on screen</param>
  14112. /// <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>
  14113. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14114. /// <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>
  14115. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14116. };
  14117. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14118. var _this = this;
  14119. return this._internalPick(function (world) {
  14120. if (!_this._pickWithRayInverseMatrix) {
  14121. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14122. }
  14123. world.invertToRef(_this._pickWithRayInverseMatrix);
  14124. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14125. }, predicate, fastCheck);
  14126. };
  14127. Scene.prototype.setPointerOverMesh = function (mesh) {
  14128. if (this._pointerOverMesh === mesh) {
  14129. return;
  14130. }
  14131. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14132. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14133. }
  14134. this._pointerOverMesh = mesh;
  14135. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14136. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14137. }
  14138. };
  14139. Scene.prototype.getPointerOverMesh = function () {
  14140. return this._pointerOverMesh;
  14141. };
  14142. Scene.prototype.setPointerOverSprite = function (sprite) {
  14143. if (this._pointerOverSprite === sprite) {
  14144. return;
  14145. }
  14146. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14147. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14148. }
  14149. this._pointerOverSprite = sprite;
  14150. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14151. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14152. }
  14153. };
  14154. Scene.prototype.getPointerOverSprite = function () {
  14155. return this._pointerOverSprite;
  14156. };
  14157. // Physics
  14158. Scene.prototype.getPhysicsEngine = function () {
  14159. return this._physicsEngine;
  14160. };
  14161. /**
  14162. * Enables physics to the current scene
  14163. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14164. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14165. * @return {boolean} was the physics engine initialized
  14166. */
  14167. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14168. if (this._physicsEngine) {
  14169. return true;
  14170. }
  14171. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14172. if (!this._physicsEngine.isSupported()) {
  14173. this._physicsEngine = null;
  14174. return false;
  14175. }
  14176. this._physicsEngine._initialize(gravity);
  14177. return true;
  14178. };
  14179. Scene.prototype.disablePhysicsEngine = function () {
  14180. if (!this._physicsEngine) {
  14181. return;
  14182. }
  14183. this._physicsEngine.dispose();
  14184. this._physicsEngine = undefined;
  14185. };
  14186. Scene.prototype.isPhysicsEnabled = function () {
  14187. return this._physicsEngine !== undefined;
  14188. };
  14189. /**
  14190. * Sets the gravity of the physics engine (and NOT of the scene)
  14191. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14192. */
  14193. Scene.prototype.setGravity = function (gravity) {
  14194. if (!this._physicsEngine) {
  14195. return;
  14196. }
  14197. this._physicsEngine._setGravity(gravity);
  14198. };
  14199. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14200. if (parts.parts) {
  14201. options = parts;
  14202. parts = parts.parts;
  14203. }
  14204. if (!this._physicsEngine) {
  14205. return null;
  14206. }
  14207. for (var index = 0; index < parts.length; index++) {
  14208. var mesh = parts[index].mesh;
  14209. mesh._physicImpostor = parts[index].impostor;
  14210. mesh._physicsMass = options.mass / parts.length;
  14211. mesh._physicsFriction = options.friction;
  14212. mesh._physicRestitution = options.restitution;
  14213. }
  14214. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14215. };
  14216. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14217. for (var index = 0; index < compound.parts.length; index++) {
  14218. var mesh = compound.parts[index].mesh;
  14219. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14220. this._physicsEngine._unregisterMesh(mesh);
  14221. }
  14222. };
  14223. // Misc.
  14224. Scene.prototype.createDefaultCameraOrLight = function () {
  14225. // Light
  14226. if (this.lights.length === 0) {
  14227. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14228. }
  14229. // Camera
  14230. if (!this.activeCamera) {
  14231. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14232. // Compute position
  14233. var worldExtends = this.getWorldExtends();
  14234. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14235. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14236. camera.setTarget(worldCenter);
  14237. this.activeCamera = camera;
  14238. }
  14239. };
  14240. // Tags
  14241. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14242. if (tagsQuery === undefined) {
  14243. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14244. return list;
  14245. }
  14246. var listByTags = [];
  14247. forEach = forEach || (function (item) { return; });
  14248. for (var i in list) {
  14249. var item = list[i];
  14250. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14251. listByTags.push(item);
  14252. forEach(item);
  14253. }
  14254. }
  14255. return listByTags;
  14256. };
  14257. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14258. return this._getByTags(this.meshes, tagsQuery, forEach);
  14259. };
  14260. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14261. return this._getByTags(this.cameras, tagsQuery, forEach);
  14262. };
  14263. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14264. return this._getByTags(this.lights, tagsQuery, forEach);
  14265. };
  14266. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14267. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14268. };
  14269. // Statics
  14270. Scene._FOGMODE_NONE = 0;
  14271. Scene._FOGMODE_EXP = 1;
  14272. Scene._FOGMODE_EXP2 = 2;
  14273. Scene._FOGMODE_LINEAR = 3;
  14274. Scene.MinDeltaTime = 1.0;
  14275. Scene.MaxDeltaTime = 1000.0;
  14276. return Scene;
  14277. })();
  14278. BABYLON.Scene = Scene;
  14279. })(BABYLON || (BABYLON = {}));
  14280. var BABYLON;
  14281. (function (BABYLON) {
  14282. var VertexBuffer = (function () {
  14283. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14284. if (engine instanceof BABYLON.Mesh) {
  14285. this._engine = engine.getScene().getEngine();
  14286. }
  14287. else {
  14288. this._engine = engine;
  14289. }
  14290. this._updatable = updatable;
  14291. this._data = data;
  14292. if (!postponeInternalCreation) {
  14293. this.create();
  14294. }
  14295. this._kind = kind;
  14296. if (stride) {
  14297. this._strideSize = stride;
  14298. return;
  14299. }
  14300. // Deduce stride from kind
  14301. switch (kind) {
  14302. case VertexBuffer.PositionKind:
  14303. this._strideSize = 3;
  14304. break;
  14305. case VertexBuffer.NormalKind:
  14306. this._strideSize = 3;
  14307. break;
  14308. case VertexBuffer.UVKind:
  14309. case VertexBuffer.UV2Kind:
  14310. case VertexBuffer.UV3Kind:
  14311. case VertexBuffer.UV4Kind:
  14312. case VertexBuffer.UV5Kind:
  14313. case VertexBuffer.UV6Kind:
  14314. this._strideSize = 2;
  14315. break;
  14316. case VertexBuffer.ColorKind:
  14317. this._strideSize = 4;
  14318. break;
  14319. case VertexBuffer.MatricesIndicesKind:
  14320. case VertexBuffer.MatricesIndicesExtraKind:
  14321. this._strideSize = 4;
  14322. break;
  14323. case VertexBuffer.MatricesWeightsKind:
  14324. case VertexBuffer.MatricesWeightsExtraKind:
  14325. this._strideSize = 4;
  14326. break;
  14327. }
  14328. }
  14329. // Properties
  14330. VertexBuffer.prototype.isUpdatable = function () {
  14331. return this._updatable;
  14332. };
  14333. VertexBuffer.prototype.getData = function () {
  14334. return this._data;
  14335. };
  14336. VertexBuffer.prototype.getBuffer = function () {
  14337. return this._buffer;
  14338. };
  14339. VertexBuffer.prototype.getStrideSize = function () {
  14340. return this._strideSize;
  14341. };
  14342. // Methods
  14343. VertexBuffer.prototype.create = function (data) {
  14344. if (!data && this._buffer) {
  14345. return; // nothing to do
  14346. }
  14347. data = data || this._data;
  14348. if (!this._buffer) {
  14349. if (this._updatable) {
  14350. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14351. }
  14352. else {
  14353. this._buffer = this._engine.createVertexBuffer(data);
  14354. }
  14355. }
  14356. if (this._updatable) {
  14357. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14358. this._data = data;
  14359. }
  14360. };
  14361. VertexBuffer.prototype.update = function (data) {
  14362. this.create(data);
  14363. };
  14364. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14365. if (!this._buffer) {
  14366. return;
  14367. }
  14368. if (this._updatable) {
  14369. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14370. this._data = null;
  14371. }
  14372. };
  14373. VertexBuffer.prototype.dispose = function () {
  14374. if (!this._buffer) {
  14375. return;
  14376. }
  14377. if (this._engine._releaseBuffer(this._buffer)) {
  14378. this._buffer = null;
  14379. }
  14380. };
  14381. Object.defineProperty(VertexBuffer, "PositionKind", {
  14382. get: function () {
  14383. return VertexBuffer._PositionKind;
  14384. },
  14385. enumerable: true,
  14386. configurable: true
  14387. });
  14388. Object.defineProperty(VertexBuffer, "NormalKind", {
  14389. get: function () {
  14390. return VertexBuffer._NormalKind;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(VertexBuffer, "UVKind", {
  14396. get: function () {
  14397. return VertexBuffer._UVKind;
  14398. },
  14399. enumerable: true,
  14400. configurable: true
  14401. });
  14402. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14403. get: function () {
  14404. return VertexBuffer._UV2Kind;
  14405. },
  14406. enumerable: true,
  14407. configurable: true
  14408. });
  14409. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14410. get: function () {
  14411. return VertexBuffer._UV3Kind;
  14412. },
  14413. enumerable: true,
  14414. configurable: true
  14415. });
  14416. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14417. get: function () {
  14418. return VertexBuffer._UV4Kind;
  14419. },
  14420. enumerable: true,
  14421. configurable: true
  14422. });
  14423. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14424. get: function () {
  14425. return VertexBuffer._UV5Kind;
  14426. },
  14427. enumerable: true,
  14428. configurable: true
  14429. });
  14430. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14431. get: function () {
  14432. return VertexBuffer._UV6Kind;
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(VertexBuffer, "ColorKind", {
  14438. get: function () {
  14439. return VertexBuffer._ColorKind;
  14440. },
  14441. enumerable: true,
  14442. configurable: true
  14443. });
  14444. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14445. get: function () {
  14446. return VertexBuffer._MatricesIndicesKind;
  14447. },
  14448. enumerable: true,
  14449. configurable: true
  14450. });
  14451. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14452. get: function () {
  14453. return VertexBuffer._MatricesWeightsKind;
  14454. },
  14455. enumerable: true,
  14456. configurable: true
  14457. });
  14458. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14459. get: function () {
  14460. return VertexBuffer._MatricesIndicesExtraKind;
  14461. },
  14462. enumerable: true,
  14463. configurable: true
  14464. });
  14465. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14466. get: function () {
  14467. return VertexBuffer._MatricesWeightsExtraKind;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. // Enums
  14473. VertexBuffer._PositionKind = "position";
  14474. VertexBuffer._NormalKind = "normal";
  14475. VertexBuffer._UVKind = "uv";
  14476. VertexBuffer._UV2Kind = "uv2";
  14477. VertexBuffer._UV3Kind = "uv3";
  14478. VertexBuffer._UV4Kind = "uv4";
  14479. VertexBuffer._UV5Kind = "uv5";
  14480. VertexBuffer._UV6Kind = "uv6";
  14481. VertexBuffer._ColorKind = "color";
  14482. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14483. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14484. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14485. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14486. return VertexBuffer;
  14487. })();
  14488. BABYLON.VertexBuffer = VertexBuffer;
  14489. })(BABYLON || (BABYLON = {}));
  14490. var BABYLON;
  14491. (function (BABYLON) {
  14492. /**
  14493. * Creates an instance based on a source mesh.
  14494. */
  14495. var InstancedMesh = (function (_super) {
  14496. __extends(InstancedMesh, _super);
  14497. function InstancedMesh(name, source) {
  14498. _super.call(this, name, source.getScene());
  14499. source.instances.push(this);
  14500. this._sourceMesh = source;
  14501. this.position.copyFrom(source.position);
  14502. this.rotation.copyFrom(source.rotation);
  14503. this.scaling.copyFrom(source.scaling);
  14504. if (source.rotationQuaternion) {
  14505. this.rotationQuaternion = source.rotationQuaternion.clone();
  14506. }
  14507. this.infiniteDistance = source.infiniteDistance;
  14508. this.setPivotMatrix(source.getPivotMatrix());
  14509. this.refreshBoundingInfo();
  14510. this._syncSubMeshes();
  14511. }
  14512. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14513. // Methods
  14514. get: function () {
  14515. return this._sourceMesh.receiveShadows;
  14516. },
  14517. enumerable: true,
  14518. configurable: true
  14519. });
  14520. Object.defineProperty(InstancedMesh.prototype, "material", {
  14521. get: function () {
  14522. return this._sourceMesh.material;
  14523. },
  14524. enumerable: true,
  14525. configurable: true
  14526. });
  14527. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14528. get: function () {
  14529. return this._sourceMesh.visibility;
  14530. },
  14531. enumerable: true,
  14532. configurable: true
  14533. });
  14534. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14535. get: function () {
  14536. return this._sourceMesh.skeleton;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14542. get: function () {
  14543. return this._sourceMesh.renderingGroupId;
  14544. },
  14545. enumerable: true,
  14546. configurable: true
  14547. });
  14548. InstancedMesh.prototype.getTotalVertices = function () {
  14549. return this._sourceMesh.getTotalVertices();
  14550. };
  14551. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14552. get: function () {
  14553. return this._sourceMesh;
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14559. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14560. };
  14561. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14562. return this._sourceMesh.isVerticesDataPresent(kind);
  14563. };
  14564. InstancedMesh.prototype.getIndices = function () {
  14565. return this._sourceMesh.getIndices();
  14566. };
  14567. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14568. get: function () {
  14569. return this._sourceMesh._positions;
  14570. },
  14571. enumerable: true,
  14572. configurable: true
  14573. });
  14574. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14575. var meshBB = this._sourceMesh.getBoundingInfo();
  14576. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14577. this._updateBoundingInfo();
  14578. };
  14579. InstancedMesh.prototype._preActivate = function () {
  14580. if (this._currentLOD) {
  14581. this._currentLOD._preActivate();
  14582. }
  14583. };
  14584. InstancedMesh.prototype._activate = function (renderId) {
  14585. if (this._currentLOD) {
  14586. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14587. }
  14588. };
  14589. InstancedMesh.prototype.getLOD = function (camera) {
  14590. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14591. if (this._currentLOD === this.sourceMesh) {
  14592. return this;
  14593. }
  14594. return this._currentLOD;
  14595. };
  14596. InstancedMesh.prototype._syncSubMeshes = function () {
  14597. this.releaseSubMeshes();
  14598. if (this._sourceMesh.subMeshes) {
  14599. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14600. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14601. }
  14602. }
  14603. };
  14604. InstancedMesh.prototype._generatePointsArray = function () {
  14605. return this._sourceMesh._generatePointsArray();
  14606. };
  14607. // Clone
  14608. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14609. var result = this._sourceMesh.createInstance(name);
  14610. // Deep copy
  14611. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14612. // Bounding info
  14613. this.refreshBoundingInfo();
  14614. // Parent
  14615. if (newParent) {
  14616. result.parent = newParent;
  14617. }
  14618. if (!doNotCloneChildren) {
  14619. // Children
  14620. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14621. var mesh = this.getScene().meshes[index];
  14622. if (mesh.parent === this) {
  14623. mesh.clone(mesh.name, result);
  14624. }
  14625. }
  14626. }
  14627. result.computeWorldMatrix(true);
  14628. return result;
  14629. };
  14630. // Dispoe
  14631. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14632. // Remove from mesh
  14633. var index = this._sourceMesh.instances.indexOf(this);
  14634. this._sourceMesh.instances.splice(index, 1);
  14635. _super.prototype.dispose.call(this, doNotRecurse);
  14636. };
  14637. return InstancedMesh;
  14638. })(BABYLON.AbstractMesh);
  14639. BABYLON.InstancedMesh = InstancedMesh;
  14640. })(BABYLON || (BABYLON = {}));
  14641. var BABYLON;
  14642. (function (BABYLON) {
  14643. var _InstancesBatch = (function () {
  14644. function _InstancesBatch() {
  14645. this.mustReturn = false;
  14646. this.visibleInstances = new Array();
  14647. this.renderSelf = new Array();
  14648. }
  14649. return _InstancesBatch;
  14650. })();
  14651. BABYLON._InstancesBatch = _InstancesBatch;
  14652. var Mesh = (function (_super) {
  14653. __extends(Mesh, _super);
  14654. /**
  14655. * @constructor
  14656. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14657. * @param {Scene} scene - The scene to add this mesh to.
  14658. * @param {Node} parent - The parent of this mesh, if it has one
  14659. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14660. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14661. * When false, achieved by calling a clone(), also passing False.
  14662. * This will make creation of children, recursive.
  14663. */
  14664. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14665. if (parent === void 0) { parent = null; }
  14666. _super.call(this, name, scene);
  14667. // Members
  14668. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14669. this.instances = new Array();
  14670. this._LODLevels = new Array();
  14671. this._onBeforeRenderCallbacks = new Array();
  14672. this._onAfterRenderCallbacks = new Array();
  14673. this._visibleInstances = {};
  14674. this._renderIdForInstances = new Array();
  14675. this._batchCache = new _InstancesBatch();
  14676. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14677. this._sideOrientation = Mesh._DEFAULTSIDE;
  14678. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14679. if (source) {
  14680. // Geometry
  14681. if (source._geometry) {
  14682. source._geometry.applyToMesh(this);
  14683. }
  14684. // Deep copy
  14685. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14686. this.id = name + "." + source.id;
  14687. // Material
  14688. this.material = source.material;
  14689. var index;
  14690. if (!doNotCloneChildren) {
  14691. // Children
  14692. for (index = 0; index < scene.meshes.length; index++) {
  14693. var mesh = scene.meshes[index];
  14694. if (mesh.parent === source) {
  14695. // doNotCloneChildren is always going to be False
  14696. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14697. }
  14698. }
  14699. }
  14700. // Particles
  14701. for (index = 0; index < scene.particleSystems.length; index++) {
  14702. var system = scene.particleSystems[index];
  14703. if (system.emitter === source) {
  14704. system.clone(system.name, this);
  14705. }
  14706. }
  14707. this.computeWorldMatrix(true);
  14708. }
  14709. // Parent
  14710. if (parent !== null) {
  14711. this.parent = parent;
  14712. }
  14713. }
  14714. Object.defineProperty(Mesh, "FRONTSIDE", {
  14715. get: function () {
  14716. return Mesh._FRONTSIDE;
  14717. },
  14718. enumerable: true,
  14719. configurable: true
  14720. });
  14721. Object.defineProperty(Mesh, "BACKSIDE", {
  14722. get: function () {
  14723. return Mesh._BACKSIDE;
  14724. },
  14725. enumerable: true,
  14726. configurable: true
  14727. });
  14728. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14729. get: function () {
  14730. return Mesh._DOUBLESIDE;
  14731. },
  14732. enumerable: true,
  14733. configurable: true
  14734. });
  14735. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14736. get: function () {
  14737. return Mesh._DEFAULTSIDE;
  14738. },
  14739. enumerable: true,
  14740. configurable: true
  14741. });
  14742. Object.defineProperty(Mesh, "NO_CAP", {
  14743. get: function () {
  14744. return Mesh._NO_CAP;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(Mesh, "CAP_START", {
  14750. get: function () {
  14751. return Mesh._CAP_START;
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(Mesh, "CAP_END", {
  14757. get: function () {
  14758. return Mesh._CAP_END;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Mesh, "CAP_ALL", {
  14764. get: function () {
  14765. return Mesh._CAP_ALL;
  14766. },
  14767. enumerable: true,
  14768. configurable: true
  14769. });
  14770. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14771. // Methods
  14772. get: function () {
  14773. return this._LODLevels.length > 0;
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. Mesh.prototype._sortLODLevels = function () {
  14779. this._LODLevels.sort(function (a, b) {
  14780. if (a.distance < b.distance) {
  14781. return 1;
  14782. }
  14783. if (a.distance > b.distance) {
  14784. return -1;
  14785. }
  14786. return 0;
  14787. });
  14788. };
  14789. /**
  14790. * Add a mesh as LOD level triggered at the given distance.
  14791. * @param {number} distance - the distance from the center of the object to show this level
  14792. * @param {Mesh} mesh - the mesh to be added as LOD level
  14793. * @return {Mesh} this mesh (for chaining)
  14794. */
  14795. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14796. if (mesh && mesh._masterMesh) {
  14797. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14798. return this;
  14799. }
  14800. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14801. this._LODLevels.push(level);
  14802. if (mesh) {
  14803. mesh._masterMesh = this;
  14804. }
  14805. this._sortLODLevels();
  14806. return this;
  14807. };
  14808. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14809. for (var index = 0; index < this._LODLevels.length; index++) {
  14810. var level = this._LODLevels[index];
  14811. if (level.distance === distance) {
  14812. return level.mesh;
  14813. }
  14814. }
  14815. return null;
  14816. };
  14817. /**
  14818. * Remove a mesh from the LOD array
  14819. * @param {Mesh} mesh - the mesh to be removed.
  14820. * @return {Mesh} this mesh (for chaining)
  14821. */
  14822. Mesh.prototype.removeLODLevel = function (mesh) {
  14823. for (var index = 0; index < this._LODLevels.length; index++) {
  14824. if (this._LODLevels[index].mesh === mesh) {
  14825. this._LODLevels.splice(index, 1);
  14826. if (mesh) {
  14827. mesh._masterMesh = null;
  14828. }
  14829. }
  14830. }
  14831. this._sortLODLevels();
  14832. return this;
  14833. };
  14834. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14835. if (!this._LODLevels || this._LODLevels.length === 0) {
  14836. return this;
  14837. }
  14838. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14839. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14840. if (this.onLODLevelSelection) {
  14841. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14842. }
  14843. return this;
  14844. }
  14845. for (var index = 0; index < this._LODLevels.length; index++) {
  14846. var level = this._LODLevels[index];
  14847. if (level.distance < distanceToCamera) {
  14848. if (level.mesh) {
  14849. level.mesh._preActivate();
  14850. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14851. }
  14852. if (this.onLODLevelSelection) {
  14853. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14854. }
  14855. return level.mesh;
  14856. }
  14857. }
  14858. if (this.onLODLevelSelection) {
  14859. this.onLODLevelSelection(distanceToCamera, this, this);
  14860. }
  14861. return this;
  14862. };
  14863. Object.defineProperty(Mesh.prototype, "geometry", {
  14864. get: function () {
  14865. return this._geometry;
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Mesh.prototype.getTotalVertices = function () {
  14871. if (!this._geometry) {
  14872. return 0;
  14873. }
  14874. return this._geometry.getTotalVertices();
  14875. };
  14876. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14877. if (!this._geometry) {
  14878. return null;
  14879. }
  14880. return this._geometry.getVerticesData(kind, copyWhenShared);
  14881. };
  14882. Mesh.prototype.getVertexBuffer = function (kind) {
  14883. if (!this._geometry) {
  14884. return undefined;
  14885. }
  14886. return this._geometry.getVertexBuffer(kind);
  14887. };
  14888. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14889. if (!this._geometry) {
  14890. if (this._delayInfo) {
  14891. return this._delayInfo.indexOf(kind) !== -1;
  14892. }
  14893. return false;
  14894. }
  14895. return this._geometry.isVerticesDataPresent(kind);
  14896. };
  14897. Mesh.prototype.getVerticesDataKinds = function () {
  14898. if (!this._geometry) {
  14899. var result = [];
  14900. if (this._delayInfo) {
  14901. for (var kind in this._delayInfo) {
  14902. result.push(kind);
  14903. }
  14904. }
  14905. return result;
  14906. }
  14907. return this._geometry.getVerticesDataKinds();
  14908. };
  14909. Mesh.prototype.getTotalIndices = function () {
  14910. if (!this._geometry) {
  14911. return 0;
  14912. }
  14913. return this._geometry.getTotalIndices();
  14914. };
  14915. Mesh.prototype.getIndices = function (copyWhenShared) {
  14916. if (!this._geometry) {
  14917. return [];
  14918. }
  14919. return this._geometry.getIndices(copyWhenShared);
  14920. };
  14921. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14922. get: function () {
  14923. return this._masterMesh !== null && this._masterMesh !== undefined;
  14924. },
  14925. enumerable: true,
  14926. configurable: true
  14927. });
  14928. Mesh.prototype.isReady = function () {
  14929. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14930. return false;
  14931. }
  14932. return _super.prototype.isReady.call(this);
  14933. };
  14934. Mesh.prototype.isDisposed = function () {
  14935. return this._isDisposed;
  14936. };
  14937. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14938. get: function () {
  14939. return this._sideOrientation;
  14940. },
  14941. set: function (sideO) {
  14942. this._sideOrientation = sideO;
  14943. },
  14944. enumerable: true,
  14945. configurable: true
  14946. });
  14947. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14948. get: function () {
  14949. return this._areNormalsFrozen;
  14950. },
  14951. enumerable: true,
  14952. configurable: true
  14953. });
  14954. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14955. Mesh.prototype.freezeNormals = function () {
  14956. this._areNormalsFrozen = true;
  14957. };
  14958. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14959. Mesh.prototype.unfreezeNormals = function () {
  14960. this._areNormalsFrozen = false;
  14961. };
  14962. // Methods
  14963. Mesh.prototype._preActivate = function () {
  14964. var sceneRenderId = this.getScene().getRenderId();
  14965. if (this._preActivateId === sceneRenderId) {
  14966. return;
  14967. }
  14968. this._preActivateId = sceneRenderId;
  14969. this._visibleInstances = null;
  14970. };
  14971. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14972. if (!this._visibleInstances) {
  14973. this._visibleInstances = {};
  14974. this._visibleInstances.defaultRenderId = renderId;
  14975. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14976. }
  14977. if (!this._visibleInstances[renderId]) {
  14978. this._visibleInstances[renderId] = new Array();
  14979. }
  14980. this._visibleInstances[renderId].push(instance);
  14981. };
  14982. Mesh.prototype.refreshBoundingInfo = function () {
  14983. if (this._boundingInfo.isLocked) {
  14984. return;
  14985. }
  14986. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14987. if (data) {
  14988. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14989. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14990. }
  14991. if (this.subMeshes) {
  14992. for (var index = 0; index < this.subMeshes.length; index++) {
  14993. this.subMeshes[index].refreshBoundingInfo();
  14994. }
  14995. }
  14996. this._updateBoundingInfo();
  14997. };
  14998. Mesh.prototype._createGlobalSubMesh = function () {
  14999. var totalVertices = this.getTotalVertices();
  15000. if (!totalVertices || !this.getIndices()) {
  15001. return null;
  15002. }
  15003. this.releaseSubMeshes();
  15004. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15005. };
  15006. Mesh.prototype.subdivide = function (count) {
  15007. if (count < 1) {
  15008. return;
  15009. }
  15010. var totalIndices = this.getTotalIndices();
  15011. var subdivisionSize = (totalIndices / count) | 0;
  15012. var offset = 0;
  15013. // Ensure that subdivisionSize is a multiple of 3
  15014. while (subdivisionSize % 3 !== 0) {
  15015. subdivisionSize++;
  15016. }
  15017. this.releaseSubMeshes();
  15018. for (var index = 0; index < count; index++) {
  15019. if (offset >= totalIndices) {
  15020. break;
  15021. }
  15022. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15023. offset += subdivisionSize;
  15024. }
  15025. this.synchronizeInstances();
  15026. };
  15027. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15028. if (!this._geometry) {
  15029. var vertexData = new BABYLON.VertexData();
  15030. vertexData.set(data, kind);
  15031. var scene = this.getScene();
  15032. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15033. }
  15034. else {
  15035. this._geometry.setVerticesData(kind, data, updatable, stride);
  15036. }
  15037. };
  15038. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15039. if (!this._geometry) {
  15040. return;
  15041. }
  15042. if (!makeItUnique) {
  15043. this._geometry.updateVerticesData(kind, data, updateExtends);
  15044. }
  15045. else {
  15046. this.makeGeometryUnique();
  15047. this.updateVerticesData(kind, data, updateExtends, false);
  15048. }
  15049. };
  15050. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15051. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15052. if (!this._geometry) {
  15053. return;
  15054. }
  15055. if (!makeItUnique) {
  15056. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15057. }
  15058. else {
  15059. this.makeGeometryUnique();
  15060. this.updateVerticesDataDirectly(kind, data, offset, false);
  15061. }
  15062. };
  15063. // Mesh positions update function :
  15064. // updates the mesh positions according to the positionFunction returned values.
  15065. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15066. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15067. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15068. if (computeNormals === void 0) { computeNormals = true; }
  15069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15070. positionFunction(positions);
  15071. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15072. if (computeNormals) {
  15073. var indices = this.getIndices();
  15074. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15075. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15076. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15077. }
  15078. };
  15079. Mesh.prototype.makeGeometryUnique = function () {
  15080. if (!this._geometry) {
  15081. return;
  15082. }
  15083. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15084. geometry.applyToMesh(this);
  15085. };
  15086. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15087. if (!this._geometry) {
  15088. var vertexData = new BABYLON.VertexData();
  15089. vertexData.indices = indices;
  15090. var scene = this.getScene();
  15091. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15092. }
  15093. else {
  15094. this._geometry.setIndices(indices, totalVertices);
  15095. }
  15096. };
  15097. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15098. var engine = this.getScene().getEngine();
  15099. // Wireframe
  15100. var indexToBind;
  15101. if (this._unIndexed) {
  15102. indexToBind = null;
  15103. }
  15104. else {
  15105. switch (fillMode) {
  15106. case BABYLON.Material.PointFillMode:
  15107. indexToBind = null;
  15108. break;
  15109. case BABYLON.Material.WireFrameFillMode:
  15110. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15111. break;
  15112. default:
  15113. case BABYLON.Material.TriangleFillMode:
  15114. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15115. break;
  15116. }
  15117. }
  15118. // VBOs
  15119. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15120. };
  15121. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15122. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15123. return;
  15124. }
  15125. if (this.onBeforeDraw) {
  15126. this.onBeforeDraw();
  15127. }
  15128. var engine = this.getScene().getEngine();
  15129. // Draw order
  15130. switch (fillMode) {
  15131. case BABYLON.Material.PointFillMode:
  15132. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15133. break;
  15134. case BABYLON.Material.WireFrameFillMode:
  15135. if (this._unIndexed) {
  15136. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15137. }
  15138. else {
  15139. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15140. }
  15141. break;
  15142. default:
  15143. if (this._unIndexed) {
  15144. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15145. }
  15146. else {
  15147. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15148. }
  15149. }
  15150. };
  15151. Mesh.prototype.registerBeforeRender = function (func) {
  15152. this._onBeforeRenderCallbacks.push(func);
  15153. };
  15154. Mesh.prototype.unregisterBeforeRender = function (func) {
  15155. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15156. if (index > -1) {
  15157. this._onBeforeRenderCallbacks.splice(index, 1);
  15158. }
  15159. };
  15160. Mesh.prototype.registerAfterRender = function (func) {
  15161. this._onAfterRenderCallbacks.push(func);
  15162. };
  15163. Mesh.prototype.unregisterAfterRender = function (func) {
  15164. var index = this._onAfterRenderCallbacks.indexOf(func);
  15165. if (index > -1) {
  15166. this._onAfterRenderCallbacks.splice(index, 1);
  15167. }
  15168. };
  15169. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15170. var scene = this.getScene();
  15171. this._batchCache.mustReturn = false;
  15172. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15173. this._batchCache.visibleInstances[subMeshId] = null;
  15174. if (this._visibleInstances) {
  15175. var currentRenderId = scene.getRenderId();
  15176. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15177. var selfRenderId = this._renderId;
  15178. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15179. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15180. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15181. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15182. }
  15183. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15184. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15185. this._batchCache.mustReturn = true;
  15186. return this._batchCache;
  15187. }
  15188. if (currentRenderId !== selfRenderId) {
  15189. this._batchCache.renderSelf[subMeshId] = false;
  15190. }
  15191. }
  15192. this._renderIdForInstances[subMeshId] = currentRenderId;
  15193. }
  15194. return this._batchCache;
  15195. };
  15196. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15197. var visibleInstances = batch.visibleInstances[subMesh._id];
  15198. var matricesCount = visibleInstances.length + 1;
  15199. var bufferSize = matricesCount * 16 * 4;
  15200. while (this._instancesBufferSize < bufferSize) {
  15201. this._instancesBufferSize *= 2;
  15202. }
  15203. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15204. if (this._worldMatricesInstancesBuffer) {
  15205. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15206. }
  15207. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15208. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15209. }
  15210. var offset = 0;
  15211. var instancesCount = 0;
  15212. var world = this.getWorldMatrix();
  15213. if (batch.renderSelf[subMesh._id]) {
  15214. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15215. offset += 16;
  15216. instancesCount++;
  15217. }
  15218. if (visibleInstances) {
  15219. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15220. var instance = visibleInstances[instanceIndex];
  15221. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15222. offset += 16;
  15223. instancesCount++;
  15224. }
  15225. }
  15226. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15227. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15228. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15229. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15230. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15231. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15232. this._draw(subMesh, fillMode, instancesCount);
  15233. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15234. };
  15235. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15236. var scene = this.getScene();
  15237. var engine = scene.getEngine();
  15238. if (hardwareInstancedRendering) {
  15239. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15240. }
  15241. else {
  15242. if (batch.renderSelf[subMesh._id]) {
  15243. // Draw
  15244. if (onBeforeDraw) {
  15245. onBeforeDraw(false, this.getWorldMatrix());
  15246. }
  15247. this._draw(subMesh, fillMode);
  15248. }
  15249. if (batch.visibleInstances[subMesh._id]) {
  15250. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15251. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15252. // World
  15253. var world = instance.getWorldMatrix();
  15254. if (onBeforeDraw) {
  15255. onBeforeDraw(true, world);
  15256. }
  15257. // Draw
  15258. this._draw(subMesh, fillMode);
  15259. }
  15260. }
  15261. }
  15262. };
  15263. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15264. var scene = this.getScene();
  15265. // Managing instances
  15266. var batch = this._getInstancesRenderList(subMesh._id);
  15267. if (batch.mustReturn) {
  15268. return;
  15269. }
  15270. // Checking geometry state
  15271. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15272. return;
  15273. }
  15274. var callbackIndex;
  15275. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15276. this._onBeforeRenderCallbacks[callbackIndex](this);
  15277. }
  15278. var engine = scene.getEngine();
  15279. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15280. // Material
  15281. var effectiveMaterial = subMesh.getMaterial();
  15282. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15283. return;
  15284. }
  15285. // Outline - step 1
  15286. var savedDepthWrite = engine.getDepthWrite();
  15287. if (this.renderOutline) {
  15288. engine.setDepthWrite(false);
  15289. scene.getOutlineRenderer().render(subMesh, batch);
  15290. engine.setDepthWrite(savedDepthWrite);
  15291. }
  15292. effectiveMaterial._preBind();
  15293. var effect = effectiveMaterial.getEffect();
  15294. // Bind
  15295. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15296. this._bind(subMesh, effect, fillMode);
  15297. var world = this.getWorldMatrix();
  15298. effectiveMaterial.bind(world, this);
  15299. // Alpha mode
  15300. if (enableAlphaMode) {
  15301. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15302. }
  15303. // Draw
  15304. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15305. if (isInstance) {
  15306. effectiveMaterial.bindOnlyWorldMatrix(world);
  15307. }
  15308. });
  15309. // Unbind
  15310. effectiveMaterial.unbind();
  15311. // Outline - step 2
  15312. if (this.renderOutline && savedDepthWrite) {
  15313. engine.setDepthWrite(true);
  15314. engine.setColorWrite(false);
  15315. scene.getOutlineRenderer().render(subMesh, batch);
  15316. engine.setColorWrite(true);
  15317. }
  15318. // Overlay
  15319. if (this.renderOverlay) {
  15320. var currentMode = engine.getAlphaMode();
  15321. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15322. scene.getOutlineRenderer().render(subMesh, batch, true);
  15323. engine.setAlphaMode(currentMode);
  15324. }
  15325. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15326. this._onAfterRenderCallbacks[callbackIndex](this);
  15327. }
  15328. };
  15329. Mesh.prototype.getEmittedParticleSystems = function () {
  15330. var results = new Array();
  15331. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15332. var particleSystem = this.getScene().particleSystems[index];
  15333. if (particleSystem.emitter === this) {
  15334. results.push(particleSystem);
  15335. }
  15336. }
  15337. return results;
  15338. };
  15339. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15340. var results = new Array();
  15341. var descendants = this.getDescendants();
  15342. descendants.push(this);
  15343. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15344. var particleSystem = this.getScene().particleSystems[index];
  15345. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15346. results.push(particleSystem);
  15347. }
  15348. }
  15349. return results;
  15350. };
  15351. Mesh.prototype.getChildren = function () {
  15352. var results = [];
  15353. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15354. var mesh = this.getScene().meshes[index];
  15355. if (mesh.parent === this) {
  15356. results.push(mesh);
  15357. }
  15358. }
  15359. return results;
  15360. };
  15361. Mesh.prototype._checkDelayState = function () {
  15362. var _this = this;
  15363. var that = this;
  15364. var scene = this.getScene();
  15365. if (this._geometry) {
  15366. this._geometry.load(scene);
  15367. }
  15368. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15369. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15370. scene._addPendingData(that);
  15371. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15372. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15373. if (data instanceof ArrayBuffer) {
  15374. _this._delayLoadingFunction(data, _this);
  15375. }
  15376. else {
  15377. _this._delayLoadingFunction(JSON.parse(data), _this);
  15378. }
  15379. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15380. scene._removePendingData(_this);
  15381. }, function () { }, scene.database, getBinaryData);
  15382. }
  15383. };
  15384. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15385. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15386. return false;
  15387. }
  15388. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15389. return false;
  15390. }
  15391. this._checkDelayState();
  15392. return true;
  15393. };
  15394. Mesh.prototype.setMaterialByID = function (id) {
  15395. var materials = this.getScene().materials;
  15396. var index;
  15397. for (index = 0; index < materials.length; index++) {
  15398. if (materials[index].id === id) {
  15399. this.material = materials[index];
  15400. return;
  15401. }
  15402. }
  15403. // Multi
  15404. var multiMaterials = this.getScene().multiMaterials;
  15405. for (index = 0; index < multiMaterials.length; index++) {
  15406. if (multiMaterials[index].id === id) {
  15407. this.material = multiMaterials[index];
  15408. return;
  15409. }
  15410. }
  15411. };
  15412. Mesh.prototype.getAnimatables = function () {
  15413. var results = [];
  15414. if (this.material) {
  15415. results.push(this.material);
  15416. }
  15417. if (this.skeleton) {
  15418. results.push(this.skeleton);
  15419. }
  15420. return results;
  15421. };
  15422. // Geometry
  15423. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15424. // Position
  15425. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15426. return;
  15427. }
  15428. this._resetPointsArrayCache();
  15429. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15430. var temp = [];
  15431. var index;
  15432. for (index = 0; index < data.length; index += 3) {
  15433. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15434. }
  15435. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15436. // Normals
  15437. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15438. return;
  15439. }
  15440. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15441. temp = [];
  15442. for (index = 0; index < data.length; index += 3) {
  15443. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15444. }
  15445. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15446. // flip faces?
  15447. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15448. this.flipFaces();
  15449. }
  15450. };
  15451. // Will apply current transform to mesh and reset world matrix
  15452. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15453. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15454. this.scaling.copyFromFloats(1, 1, 1);
  15455. this.position.copyFromFloats(0, 0, 0);
  15456. this.rotation.copyFromFloats(0, 0, 0);
  15457. //only if quaternion is already set
  15458. if (this.rotationQuaternion) {
  15459. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15460. }
  15461. this._worldMatrix = BABYLON.Matrix.Identity();
  15462. };
  15463. // Cache
  15464. Mesh.prototype._resetPointsArrayCache = function () {
  15465. this._positions = null;
  15466. };
  15467. Mesh.prototype._generatePointsArray = function () {
  15468. if (this._positions)
  15469. return true;
  15470. this._positions = [];
  15471. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15472. if (!data) {
  15473. return false;
  15474. }
  15475. for (var index = 0; index < data.length; index += 3) {
  15476. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15477. }
  15478. return true;
  15479. };
  15480. // Clone
  15481. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15482. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15483. };
  15484. // Dispose
  15485. Mesh.prototype.dispose = function (doNotRecurse) {
  15486. if (this._geometry) {
  15487. this._geometry.releaseForMesh(this, true);
  15488. }
  15489. // Instances
  15490. if (this._worldMatricesInstancesBuffer) {
  15491. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15492. this._worldMatricesInstancesBuffer = null;
  15493. }
  15494. while (this.instances.length) {
  15495. this.instances[0].dispose();
  15496. }
  15497. _super.prototype.dispose.call(this, doNotRecurse);
  15498. };
  15499. // Geometric tools
  15500. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15501. var _this = this;
  15502. var scene = this.getScene();
  15503. var onload = function (img) {
  15504. // Getting height map data
  15505. var canvas = document.createElement("canvas");
  15506. var context = canvas.getContext("2d");
  15507. var heightMapWidth = img.width;
  15508. var heightMapHeight = img.height;
  15509. canvas.width = heightMapWidth;
  15510. canvas.height = heightMapHeight;
  15511. context.drawImage(img, 0, 0);
  15512. // Create VertexData from map data
  15513. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15514. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15515. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15516. //execute success callback, if set
  15517. if (onSuccess) {
  15518. onSuccess(_this);
  15519. }
  15520. };
  15521. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15522. };
  15523. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15524. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15525. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15526. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15527. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15528. return;
  15529. }
  15530. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15531. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15532. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15533. var position = BABYLON.Vector3.Zero();
  15534. var normal = BABYLON.Vector3.Zero();
  15535. var uv = BABYLON.Vector2.Zero();
  15536. for (var index = 0; index < positions.length; index += 3) {
  15537. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15538. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15539. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15540. // Compute height
  15541. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15542. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15543. var pos = (u + v * heightMapWidth) * 4;
  15544. var r = buffer[pos] / 255.0;
  15545. var g = buffer[pos + 1] / 255.0;
  15546. var b = buffer[pos + 2] / 255.0;
  15547. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15548. normal.normalize();
  15549. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15550. position = position.add(normal);
  15551. position.toArray(positions, index);
  15552. }
  15553. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15554. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15555. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15556. };
  15557. Mesh.prototype.convertToFlatShadedMesh = function () {
  15558. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15559. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15560. var kinds = this.getVerticesDataKinds();
  15561. var vbs = [];
  15562. var data = [];
  15563. var newdata = [];
  15564. var updatableNormals = false;
  15565. var kindIndex;
  15566. var kind;
  15567. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15568. kind = kinds[kindIndex];
  15569. var vertexBuffer = this.getVertexBuffer(kind);
  15570. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15571. updatableNormals = vertexBuffer.isUpdatable();
  15572. kinds.splice(kindIndex, 1);
  15573. kindIndex--;
  15574. continue;
  15575. }
  15576. vbs[kind] = vertexBuffer;
  15577. data[kind] = vbs[kind].getData();
  15578. newdata[kind] = [];
  15579. }
  15580. // Save previous submeshes
  15581. var previousSubmeshes = this.subMeshes.slice(0);
  15582. var indices = this.getIndices();
  15583. var totalIndices = this.getTotalIndices();
  15584. // Generating unique vertices per face
  15585. var index;
  15586. for (index = 0; index < totalIndices; index++) {
  15587. var vertexIndex = indices[index];
  15588. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15589. kind = kinds[kindIndex];
  15590. var stride = vbs[kind].getStrideSize();
  15591. for (var offset = 0; offset < stride; offset++) {
  15592. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15593. }
  15594. }
  15595. }
  15596. // Updating faces & normal
  15597. var normals = [];
  15598. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15599. for (index = 0; index < totalIndices; index += 3) {
  15600. indices[index] = index;
  15601. indices[index + 1] = index + 1;
  15602. indices[index + 2] = index + 2;
  15603. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15604. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15605. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15606. var p1p2 = p1.subtract(p2);
  15607. var p3p2 = p3.subtract(p2);
  15608. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15609. // Store same normals for every vertex
  15610. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15611. normals.push(normal.x);
  15612. normals.push(normal.y);
  15613. normals.push(normal.z);
  15614. }
  15615. }
  15616. this.setIndices(indices);
  15617. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15618. // Updating vertex buffers
  15619. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15620. kind = kinds[kindIndex];
  15621. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15622. }
  15623. // Updating submeshes
  15624. this.releaseSubMeshes();
  15625. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15626. var previousOne = previousSubmeshes[submeshIndex];
  15627. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15628. }
  15629. this.synchronizeInstances();
  15630. };
  15631. Mesh.prototype.convertToUnIndexedMesh = function () {
  15632. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15633. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15634. var kinds = this.getVerticesDataKinds();
  15635. var vbs = [];
  15636. var data = [];
  15637. var newdata = [];
  15638. var updatableNormals = false;
  15639. var kindIndex;
  15640. var kind;
  15641. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15642. kind = kinds[kindIndex];
  15643. var vertexBuffer = this.getVertexBuffer(kind);
  15644. vbs[kind] = vertexBuffer;
  15645. data[kind] = vbs[kind].getData();
  15646. newdata[kind] = [];
  15647. }
  15648. // Save previous submeshes
  15649. var previousSubmeshes = this.subMeshes.slice(0);
  15650. var indices = this.getIndices();
  15651. var totalIndices = this.getTotalIndices();
  15652. // Generating unique vertices per face
  15653. var index;
  15654. for (index = 0; index < totalIndices; index++) {
  15655. var vertexIndex = indices[index];
  15656. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15657. kind = kinds[kindIndex];
  15658. var stride = vbs[kind].getStrideSize();
  15659. for (var offset = 0; offset < stride; offset++) {
  15660. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15661. }
  15662. }
  15663. }
  15664. // Updating indices
  15665. for (index = 0; index < totalIndices; index += 3) {
  15666. indices[index] = index;
  15667. indices[index + 1] = index + 1;
  15668. indices[index + 2] = index + 2;
  15669. }
  15670. this.setIndices(indices);
  15671. // Updating vertex buffers
  15672. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15673. kind = kinds[kindIndex];
  15674. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15675. }
  15676. // Updating submeshes
  15677. this.releaseSubMeshes();
  15678. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15679. var previousOne = previousSubmeshes[submeshIndex];
  15680. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15681. }
  15682. this._unIndexed = true;
  15683. this.synchronizeInstances();
  15684. };
  15685. // will inverse faces orientations, and invert normals too if specified
  15686. Mesh.prototype.flipFaces = function (flipNormals) {
  15687. if (flipNormals === void 0) { flipNormals = false; }
  15688. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15689. var i;
  15690. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15691. for (i = 0; i < vertex_data.normals.length; i++) {
  15692. vertex_data.normals[i] *= -1;
  15693. }
  15694. }
  15695. var temp;
  15696. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15697. // reassign indices
  15698. temp = vertex_data.indices[i + 1];
  15699. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15700. vertex_data.indices[i + 2] = temp;
  15701. }
  15702. vertex_data.applyToMesh(this);
  15703. };
  15704. // Instances
  15705. Mesh.prototype.createInstance = function (name) {
  15706. return new BABYLON.InstancedMesh(name, this);
  15707. };
  15708. Mesh.prototype.synchronizeInstances = function () {
  15709. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15710. var instance = this.instances[instanceIndex];
  15711. instance._syncSubMeshes();
  15712. }
  15713. };
  15714. /**
  15715. * Simplify the mesh according to the given array of settings.
  15716. * Function will return immediately and will simplify async.
  15717. * @param settings a collection of simplification settings.
  15718. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15719. * @param type the type of simplification to run.
  15720. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15721. */
  15722. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15723. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15724. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15725. this.getScene().simplificationQueue.addTask({
  15726. settings: settings,
  15727. parallelProcessing: parallelProcessing,
  15728. mesh: this,
  15729. simplificationType: simplificationType,
  15730. successCallback: successCallback
  15731. });
  15732. };
  15733. /**
  15734. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15735. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15736. * This should be used together with the simplification to avoid disappearing triangles.
  15737. * @param successCallback an optional success callback to be called after the optimization finished.
  15738. */
  15739. Mesh.prototype.optimizeIndices = function (successCallback) {
  15740. var _this = this;
  15741. var indices = this.getIndices();
  15742. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15743. var vectorPositions = [];
  15744. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15745. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15746. }
  15747. var dupes = [];
  15748. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15749. var realPos = vectorPositions.length - 1 - iteration;
  15750. var testedPosition = vectorPositions[realPos];
  15751. for (var j = 0; j < realPos; ++j) {
  15752. var againstPosition = vectorPositions[j];
  15753. if (testedPosition.equals(againstPosition)) {
  15754. dupes[realPos] = j;
  15755. break;
  15756. }
  15757. }
  15758. }, function () {
  15759. for (var i = 0; i < indices.length; ++i) {
  15760. indices[i] = dupes[indices[i]] || indices[i];
  15761. }
  15762. //indices are now reordered
  15763. var originalSubMeshes = _this.subMeshes.slice(0);
  15764. _this.setIndices(indices);
  15765. _this.subMeshes = originalSubMeshes;
  15766. if (successCallback) {
  15767. successCallback(_this);
  15768. }
  15769. });
  15770. };
  15771. // Statics
  15772. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15773. var mesh = new Mesh(parsedMesh.name, scene);
  15774. mesh.id = parsedMesh.id;
  15775. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15776. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15777. if (parsedMesh.rotationQuaternion) {
  15778. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15779. }
  15780. else if (parsedMesh.rotation) {
  15781. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15782. }
  15783. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15784. if (parsedMesh.localMatrix) {
  15785. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15786. }
  15787. else if (parsedMesh.pivotMatrix) {
  15788. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15789. }
  15790. mesh.setEnabled(parsedMesh.isEnabled);
  15791. mesh.isVisible = parsedMesh.isVisible;
  15792. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15793. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15794. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15795. if (parsedMesh.applyFog !== undefined) {
  15796. mesh.applyFog = parsedMesh.applyFog;
  15797. }
  15798. if (parsedMesh.pickable !== undefined) {
  15799. mesh.isPickable = parsedMesh.pickable;
  15800. }
  15801. if (parsedMesh.alphaIndex !== undefined) {
  15802. mesh.alphaIndex = parsedMesh.alphaIndex;
  15803. }
  15804. mesh.receiveShadows = parsedMesh.receiveShadows;
  15805. mesh.billboardMode = parsedMesh.billboardMode;
  15806. if (parsedMesh.visibility !== undefined) {
  15807. mesh.visibility = parsedMesh.visibility;
  15808. }
  15809. mesh.checkCollisions = parsedMesh.checkCollisions;
  15810. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15811. // freezeWorldMatrix
  15812. if (parsedMesh.freezeWorldMatrix) {
  15813. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15814. }
  15815. // Parent
  15816. if (parsedMesh.parentId) {
  15817. mesh._waitingParentId = parsedMesh.parentId;
  15818. }
  15819. // Actions
  15820. if (parsedMesh.actions !== undefined) {
  15821. mesh._waitingActions = parsedMesh.actions;
  15822. }
  15823. // Geometry
  15824. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15825. if (parsedMesh.delayLoadingFile) {
  15826. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15827. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15828. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15829. if (parsedMesh._binaryInfo) {
  15830. mesh._binaryInfo = parsedMesh._binaryInfo;
  15831. }
  15832. mesh._delayInfo = [];
  15833. if (parsedMesh.hasUVs) {
  15834. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15835. }
  15836. if (parsedMesh.hasUVs2) {
  15837. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15838. }
  15839. if (parsedMesh.hasUVs3) {
  15840. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15841. }
  15842. if (parsedMesh.hasUVs4) {
  15843. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15844. }
  15845. if (parsedMesh.hasUVs5) {
  15846. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15847. }
  15848. if (parsedMesh.hasUVs6) {
  15849. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15850. }
  15851. if (parsedMesh.hasColors) {
  15852. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15853. }
  15854. if (parsedMesh.hasMatricesIndices) {
  15855. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15856. }
  15857. if (parsedMesh.hasMatricesWeights) {
  15858. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15859. }
  15860. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15861. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15862. mesh._checkDelayState();
  15863. }
  15864. }
  15865. else {
  15866. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15867. }
  15868. // Material
  15869. if (parsedMesh.materialId) {
  15870. mesh.setMaterialByID(parsedMesh.materialId);
  15871. }
  15872. else {
  15873. mesh.material = null;
  15874. }
  15875. // Skeleton
  15876. if (parsedMesh.skeletonId > -1) {
  15877. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15878. if (parsedMesh.numBoneInfluencers) {
  15879. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15880. }
  15881. }
  15882. // Physics
  15883. if (parsedMesh.physicsImpostor) {
  15884. if (!scene.isPhysicsEnabled()) {
  15885. scene.enablePhysics();
  15886. }
  15887. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15888. }
  15889. // Animations
  15890. if (parsedMesh.animations) {
  15891. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15892. var parsedAnimation = parsedMesh.animations[animationIndex];
  15893. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15894. }
  15895. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15896. }
  15897. if (parsedMesh.autoAnimate) {
  15898. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15899. }
  15900. // Layer Mask
  15901. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15902. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15903. }
  15904. else {
  15905. mesh.layerMask = 0x0FFFFFFF;
  15906. }
  15907. // Instances
  15908. if (parsedMesh.instances) {
  15909. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15910. var parsedInstance = parsedMesh.instances[index];
  15911. var instance = mesh.createInstance(parsedInstance.name);
  15912. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15913. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15914. if (parsedInstance.rotationQuaternion) {
  15915. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15916. }
  15917. else if (parsedInstance.rotation) {
  15918. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15919. }
  15920. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15921. instance.checkCollisions = mesh.checkCollisions;
  15922. if (parsedMesh.animations) {
  15923. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15924. parsedAnimation = parsedMesh.animations[animationIndex];
  15925. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15926. }
  15927. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15928. }
  15929. }
  15930. }
  15931. return mesh;
  15932. };
  15933. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15934. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15935. pathArray: pathArray,
  15936. closeArray: closeArray,
  15937. closePath: closePath,
  15938. offset: offset,
  15939. updatable: updatable,
  15940. sideOrientation: sideOrientation,
  15941. instance: instance
  15942. }, scene);
  15943. };
  15944. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15945. var options = {
  15946. radius: radius,
  15947. tessellation: tessellation,
  15948. sideOrientation: sideOrientation,
  15949. updatable: updatable
  15950. };
  15951. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15952. };
  15953. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15954. var options = {
  15955. size: size,
  15956. sideOrientation: sideOrientation,
  15957. updatable: updatable
  15958. };
  15959. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15960. };
  15961. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15962. var options = {
  15963. segments: segments,
  15964. diameterX: diameter,
  15965. diameterY: diameter,
  15966. diameterZ: diameter,
  15967. sideOrientation: sideOrientation,
  15968. updatable: updatable
  15969. };
  15970. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15971. };
  15972. // Cylinder and cone
  15973. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15974. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15975. if (scene !== undefined) {
  15976. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15977. updatable = scene;
  15978. }
  15979. scene = subdivisions;
  15980. subdivisions = 1;
  15981. }
  15982. var options = {
  15983. height: height,
  15984. diameterTop: diameterTop,
  15985. diameterBottom: diameterBottom,
  15986. tessellation: tessellation,
  15987. subdivisions: subdivisions,
  15988. sideOrientation: sideOrientation,
  15989. updatable: updatable
  15990. };
  15991. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15992. };
  15993. // Torus (Code from SharpDX.org)
  15994. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15995. var options = {
  15996. diameter: diameter,
  15997. thickness: thickness,
  15998. tessellation: tessellation,
  15999. sideOrientation: sideOrientation,
  16000. updatable: updatable
  16001. };
  16002. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16003. };
  16004. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16005. var options = {
  16006. radius: radius,
  16007. tube: tube,
  16008. radialSegments: radialSegments,
  16009. tubularSegments: tubularSegments,
  16010. p: p,
  16011. q: q,
  16012. sideOrientation: sideOrientation,
  16013. updatable: updatable
  16014. };
  16015. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16016. };
  16017. // Lines
  16018. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16019. var options = {
  16020. points: points,
  16021. updatable: updatable,
  16022. instance: instance
  16023. };
  16024. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16025. };
  16026. // Dashed Lines
  16027. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16028. var options = {
  16029. points: points,
  16030. dashSize: dashSize,
  16031. gapSize: gapSize,
  16032. dashNb: dashNb,
  16033. updatable: updatable
  16034. };
  16035. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16036. };
  16037. // Extrusion
  16038. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16039. var options = {
  16040. shape: shape,
  16041. path: path,
  16042. scale: scale,
  16043. rotation: rotation,
  16044. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16045. sideOrientation: sideOrientation,
  16046. instance: instance,
  16047. updatable: updatable
  16048. };
  16049. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16050. };
  16051. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16052. var options = {
  16053. shape: shape,
  16054. path: path,
  16055. scaleFunction: scaleFunction,
  16056. rotationFunction: rotationFunction,
  16057. ribbonCloseArray: ribbonCloseArray,
  16058. ribbonClosePath: ribbonClosePath,
  16059. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16060. sideOrientation: sideOrientation,
  16061. instance: instance,
  16062. updatable: updatable
  16063. };
  16064. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16065. };
  16066. // Lathe
  16067. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16068. var options = {
  16069. shape: shape,
  16070. radius: radius,
  16071. tessellation: tessellation,
  16072. sideOrientation: sideOrientation,
  16073. updatable: updatable
  16074. };
  16075. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16076. };
  16077. // Plane & ground
  16078. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16079. var options = {
  16080. size: size,
  16081. width: size,
  16082. height: size,
  16083. sideOrientation: sideOrientation,
  16084. updatable: updatable
  16085. };
  16086. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16087. };
  16088. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16089. var options = {
  16090. width: width,
  16091. height: height,
  16092. subdivisions: subdivisions,
  16093. updatable: updatable
  16094. };
  16095. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16096. };
  16097. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16098. var options = {
  16099. xmin: xmin,
  16100. zmin: zmin,
  16101. xmax: xmax,
  16102. zmax: zmax,
  16103. subdivisions: subdivisions,
  16104. precision: precision,
  16105. updatable: updatable
  16106. };
  16107. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16108. };
  16109. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16110. var options = {
  16111. width: width,
  16112. height: height,
  16113. subdivisions: subdivisions,
  16114. minHeight: minHeight,
  16115. maxHeight: maxHeight,
  16116. updatable: updatable,
  16117. onReady: onReady
  16118. };
  16119. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16120. };
  16121. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16122. var options = {
  16123. path: path,
  16124. radius: radius,
  16125. tessellation: tessellation,
  16126. radiusFunction: radiusFunction,
  16127. arc: 1,
  16128. cap: cap,
  16129. updatable: updatable,
  16130. sideOrientation: sideOrientation,
  16131. instance: instance
  16132. };
  16133. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16134. };
  16135. Mesh.CreatePolyhedron = function (name, options, scene) {
  16136. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16137. };
  16138. Mesh.CreateIcoSphere = function (name, options, scene) {
  16139. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16140. };
  16141. // Decals
  16142. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16143. var options = {
  16144. position: position,
  16145. normal: normal,
  16146. size: size,
  16147. angle: angle
  16148. };
  16149. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16150. };
  16151. // Skeletons
  16152. /**
  16153. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16154. */
  16155. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16156. var source;
  16157. if (!this._sourcePositions) {
  16158. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16159. this._sourcePositions = new Float32Array(source);
  16160. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16161. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16162. }
  16163. }
  16164. return this._sourcePositions;
  16165. };
  16166. /**
  16167. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16168. */
  16169. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16170. var source;
  16171. if (!this._sourceNormals) {
  16172. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16173. this._sourceNormals = new Float32Array(source);
  16174. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16175. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16176. }
  16177. }
  16178. return this._sourceNormals;
  16179. };
  16180. /**
  16181. * Update the vertex buffers by applying transformation from the bones
  16182. * @param {skeleton} skeleton to apply
  16183. */
  16184. Mesh.prototype.applySkeleton = function (skeleton) {
  16185. if (!this.geometry) {
  16186. return;
  16187. }
  16188. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16189. return;
  16190. }
  16191. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16193. return this;
  16194. }
  16195. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16196. return this;
  16197. }
  16198. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16199. return this;
  16200. }
  16201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16202. return this;
  16203. }
  16204. if (!this._sourcePositions) {
  16205. this.setPositionsForCPUSkinning();
  16206. }
  16207. if (!this._sourceNormals) {
  16208. this.setNormalsForCPUSkinning();
  16209. }
  16210. // positionsData checks for not being Float32Array will only pass at most once
  16211. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16212. if (!(positionsData instanceof Float32Array)) {
  16213. positionsData = new Float32Array(positionsData);
  16214. }
  16215. // normalsData checks for not being Float32Array will only pass at most once
  16216. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16217. if (!(normalsData instanceof Float32Array)) {
  16218. normalsData = new Float32Array(normalsData);
  16219. }
  16220. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16221. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16222. var needExtras = this.numBoneInfluencers > 4;
  16223. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16224. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16225. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16226. var tempVector3 = BABYLON.Vector3.Zero();
  16227. var finalMatrix = new BABYLON.Matrix();
  16228. var tempMatrix = new BABYLON.Matrix();
  16229. var matWeightIdx = 0;
  16230. var inf;
  16231. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16232. var weight;
  16233. for (inf = 0; inf < 4; inf++) {
  16234. weight = matricesWeightsData[matWeightIdx + inf];
  16235. if (weight > 0) {
  16236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16237. finalMatrix.addToSelf(tempMatrix);
  16238. }
  16239. else
  16240. break;
  16241. }
  16242. if (needExtras) {
  16243. for (inf = 0; inf < 4; inf++) {
  16244. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16245. if (weight > 0) {
  16246. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16247. finalMatrix.addToSelf(tempMatrix);
  16248. }
  16249. else
  16250. break;
  16251. }
  16252. }
  16253. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16254. tempVector3.toArray(positionsData, index);
  16255. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16256. tempVector3.toArray(normalsData, index);
  16257. finalMatrix.reset();
  16258. }
  16259. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16260. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16261. return this;
  16262. };
  16263. // Tools
  16264. Mesh.MinMax = function (meshes) {
  16265. var minVector = null;
  16266. var maxVector = null;
  16267. for (var i in meshes) {
  16268. var mesh = meshes[i];
  16269. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16270. if (!minVector) {
  16271. minVector = boundingBox.minimumWorld;
  16272. maxVector = boundingBox.maximumWorld;
  16273. continue;
  16274. }
  16275. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16276. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16277. }
  16278. return {
  16279. min: minVector,
  16280. max: maxVector
  16281. };
  16282. };
  16283. Mesh.Center = function (meshesOrMinMaxVector) {
  16284. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16285. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16286. };
  16287. /**
  16288. * Merge the array of meshes into a single mesh for performance reasons.
  16289. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16290. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16291. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16292. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16293. */
  16294. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16295. if (disposeSource === void 0) { disposeSource = true; }
  16296. var index;
  16297. if (!allow32BitsIndices) {
  16298. var totalVertices = 0;
  16299. // Counting vertices
  16300. for (index = 0; index < meshes.length; index++) {
  16301. if (meshes[index]) {
  16302. totalVertices += meshes[index].getTotalVertices();
  16303. if (totalVertices > 65536) {
  16304. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16305. return null;
  16306. }
  16307. }
  16308. }
  16309. }
  16310. // Merge
  16311. var vertexData;
  16312. var otherVertexData;
  16313. var source;
  16314. for (index = 0; index < meshes.length; index++) {
  16315. if (meshes[index]) {
  16316. meshes[index].computeWorldMatrix(true);
  16317. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16318. otherVertexData.transform(meshes[index].getWorldMatrix());
  16319. if (vertexData) {
  16320. vertexData.merge(otherVertexData);
  16321. }
  16322. else {
  16323. vertexData = otherVertexData;
  16324. source = meshes[index];
  16325. }
  16326. }
  16327. }
  16328. if (!meshSubclass) {
  16329. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16330. }
  16331. vertexData.applyToMesh(meshSubclass);
  16332. // Setting properties
  16333. meshSubclass.material = source.material;
  16334. meshSubclass.checkCollisions = source.checkCollisions;
  16335. // Cleaning
  16336. if (disposeSource) {
  16337. for (index = 0; index < meshes.length; index++) {
  16338. if (meshes[index]) {
  16339. meshes[index].dispose();
  16340. }
  16341. }
  16342. }
  16343. return meshSubclass;
  16344. };
  16345. // Consts
  16346. Mesh._FRONTSIDE = 0;
  16347. Mesh._BACKSIDE = 1;
  16348. Mesh._DOUBLESIDE = 2;
  16349. Mesh._DEFAULTSIDE = 0;
  16350. Mesh._NO_CAP = 0;
  16351. Mesh._CAP_START = 1;
  16352. Mesh._CAP_END = 2;
  16353. Mesh._CAP_ALL = 3;
  16354. return Mesh;
  16355. })(BABYLON.AbstractMesh);
  16356. BABYLON.Mesh = Mesh;
  16357. })(BABYLON || (BABYLON = {}));
  16358. var BABYLON;
  16359. (function (BABYLON) {
  16360. var SubMesh = (function () {
  16361. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16362. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16363. this.materialIndex = materialIndex;
  16364. this.verticesStart = verticesStart;
  16365. this.verticesCount = verticesCount;
  16366. this.indexStart = indexStart;
  16367. this.indexCount = indexCount;
  16368. this._renderId = 0;
  16369. this._mesh = mesh;
  16370. this._renderingMesh = renderingMesh || mesh;
  16371. mesh.subMeshes.push(this);
  16372. this._trianglePlanes = [];
  16373. this._id = mesh.subMeshes.length - 1;
  16374. if (createBoundingBox) {
  16375. this.refreshBoundingInfo();
  16376. mesh.computeWorldMatrix(true);
  16377. }
  16378. }
  16379. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16380. get: function () {
  16381. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16382. },
  16383. enumerable: true,
  16384. configurable: true
  16385. });
  16386. SubMesh.prototype.getBoundingInfo = function () {
  16387. if (this.IsGlobal) {
  16388. return this._mesh.getBoundingInfo();
  16389. }
  16390. return this._boundingInfo;
  16391. };
  16392. SubMesh.prototype.getMesh = function () {
  16393. return this._mesh;
  16394. };
  16395. SubMesh.prototype.getRenderingMesh = function () {
  16396. return this._renderingMesh;
  16397. };
  16398. SubMesh.prototype.getMaterial = function () {
  16399. var rootMaterial = this._renderingMesh.material;
  16400. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16401. var multiMaterial = rootMaterial;
  16402. return multiMaterial.getSubMaterial(this.materialIndex);
  16403. }
  16404. if (!rootMaterial) {
  16405. return this._mesh.getScene().defaultMaterial;
  16406. }
  16407. return rootMaterial;
  16408. };
  16409. // Methods
  16410. SubMesh.prototype.refreshBoundingInfo = function () {
  16411. if (this.IsGlobal) {
  16412. return;
  16413. }
  16414. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16415. if (!data) {
  16416. this._boundingInfo = this._mesh._boundingInfo;
  16417. return;
  16418. }
  16419. var indices = this._renderingMesh.getIndices();
  16420. var extend;
  16421. //is this the only submesh?
  16422. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16423. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16424. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16425. }
  16426. else {
  16427. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16428. }
  16429. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16430. };
  16431. SubMesh.prototype._checkCollision = function (collider) {
  16432. return this.getBoundingInfo()._checkCollision(collider);
  16433. };
  16434. SubMesh.prototype.updateBoundingInfo = function (world) {
  16435. if (!this.getBoundingInfo()) {
  16436. this.refreshBoundingInfo();
  16437. }
  16438. this.getBoundingInfo().update(world);
  16439. };
  16440. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16441. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16442. };
  16443. SubMesh.prototype.render = function (enableAlphaMode) {
  16444. this._renderingMesh.render(this, enableAlphaMode);
  16445. };
  16446. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16447. if (!this._linesIndexBuffer) {
  16448. var linesIndices = [];
  16449. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16450. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16451. }
  16452. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16453. this.linesIndexCount = linesIndices.length;
  16454. }
  16455. return this._linesIndexBuffer;
  16456. };
  16457. SubMesh.prototype.canIntersects = function (ray) {
  16458. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16459. };
  16460. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16461. var intersectInfo = null;
  16462. // Triangles test
  16463. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16464. var p0 = positions[indices[index]];
  16465. var p1 = positions[indices[index + 1]];
  16466. var p2 = positions[indices[index + 2]];
  16467. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16468. if (currentIntersectInfo) {
  16469. if (currentIntersectInfo.distance < 0) {
  16470. continue;
  16471. }
  16472. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16473. intersectInfo = currentIntersectInfo;
  16474. intersectInfo.faceId = index / 3;
  16475. if (fastCheck) {
  16476. break;
  16477. }
  16478. }
  16479. }
  16480. }
  16481. return intersectInfo;
  16482. };
  16483. // Clone
  16484. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16485. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16486. if (!this.IsGlobal) {
  16487. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16488. }
  16489. return result;
  16490. };
  16491. // Dispose
  16492. SubMesh.prototype.dispose = function () {
  16493. if (this._linesIndexBuffer) {
  16494. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16495. this._linesIndexBuffer = null;
  16496. }
  16497. // Remove from mesh
  16498. var index = this._mesh.subMeshes.indexOf(this);
  16499. this._mesh.subMeshes.splice(index, 1);
  16500. };
  16501. // Statics
  16502. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16503. var minVertexIndex = Number.MAX_VALUE;
  16504. var maxVertexIndex = -Number.MAX_VALUE;
  16505. renderingMesh = renderingMesh || mesh;
  16506. var indices = renderingMesh.getIndices();
  16507. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16508. var vertexIndex = indices[index];
  16509. if (vertexIndex < minVertexIndex)
  16510. minVertexIndex = vertexIndex;
  16511. if (vertexIndex > maxVertexIndex)
  16512. maxVertexIndex = vertexIndex;
  16513. }
  16514. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16515. };
  16516. return SubMesh;
  16517. })();
  16518. BABYLON.SubMesh = SubMesh;
  16519. })(BABYLON || (BABYLON = {}));
  16520. var BABYLON;
  16521. (function (BABYLON) {
  16522. var MeshBuilder = (function () {
  16523. function MeshBuilder() {
  16524. }
  16525. MeshBuilder.CreateBox = function (name, options, scene) {
  16526. var box = new BABYLON.Mesh(name, scene);
  16527. var vertexData = BABYLON.VertexData.CreateBox(options);
  16528. vertexData.applyToMesh(box, options.updatable);
  16529. return box;
  16530. };
  16531. MeshBuilder.CreateSphere = function (name, options, scene) {
  16532. var sphere = new BABYLON.Mesh(name, scene);
  16533. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16534. vertexData.applyToMesh(sphere, options.updatable);
  16535. return sphere;
  16536. };
  16537. MeshBuilder.CreateDisc = function (name, options, scene) {
  16538. var disc = new BABYLON.Mesh(name, scene);
  16539. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16540. vertexData.applyToMesh(disc, options.updatable);
  16541. return disc;
  16542. };
  16543. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16544. var sphere = new BABYLON.Mesh(name, scene);
  16545. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16546. vertexData.applyToMesh(sphere, options.updatable);
  16547. return sphere;
  16548. };
  16549. ;
  16550. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16551. var pathArray = options.pathArray;
  16552. var closeArray = options.closeArray;
  16553. var closePath = options.closePath;
  16554. var offset = options.offset;
  16555. var sideOrientation = options.sideOrientation;
  16556. var instance = options.instance;
  16557. var updatable = options.updatable;
  16558. if (instance) {
  16559. // positionFunction : ribbon case
  16560. // only pathArray and sideOrientation parameters are taken into account for positions update
  16561. var positionFunction = function (positions) {
  16562. var minlg = pathArray[0].length;
  16563. var i = 0;
  16564. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16565. for (var si = 1; si <= ns; si++) {
  16566. for (var p = 0; p < pathArray.length; p++) {
  16567. var path = pathArray[p];
  16568. var l = path.length;
  16569. minlg = (minlg < l) ? minlg : l;
  16570. var j = 0;
  16571. while (j < minlg) {
  16572. positions[i] = path[j].x;
  16573. positions[i + 1] = path[j].y;
  16574. positions[i + 2] = path[j].z;
  16575. j++;
  16576. i += 3;
  16577. }
  16578. if (instance._closePath) {
  16579. positions[i] = path[0].x;
  16580. positions[i + 1] = path[0].y;
  16581. positions[i + 2] = path[0].z;
  16582. i += 3;
  16583. }
  16584. }
  16585. }
  16586. };
  16587. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16588. positionFunction(positions);
  16589. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16590. if (!(instance.areNormalsFrozen)) {
  16591. var indices = instance.getIndices();
  16592. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16593. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16594. if (instance._closePath) {
  16595. var indexFirst = 0;
  16596. var indexLast = 0;
  16597. for (var p = 0; p < pathArray.length; p++) {
  16598. indexFirst = instance._idx[p] * 3;
  16599. if (p + 1 < pathArray.length) {
  16600. indexLast = (instance._idx[p + 1] - 1) * 3;
  16601. }
  16602. else {
  16603. indexLast = normals.length - 3;
  16604. }
  16605. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16606. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16607. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16608. normals[indexLast] = normals[indexFirst];
  16609. normals[indexLast + 1] = normals[indexFirst + 1];
  16610. normals[indexLast + 2] = normals[indexFirst + 2];
  16611. }
  16612. }
  16613. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16614. }
  16615. return instance;
  16616. }
  16617. else {
  16618. var ribbon = new BABYLON.Mesh(name, scene);
  16619. ribbon.sideOrientation = sideOrientation;
  16620. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16621. if (closePath) {
  16622. ribbon._idx = vertexData._idx;
  16623. }
  16624. ribbon._closePath = closePath;
  16625. ribbon._closeArray = closeArray;
  16626. vertexData.applyToMesh(ribbon, updatable);
  16627. return ribbon;
  16628. }
  16629. };
  16630. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16631. var cylinder = new BABYLON.Mesh(name, scene);
  16632. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16633. vertexData.applyToMesh(cylinder, options.updatable);
  16634. return cylinder;
  16635. };
  16636. MeshBuilder.CreateTorus = function (name, options, scene) {
  16637. var torus = new BABYLON.Mesh(name, scene);
  16638. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16639. vertexData.applyToMesh(torus, options.updatable);
  16640. return torus;
  16641. };
  16642. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16643. var torusKnot = new BABYLON.Mesh(name, scene);
  16644. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16645. vertexData.applyToMesh(torusKnot, options.updatable);
  16646. return torusKnot;
  16647. };
  16648. MeshBuilder.CreateLines = function (name, options, scene) {
  16649. var instance = options.instance;
  16650. var points = options.points;
  16651. if (instance) {
  16652. var positionFunction = function (positions) {
  16653. var i = 0;
  16654. for (var p = 0; p < points.length; p++) {
  16655. positions[i] = points[p].x;
  16656. positions[i + 1] = points[p].y;
  16657. positions[i + 2] = points[p].z;
  16658. i += 3;
  16659. }
  16660. };
  16661. instance.updateMeshPositions(positionFunction, false);
  16662. return instance;
  16663. }
  16664. // lines creation
  16665. var lines = new BABYLON.LinesMesh(name, scene);
  16666. var vertexData = BABYLON.VertexData.CreateLines(options);
  16667. vertexData.applyToMesh(lines, options.updatable);
  16668. return lines;
  16669. };
  16670. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16671. var points = options.points;
  16672. var instance = options.instance;
  16673. var gapSize = options.gapSize;
  16674. var dashNb = options.dashNb;
  16675. var dashSize = options.dashSize;
  16676. if (instance) {
  16677. var positionFunction = function (positions) {
  16678. var curvect = BABYLON.Vector3.Zero();
  16679. var nbSeg = positions.length / 6;
  16680. var lg = 0;
  16681. var nb = 0;
  16682. var shft = 0;
  16683. var dashshft = 0;
  16684. var curshft = 0;
  16685. var p = 0;
  16686. var i = 0;
  16687. var j = 0;
  16688. for (i = 0; i < points.length - 1; i++) {
  16689. points[i + 1].subtractToRef(points[i], curvect);
  16690. lg += curvect.length();
  16691. }
  16692. shft = lg / nbSeg;
  16693. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16694. for (i = 0; i < points.length - 1; i++) {
  16695. points[i + 1].subtractToRef(points[i], curvect);
  16696. nb = Math.floor(curvect.length() / shft);
  16697. curvect.normalize();
  16698. j = 0;
  16699. while (j < nb && p < positions.length) {
  16700. curshft = shft * j;
  16701. positions[p] = points[i].x + curshft * curvect.x;
  16702. positions[p + 1] = points[i].y + curshft * curvect.y;
  16703. positions[p + 2] = points[i].z + curshft * curvect.z;
  16704. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16705. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16706. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16707. p += 6;
  16708. j++;
  16709. }
  16710. }
  16711. while (p < positions.length) {
  16712. positions[p] = points[i].x;
  16713. positions[p + 1] = points[i].y;
  16714. positions[p + 2] = points[i].z;
  16715. p += 3;
  16716. }
  16717. };
  16718. instance.updateMeshPositions(positionFunction, false);
  16719. return instance;
  16720. }
  16721. // dashed lines creation
  16722. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16723. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16724. vertexData.applyToMesh(dashedLines, options.updatable);
  16725. dashedLines.dashSize = dashSize;
  16726. dashedLines.gapSize = gapSize;
  16727. return dashedLines;
  16728. };
  16729. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16730. var path = options.path;
  16731. var shape = options.shape;
  16732. var scale = options.scale || 1;
  16733. var rotation = options.rotation || 0;
  16734. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16735. var updatable = options.updatable;
  16736. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16737. var instance = options.instance;
  16738. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16739. };
  16740. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16741. var path = options.path;
  16742. var shape = options.shape;
  16743. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16744. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16745. var ribbonCloseArray = options.ribbonCloseArray || false;
  16746. var ribbonClosePath = options.ribbonClosePath || false;
  16747. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16748. var updatable = options.updatable;
  16749. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16750. var instance = options.instance;
  16751. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16752. };
  16753. MeshBuilder.CreateLathe = function (name, options, scene) {
  16754. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16755. var closed = (options.closed === undefined) ? true : options.closed;
  16756. var shape = options.shape;
  16757. var radius = options.radius || 1;
  16758. var tessellation = options.tessellation || 64;
  16759. var updatable = options.updatable;
  16760. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16761. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16762. var pi2 = Math.PI * 2;
  16763. var paths = new Array();
  16764. var i = 0;
  16765. var p = 0;
  16766. var step = pi2 / tessellation * arc;
  16767. var rotated;
  16768. var path = new Array();
  16769. ;
  16770. for (i = 0; i <= tessellation; i++) {
  16771. var path = [];
  16772. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16773. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16774. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16775. }
  16776. for (p = 0; p < shape.length; p++) {
  16777. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16778. path.push(rotated);
  16779. }
  16780. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16781. 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));
  16782. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16783. }
  16784. paths.push(path);
  16785. }
  16786. // lathe ribbon
  16787. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16788. return lathe;
  16789. };
  16790. MeshBuilder.CreatePlane = function (name, options, scene) {
  16791. var plane = new BABYLON.Mesh(name, scene);
  16792. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16793. vertexData.applyToMesh(plane, options.updatable);
  16794. if (options.sourcePlane) {
  16795. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16796. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16797. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16798. plane.rotate(vectorProduct, product);
  16799. }
  16800. return plane;
  16801. };
  16802. MeshBuilder.CreateGround = function (name, options, scene) {
  16803. var ground = new BABYLON.GroundMesh(name, scene);
  16804. ground._setReady(false);
  16805. ground._subdivisions = options.subdivisions || 1;
  16806. ground._width = options.width || 1;
  16807. ground._height = options.height || 1;
  16808. ground._maxX = ground._width / 2;
  16809. ground._maxZ = ground._height / 2;
  16810. ground._minX = -ground._maxX;
  16811. ground._minZ = -ground._maxZ;
  16812. var vertexData = BABYLON.VertexData.CreateGround(options);
  16813. vertexData.applyToMesh(ground, options.updatable);
  16814. ground._setReady(true);
  16815. return ground;
  16816. };
  16817. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16818. var tiledGround = new BABYLON.Mesh(name, scene);
  16819. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16820. vertexData.applyToMesh(tiledGround, options.updatable);
  16821. return tiledGround;
  16822. };
  16823. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16824. var width = options.width || 10;
  16825. var height = options.height || 10;
  16826. var subdivisions = options.subdivisions || 1;
  16827. var minHeight = options.minHeight;
  16828. var maxHeight = options.maxHeight || 10;
  16829. var updatable = options.updatable;
  16830. var onReady = options.onReady;
  16831. var ground = new BABYLON.GroundMesh(name, scene);
  16832. ground._subdivisions = subdivisions;
  16833. ground._width = width;
  16834. ground._height = height;
  16835. ground._maxX = ground._width / 2;
  16836. ground._maxZ = ground._height / 2;
  16837. ground._minX = -ground._maxX;
  16838. ground._minZ = -ground._maxZ;
  16839. ground._setReady(false);
  16840. var onload = function (img) {
  16841. // Getting height map data
  16842. var canvas = document.createElement("canvas");
  16843. var context = canvas.getContext("2d");
  16844. var bufferWidth = img.width;
  16845. var bufferHeight = img.height;
  16846. canvas.width = bufferWidth;
  16847. canvas.height = bufferHeight;
  16848. context.drawImage(img, 0, 0);
  16849. // Create VertexData from map data
  16850. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16851. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16852. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16853. width: width, height: height,
  16854. subdivisions: subdivisions,
  16855. minHeight: minHeight, maxHeight: maxHeight,
  16856. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16857. });
  16858. vertexData.applyToMesh(ground, updatable);
  16859. ground._setReady(true);
  16860. //execute ready callback, if set
  16861. if (onReady) {
  16862. onReady(ground);
  16863. }
  16864. };
  16865. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16866. return ground;
  16867. };
  16868. MeshBuilder.CreateTube = function (name, options, scene) {
  16869. var path = options.path;
  16870. var radius = options.radius || 1;
  16871. var tessellation = options.tessellation || 64;
  16872. var radiusFunction = options.radiusFunction;
  16873. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16874. var updatable = options.updatable;
  16875. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16876. var instance = options.instance;
  16877. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16878. // tube geometry
  16879. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16880. var tangents = path3D.getTangents();
  16881. var normals = path3D.getNormals();
  16882. var distances = path3D.getDistances();
  16883. var pi2 = Math.PI * 2;
  16884. var step = pi2 / tessellation * arc;
  16885. var returnRadius = function () { return radius; };
  16886. var radiusFunctionFinal = radiusFunction || returnRadius;
  16887. var circlePath;
  16888. var rad;
  16889. var normal;
  16890. var rotated;
  16891. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16892. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16893. for (var i = 0; i < path.length; i++) {
  16894. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16895. circlePath = Array(); // current circle array
  16896. normal = normals[i]; // current normal
  16897. for (var t = 0; t < tessellation; t++) {
  16898. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16899. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16900. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16901. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16902. circlePath[t] = rotated;
  16903. }
  16904. circlePaths[index] = circlePath;
  16905. index++;
  16906. }
  16907. // cap
  16908. var capPath = function (nbPoints, pathIndex) {
  16909. var pointCap = Array();
  16910. for (var i = 0; i < nbPoints; i++) {
  16911. pointCap.push(path[pathIndex]);
  16912. }
  16913. return pointCap;
  16914. };
  16915. switch (cap) {
  16916. case BABYLON.Mesh.NO_CAP:
  16917. break;
  16918. case BABYLON.Mesh.CAP_START:
  16919. circlePaths[0] = capPath(tessellation, 0);
  16920. circlePaths[1] = circlePaths[2].slice(0);
  16921. break;
  16922. case BABYLON.Mesh.CAP_END:
  16923. circlePaths[index] = circlePaths[index - 1].slice(0);
  16924. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16925. break;
  16926. case BABYLON.Mesh.CAP_ALL:
  16927. circlePaths[0] = capPath(tessellation, 0);
  16928. circlePaths[1] = circlePaths[2].slice(0);
  16929. circlePaths[index] = circlePaths[index - 1].slice(0);
  16930. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16931. break;
  16932. default:
  16933. break;
  16934. }
  16935. return circlePaths;
  16936. };
  16937. var path3D;
  16938. var pathArray;
  16939. if (instance) {
  16940. var arc = options.arc || instance.arc;
  16941. path3D = (instance.path3D).update(path);
  16942. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16943. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16944. instance.path3D = path3D;
  16945. instance.pathArray = pathArray;
  16946. instance.arc = arc;
  16947. return instance;
  16948. }
  16949. // tube creation
  16950. path3D = new BABYLON.Path3D(path);
  16951. var newPathArray = new Array();
  16952. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16953. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16954. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16955. tube.pathArray = pathArray;
  16956. tube.path3D = path3D;
  16957. tube.tessellation = tessellation;
  16958. tube.cap = cap;
  16959. tube.arc = options.arc;
  16960. return tube;
  16961. };
  16962. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16963. var polyhedron = new BABYLON.Mesh(name, scene);
  16964. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16965. vertexData.applyToMesh(polyhedron, options.updatable);
  16966. return polyhedron;
  16967. };
  16968. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16969. var indices = sourceMesh.getIndices();
  16970. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16971. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16972. var position = options.position || BABYLON.Vector3.Zero();
  16973. var normal = options.normal || BABYLON.Vector3.Up();
  16974. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16975. var angle = options.angle || 0;
  16976. // Getting correct rotation
  16977. if (!normal) {
  16978. var target = new BABYLON.Vector3(0, 0, 1);
  16979. var camera = sourceMesh.getScene().activeCamera;
  16980. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16981. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16982. }
  16983. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16984. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16985. var pitch = Math.atan2(normal.y, len);
  16986. // Matrix
  16987. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16988. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16989. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16990. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16991. var vertexData = new BABYLON.VertexData();
  16992. vertexData.indices = [];
  16993. vertexData.positions = [];
  16994. vertexData.normals = [];
  16995. vertexData.uvs = [];
  16996. var currentVertexDataIndex = 0;
  16997. var extractDecalVector3 = function (indexId) {
  16998. var vertexId = indices[indexId];
  16999. var result = new BABYLON.PositionNormalVertex();
  17000. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17001. // Send vector to decal local world
  17002. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17003. // Get normal
  17004. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17005. return result;
  17006. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17007. var clip = function (vertices, axis) {
  17008. if (vertices.length === 0) {
  17009. return vertices;
  17010. }
  17011. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17012. var clipVertices = function (v0, v1) {
  17013. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17014. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17015. };
  17016. var result = new Array();
  17017. for (var index = 0; index < vertices.length; index += 3) {
  17018. var v1Out;
  17019. var v2Out;
  17020. var v3Out;
  17021. var total = 0;
  17022. var nV1, nV2, nV3, nV4;
  17023. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17024. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17025. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17026. v1Out = d1 > 0;
  17027. v2Out = d2 > 0;
  17028. v3Out = d3 > 0;
  17029. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17030. switch (total) {
  17031. case 0:
  17032. result.push(vertices[index]);
  17033. result.push(vertices[index + 1]);
  17034. result.push(vertices[index + 2]);
  17035. break;
  17036. case 1:
  17037. if (v1Out) {
  17038. nV1 = vertices[index + 1];
  17039. nV2 = vertices[index + 2];
  17040. nV3 = clipVertices(vertices[index], nV1);
  17041. nV4 = clipVertices(vertices[index], nV2);
  17042. }
  17043. if (v2Out) {
  17044. nV1 = vertices[index];
  17045. nV2 = vertices[index + 2];
  17046. nV3 = clipVertices(vertices[index + 1], nV1);
  17047. nV4 = clipVertices(vertices[index + 1], nV2);
  17048. result.push(nV3);
  17049. result.push(nV2.clone());
  17050. result.push(nV1.clone());
  17051. result.push(nV2.clone());
  17052. result.push(nV3.clone());
  17053. result.push(nV4);
  17054. break;
  17055. }
  17056. if (v3Out) {
  17057. nV1 = vertices[index];
  17058. nV2 = vertices[index + 1];
  17059. nV3 = clipVertices(vertices[index + 2], nV1);
  17060. nV4 = clipVertices(vertices[index + 2], nV2);
  17061. }
  17062. result.push(nV1.clone());
  17063. result.push(nV2.clone());
  17064. result.push(nV3);
  17065. result.push(nV4);
  17066. result.push(nV3.clone());
  17067. result.push(nV2.clone());
  17068. break;
  17069. case 2:
  17070. if (!v1Out) {
  17071. nV1 = vertices[index].clone();
  17072. nV2 = clipVertices(nV1, vertices[index + 1]);
  17073. nV3 = clipVertices(nV1, vertices[index + 2]);
  17074. result.push(nV1);
  17075. result.push(nV2);
  17076. result.push(nV3);
  17077. }
  17078. if (!v2Out) {
  17079. nV1 = vertices[index + 1].clone();
  17080. nV2 = clipVertices(nV1, vertices[index + 2]);
  17081. nV3 = clipVertices(nV1, vertices[index]);
  17082. result.push(nV1);
  17083. result.push(nV2);
  17084. result.push(nV3);
  17085. }
  17086. if (!v3Out) {
  17087. nV1 = vertices[index + 2].clone();
  17088. nV2 = clipVertices(nV1, vertices[index]);
  17089. nV3 = clipVertices(nV1, vertices[index + 1]);
  17090. result.push(nV1);
  17091. result.push(nV2);
  17092. result.push(nV3);
  17093. }
  17094. break;
  17095. case 3:
  17096. break;
  17097. }
  17098. }
  17099. return result;
  17100. };
  17101. for (var index = 0; index < indices.length; index += 3) {
  17102. var faceVertices = new Array();
  17103. faceVertices.push(extractDecalVector3(index));
  17104. faceVertices.push(extractDecalVector3(index + 1));
  17105. faceVertices.push(extractDecalVector3(index + 2));
  17106. // Clip
  17107. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17108. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17109. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17110. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17111. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17112. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17113. if (faceVertices.length === 0) {
  17114. continue;
  17115. }
  17116. // Add UVs and get back to world
  17117. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17118. var vertex = faceVertices[vIndex];
  17119. //TODO check for Int32Array
  17120. vertexData.indices.push(currentVertexDataIndex);
  17121. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17122. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17123. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17124. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17125. currentVertexDataIndex++;
  17126. }
  17127. }
  17128. // Return mesh
  17129. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17130. vertexData.applyToMesh(decal);
  17131. decal.position = position.clone();
  17132. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17133. return decal;
  17134. };
  17135. // Privates
  17136. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17137. // extrusion geometry
  17138. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17139. var tangents = path3D.getTangents();
  17140. var normals = path3D.getNormals();
  17141. var binormals = path3D.getBinormals();
  17142. var distances = path3D.getDistances();
  17143. var angle = 0;
  17144. var returnScale = function () { return scale; };
  17145. var returnRotation = function () { return rotation; };
  17146. var rotate = custom ? rotateFunction : returnRotation;
  17147. var scl = custom ? scaleFunction : returnScale;
  17148. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17149. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17150. for (var i = 0; i < curve.length; i++) {
  17151. var shapePath = new Array();
  17152. var angleStep = rotate(i, distances[i]);
  17153. var scaleRatio = scl(i, distances[i]);
  17154. for (var p = 0; p < shape.length; p++) {
  17155. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17156. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17157. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17158. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17159. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17160. shapePath[p] = rotated;
  17161. }
  17162. shapePaths[index] = shapePath;
  17163. angle += angleStep;
  17164. index++;
  17165. }
  17166. // cap
  17167. var capPath = function (shapePath) {
  17168. var pointCap = Array();
  17169. var barycenter = BABYLON.Vector3.Zero();
  17170. var i;
  17171. for (i = 0; i < shapePath.length; i++) {
  17172. barycenter.addInPlace(shapePath[i]);
  17173. }
  17174. barycenter.scaleInPlace(1 / shapePath.length);
  17175. for (i = 0; i < shapePath.length; i++) {
  17176. pointCap.push(barycenter);
  17177. }
  17178. return pointCap;
  17179. };
  17180. switch (cap) {
  17181. case BABYLON.Mesh.NO_CAP:
  17182. break;
  17183. case BABYLON.Mesh.CAP_START:
  17184. shapePaths[0] = capPath(shapePaths[2]);
  17185. shapePaths[1] = shapePaths[2].slice(0);
  17186. break;
  17187. case BABYLON.Mesh.CAP_END:
  17188. shapePaths[index] = shapePaths[index - 1];
  17189. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17190. break;
  17191. case BABYLON.Mesh.CAP_ALL:
  17192. shapePaths[0] = capPath(shapePaths[2]);
  17193. shapePaths[1] = shapePaths[2].slice(0);
  17194. shapePaths[index] = shapePaths[index - 1];
  17195. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17196. break;
  17197. default:
  17198. break;
  17199. }
  17200. return shapePaths;
  17201. };
  17202. var path3D;
  17203. var pathArray;
  17204. if (instance) {
  17205. path3D = (instance.path3D).update(curve);
  17206. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17207. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17208. return instance;
  17209. }
  17210. // extruded shape creation
  17211. path3D = new BABYLON.Path3D(curve);
  17212. var newShapePaths = new Array();
  17213. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17214. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17215. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17216. extrudedGeneric.pathArray = pathArray;
  17217. extrudedGeneric.path3D = path3D;
  17218. extrudedGeneric.cap = cap;
  17219. return extrudedGeneric;
  17220. };
  17221. return MeshBuilder;
  17222. })();
  17223. BABYLON.MeshBuilder = MeshBuilder;
  17224. })(BABYLON || (BABYLON = {}));
  17225. var BABYLON;
  17226. (function (BABYLON) {
  17227. var BaseTexture = (function () {
  17228. function BaseTexture(scene) {
  17229. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17230. this.hasAlpha = false;
  17231. this.getAlphaFromRGB = false;
  17232. this.level = 1;
  17233. this.isCube = false;
  17234. this.isRenderTarget = false;
  17235. this.animations = new Array();
  17236. this.coordinatesIndex = 0;
  17237. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17238. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17239. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17240. this.anisotropicFilteringLevel = 4;
  17241. this._scene = scene;
  17242. this._scene.textures.push(this);
  17243. }
  17244. BaseTexture.prototype.getScene = function () {
  17245. return this._scene;
  17246. };
  17247. BaseTexture.prototype.getTextureMatrix = function () {
  17248. return null;
  17249. };
  17250. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17251. return null;
  17252. };
  17253. BaseTexture.prototype.getInternalTexture = function () {
  17254. return this._texture;
  17255. };
  17256. BaseTexture.prototype.isReady = function () {
  17257. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17258. return true;
  17259. }
  17260. if (this._texture) {
  17261. return this._texture.isReady;
  17262. }
  17263. return false;
  17264. };
  17265. BaseTexture.prototype.getSize = function () {
  17266. if (this._texture._width) {
  17267. return { width: this._texture._width, height: this._texture._height };
  17268. }
  17269. if (this._texture._size) {
  17270. return { width: this._texture._size, height: this._texture._size };
  17271. }
  17272. return { width: 0, height: 0 };
  17273. };
  17274. BaseTexture.prototype.getBaseSize = function () {
  17275. if (!this.isReady())
  17276. return { width: 0, height: 0 };
  17277. if (this._texture._size) {
  17278. return { width: this._texture._size, height: this._texture._size };
  17279. }
  17280. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17281. };
  17282. BaseTexture.prototype.scale = function (ratio) {
  17283. };
  17284. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17285. get: function () {
  17286. return false;
  17287. },
  17288. enumerable: true,
  17289. configurable: true
  17290. });
  17291. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17292. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17293. for (var index = 0; index < texturesCache.length; index++) {
  17294. var texturesCacheEntry = texturesCache[index];
  17295. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17296. texturesCache.splice(index, 1);
  17297. return;
  17298. }
  17299. }
  17300. };
  17301. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17302. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17303. for (var index = 0; index < texturesCache.length; index++) {
  17304. var texturesCacheEntry = texturesCache[index];
  17305. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17306. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17307. texturesCacheEntry.references++;
  17308. return texturesCacheEntry;
  17309. }
  17310. }
  17311. }
  17312. return null;
  17313. };
  17314. BaseTexture.prototype.delayLoad = function () {
  17315. };
  17316. BaseTexture.prototype.clone = function () {
  17317. return null;
  17318. };
  17319. BaseTexture.prototype.releaseInternalTexture = function () {
  17320. if (this._texture) {
  17321. this._scene.getEngine().releaseInternalTexture(this._texture);
  17322. delete this._texture;
  17323. }
  17324. };
  17325. BaseTexture.prototype.dispose = function () {
  17326. // Animations
  17327. this.getScene().stopAnimation(this);
  17328. // Remove from scene
  17329. var index = this._scene.textures.indexOf(this);
  17330. if (index >= 0) {
  17331. this._scene.textures.splice(index, 1);
  17332. }
  17333. if (this._texture === undefined) {
  17334. return;
  17335. }
  17336. // Release
  17337. this.releaseInternalTexture();
  17338. // Callback
  17339. if (this.onDispose) {
  17340. this.onDispose();
  17341. }
  17342. };
  17343. BaseTexture.prototype.serialize = function () {
  17344. var serializationObject = {};
  17345. if (!this.name) {
  17346. return null;
  17347. }
  17348. serializationObject.name = this.name;
  17349. serializationObject.hasAlpha = this.hasAlpha;
  17350. serializationObject.level = this.level;
  17351. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17352. serializationObject.coordinatesMode = this.coordinatesMode;
  17353. serializationObject.wrapU = this.wrapU;
  17354. serializationObject.wrapV = this.wrapV;
  17355. // Animations
  17356. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17357. return serializationObject;
  17358. };
  17359. return BaseTexture;
  17360. })();
  17361. BABYLON.BaseTexture = BaseTexture;
  17362. })(BABYLON || (BABYLON = {}));
  17363. var BABYLON;
  17364. (function (BABYLON) {
  17365. var Texture = (function (_super) {
  17366. __extends(Texture, _super);
  17367. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17368. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17369. if (onLoad === void 0) { onLoad = null; }
  17370. if (onError === void 0) { onError = null; }
  17371. if (buffer === void 0) { buffer = null; }
  17372. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17373. _super.call(this, scene);
  17374. this.uOffset = 0;
  17375. this.vOffset = 0;
  17376. this.uScale = 1.0;
  17377. this.vScale = 1.0;
  17378. this.uAng = 0;
  17379. this.vAng = 0;
  17380. this.wAng = 0;
  17381. this.name = url;
  17382. this.url = url;
  17383. this._noMipmap = noMipmap;
  17384. this._invertY = invertY;
  17385. this._samplingMode = samplingMode;
  17386. this._buffer = buffer;
  17387. this._deleteBuffer = deleteBuffer;
  17388. if (!url) {
  17389. return;
  17390. }
  17391. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17392. if (!this._texture) {
  17393. if (!scene.useDelayedTextureLoading) {
  17394. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17395. if (deleteBuffer) {
  17396. delete this._buffer;
  17397. }
  17398. }
  17399. else {
  17400. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17401. }
  17402. }
  17403. else {
  17404. BABYLON.Tools.SetImmediate(function () {
  17405. if (onLoad) {
  17406. onLoad();
  17407. }
  17408. });
  17409. }
  17410. }
  17411. Texture.prototype.delayLoad = function () {
  17412. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17413. return;
  17414. }
  17415. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17416. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17417. if (!this._texture) {
  17418. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17419. if (this._deleteBuffer) {
  17420. delete this._buffer;
  17421. }
  17422. }
  17423. };
  17424. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17425. if (!this._texture) {
  17426. return;
  17427. }
  17428. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17429. };
  17430. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17431. x *= this.uScale;
  17432. y *= this.vScale;
  17433. x -= 0.5 * this.uScale;
  17434. y -= 0.5 * this.vScale;
  17435. z -= 0.5;
  17436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17437. t.x += 0.5 * this.uScale + this.uOffset;
  17438. t.y += 0.5 * this.vScale + this.vOffset;
  17439. t.z += 0.5;
  17440. };
  17441. Texture.prototype.getTextureMatrix = function () {
  17442. if (this.uOffset === this._cachedUOffset &&
  17443. this.vOffset === this._cachedVOffset &&
  17444. this.uScale === this._cachedUScale &&
  17445. this.vScale === this._cachedVScale &&
  17446. this.uAng === this._cachedUAng &&
  17447. this.vAng === this._cachedVAng &&
  17448. this.wAng === this._cachedWAng) {
  17449. return this._cachedTextureMatrix;
  17450. }
  17451. this._cachedUOffset = this.uOffset;
  17452. this._cachedVOffset = this.vOffset;
  17453. this._cachedUScale = this.uScale;
  17454. this._cachedVScale = this.vScale;
  17455. this._cachedUAng = this.uAng;
  17456. this._cachedVAng = this.vAng;
  17457. this._cachedWAng = this.wAng;
  17458. if (!this._cachedTextureMatrix) {
  17459. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17460. this._rowGenerationMatrix = new BABYLON.Matrix();
  17461. this._t0 = BABYLON.Vector3.Zero();
  17462. this._t1 = BABYLON.Vector3.Zero();
  17463. this._t2 = BABYLON.Vector3.Zero();
  17464. }
  17465. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17466. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17467. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17468. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17469. this._t1.subtractInPlace(this._t0);
  17470. this._t2.subtractInPlace(this._t0);
  17471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17472. this._cachedTextureMatrix.m[0] = this._t1.x;
  17473. this._cachedTextureMatrix.m[1] = this._t1.y;
  17474. this._cachedTextureMatrix.m[2] = this._t1.z;
  17475. this._cachedTextureMatrix.m[4] = this._t2.x;
  17476. this._cachedTextureMatrix.m[5] = this._t2.y;
  17477. this._cachedTextureMatrix.m[6] = this._t2.z;
  17478. this._cachedTextureMatrix.m[8] = this._t0.x;
  17479. this._cachedTextureMatrix.m[9] = this._t0.y;
  17480. this._cachedTextureMatrix.m[10] = this._t0.z;
  17481. return this._cachedTextureMatrix;
  17482. };
  17483. Texture.prototype.getReflectionTextureMatrix = function () {
  17484. if (this.uOffset === this._cachedUOffset &&
  17485. this.vOffset === this._cachedVOffset &&
  17486. this.uScale === this._cachedUScale &&
  17487. this.vScale === this._cachedVScale &&
  17488. this.coordinatesMode === this._cachedCoordinatesMode) {
  17489. return this._cachedTextureMatrix;
  17490. }
  17491. if (!this._cachedTextureMatrix) {
  17492. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17493. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17494. }
  17495. this._cachedCoordinatesMode = this.coordinatesMode;
  17496. switch (this.coordinatesMode) {
  17497. case Texture.PLANAR_MODE:
  17498. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17499. this._cachedTextureMatrix[0] = this.uScale;
  17500. this._cachedTextureMatrix[5] = this.vScale;
  17501. this._cachedTextureMatrix[12] = this.uOffset;
  17502. this._cachedTextureMatrix[13] = this.vOffset;
  17503. break;
  17504. case Texture.PROJECTION_MODE:
  17505. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17506. this._projectionModeMatrix.m[0] = 0.5;
  17507. this._projectionModeMatrix.m[5] = -0.5;
  17508. this._projectionModeMatrix.m[10] = 0.0;
  17509. this._projectionModeMatrix.m[12] = 0.5;
  17510. this._projectionModeMatrix.m[13] = 0.5;
  17511. this._projectionModeMatrix.m[14] = 1.0;
  17512. this._projectionModeMatrix.m[15] = 1.0;
  17513. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17514. break;
  17515. default:
  17516. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17517. break;
  17518. }
  17519. return this._cachedTextureMatrix;
  17520. };
  17521. Texture.prototype.clone = function () {
  17522. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17523. // Base texture
  17524. newTexture.hasAlpha = this.hasAlpha;
  17525. newTexture.level = this.level;
  17526. newTexture.wrapU = this.wrapU;
  17527. newTexture.wrapV = this.wrapV;
  17528. newTexture.coordinatesIndex = this.coordinatesIndex;
  17529. newTexture.coordinatesMode = this.coordinatesMode;
  17530. // Texture
  17531. newTexture.uOffset = this.uOffset;
  17532. newTexture.vOffset = this.vOffset;
  17533. newTexture.uScale = this.uScale;
  17534. newTexture.vScale = this.vScale;
  17535. newTexture.uAng = this.uAng;
  17536. newTexture.vAng = this.vAng;
  17537. newTexture.wAng = this.wAng;
  17538. return newTexture;
  17539. };
  17540. Texture.prototype.serialize = function () {
  17541. if (!this.name) {
  17542. return null;
  17543. }
  17544. var serializationObject = _super.prototype.serialize.call(this);
  17545. serializationObject.uOffset = this.uOffset;
  17546. serializationObject.vOffset = this.vOffset;
  17547. serializationObject.uScale = this.uScale;
  17548. serializationObject.vScale = this.vScale;
  17549. serializationObject.uAng = this.uAng;
  17550. serializationObject.vAng = this.vAng;
  17551. serializationObject.wAng = this.wAng;
  17552. return serializationObject;
  17553. };
  17554. // Statics
  17555. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17556. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17557. if (onLoad === void 0) { onLoad = null; }
  17558. if (onError === void 0) { onError = null; }
  17559. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17560. };
  17561. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17562. if (parsedTexture.isCube) {
  17563. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17564. }
  17565. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17566. return null;
  17567. }
  17568. var texture;
  17569. if (parsedTexture.mirrorPlane) {
  17570. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17571. texture._waitingRenderList = parsedTexture.renderList;
  17572. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17573. }
  17574. else if (parsedTexture.isRenderTarget) {
  17575. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17576. texture._waitingRenderList = parsedTexture.renderList;
  17577. }
  17578. else {
  17579. if (parsedTexture.base64String) {
  17580. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17581. }
  17582. else {
  17583. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17584. }
  17585. }
  17586. texture.name = parsedTexture.name;
  17587. texture.hasAlpha = parsedTexture.hasAlpha;
  17588. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17589. texture.level = parsedTexture.level;
  17590. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17591. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17592. texture.uOffset = parsedTexture.uOffset;
  17593. texture.vOffset = parsedTexture.vOffset;
  17594. texture.uScale = parsedTexture.uScale;
  17595. texture.vScale = parsedTexture.vScale;
  17596. texture.uAng = parsedTexture.uAng;
  17597. texture.vAng = parsedTexture.vAng;
  17598. texture.wAng = parsedTexture.wAng;
  17599. texture.wrapU = parsedTexture.wrapU;
  17600. texture.wrapV = parsedTexture.wrapV;
  17601. // Animations
  17602. if (parsedTexture.animations) {
  17603. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17604. var parsedAnimation = parsedTexture.animations[animationIndex];
  17605. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17606. }
  17607. }
  17608. return texture;
  17609. };
  17610. // Constants
  17611. Texture.NEAREST_SAMPLINGMODE = 1;
  17612. Texture.BILINEAR_SAMPLINGMODE = 2;
  17613. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17614. Texture.EXPLICIT_MODE = 0;
  17615. Texture.SPHERICAL_MODE = 1;
  17616. Texture.PLANAR_MODE = 2;
  17617. Texture.CUBIC_MODE = 3;
  17618. Texture.PROJECTION_MODE = 4;
  17619. Texture.SKYBOX_MODE = 5;
  17620. Texture.INVCUBIC_MODE = 6;
  17621. Texture.EQUIRECTANGULAR_MODE = 7;
  17622. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17623. Texture.CLAMP_ADDRESSMODE = 0;
  17624. Texture.WRAP_ADDRESSMODE = 1;
  17625. Texture.MIRROR_ADDRESSMODE = 2;
  17626. return Texture;
  17627. })(BABYLON.BaseTexture);
  17628. BABYLON.Texture = Texture;
  17629. })(BABYLON || (BABYLON = {}));
  17630. var BABYLON;
  17631. (function (BABYLON) {
  17632. var CubeTexture = (function (_super) {
  17633. __extends(CubeTexture, _super);
  17634. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17635. _super.call(this, scene);
  17636. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17637. this.name = rootUrl;
  17638. this.url = rootUrl;
  17639. this._noMipmap = noMipmap;
  17640. this.hasAlpha = false;
  17641. if (!rootUrl && !files) {
  17642. return;
  17643. }
  17644. this._texture = this._getFromCache(rootUrl, noMipmap);
  17645. if (!files) {
  17646. if (!extensions) {
  17647. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17648. }
  17649. files = [];
  17650. for (var index = 0; index < extensions.length; index++) {
  17651. files.push(rootUrl + extensions[index]);
  17652. }
  17653. this._extensions = extensions;
  17654. }
  17655. this._files = files;
  17656. if (!this._texture) {
  17657. if (!scene.useDelayedTextureLoading) {
  17658. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17659. }
  17660. else {
  17661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17662. }
  17663. }
  17664. this.isCube = true;
  17665. this._textureMatrix = BABYLON.Matrix.Identity();
  17666. }
  17667. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17668. return new CubeTexture("", scene, null, noMipmap, files);
  17669. };
  17670. CubeTexture.prototype.clone = function () {
  17671. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17672. // Base texture
  17673. newTexture.level = this.level;
  17674. newTexture.wrapU = this.wrapU;
  17675. newTexture.wrapV = this.wrapV;
  17676. newTexture.coordinatesIndex = this.coordinatesIndex;
  17677. newTexture.coordinatesMode = this.coordinatesMode;
  17678. return newTexture;
  17679. };
  17680. // Methods
  17681. CubeTexture.prototype.delayLoad = function () {
  17682. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17683. return;
  17684. }
  17685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17686. this._texture = this._getFromCache(this.url, this._noMipmap);
  17687. if (!this._texture) {
  17688. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17689. }
  17690. };
  17691. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17692. return this._textureMatrix;
  17693. };
  17694. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17695. var texture = null;
  17696. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17697. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17698. texture.name = parsedTexture.name;
  17699. texture.hasAlpha = parsedTexture.hasAlpha;
  17700. texture.level = parsedTexture.level;
  17701. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17702. }
  17703. return texture;
  17704. };
  17705. CubeTexture.prototype.serialize = function () {
  17706. if (!this.name) {
  17707. return null;
  17708. }
  17709. var serializationObject = {};
  17710. serializationObject.name = this.name;
  17711. serializationObject.hasAlpha = this.hasAlpha;
  17712. serializationObject.isCube = true;
  17713. serializationObject.level = this.level;
  17714. serializationObject.coordinatesMode = this.coordinatesMode;
  17715. return serializationObject;
  17716. };
  17717. return CubeTexture;
  17718. })(BABYLON.BaseTexture);
  17719. BABYLON.CubeTexture = CubeTexture;
  17720. })(BABYLON || (BABYLON = {}));
  17721. var BABYLON;
  17722. (function (BABYLON) {
  17723. var RenderTargetTexture = (function (_super) {
  17724. __extends(RenderTargetTexture, _super);
  17725. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17726. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17727. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17728. if (isCube === void 0) { isCube = false; }
  17729. _super.call(this, null, scene, !generateMipMaps);
  17730. this.isCube = isCube;
  17731. this.renderList = new Array();
  17732. this.renderParticles = true;
  17733. this.renderSprites = false;
  17734. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17735. this._currentRefreshId = -1;
  17736. this._refreshRate = 1;
  17737. this.name = name;
  17738. this.isRenderTarget = true;
  17739. this._size = size;
  17740. this._generateMipMaps = generateMipMaps;
  17741. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17742. if (isCube) {
  17743. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17744. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17745. this._textureMatrix = BABYLON.Matrix.Identity();
  17746. }
  17747. else {
  17748. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17749. }
  17750. // Rendering groups
  17751. this._renderingManager = new BABYLON.RenderingManager(scene);
  17752. }
  17753. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17754. get: function () {
  17755. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17761. get: function () {
  17762. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17768. get: function () {
  17769. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17775. this._currentRefreshId = -1;
  17776. };
  17777. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17778. get: function () {
  17779. return this._refreshRate;
  17780. },
  17781. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17782. set: function (value) {
  17783. this._refreshRate = value;
  17784. this.resetRefreshCounter();
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. RenderTargetTexture.prototype._shouldRender = function () {
  17790. if (this._currentRefreshId === -1) {
  17791. this._currentRefreshId = 1;
  17792. return true;
  17793. }
  17794. if (this.refreshRate === this._currentRefreshId) {
  17795. this._currentRefreshId = 1;
  17796. return true;
  17797. }
  17798. this._currentRefreshId++;
  17799. return false;
  17800. };
  17801. RenderTargetTexture.prototype.isReady = function () {
  17802. if (!this.getScene().renderTargetsEnabled) {
  17803. return false;
  17804. }
  17805. return _super.prototype.isReady.call(this);
  17806. };
  17807. RenderTargetTexture.prototype.getRenderSize = function () {
  17808. return this._size;
  17809. };
  17810. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17811. get: function () {
  17812. return true;
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. RenderTargetTexture.prototype.scale = function (ratio) {
  17818. var newSize = this._size * ratio;
  17819. this.resize(newSize, this._generateMipMaps);
  17820. };
  17821. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17822. if (this.isCube) {
  17823. return this._textureMatrix;
  17824. }
  17825. return _super.prototype.getReflectionTextureMatrix.call(this);
  17826. };
  17827. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17828. this.releaseInternalTexture();
  17829. if (this.isCube) {
  17830. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17831. }
  17832. else {
  17833. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17834. }
  17835. };
  17836. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17837. var scene = this.getScene();
  17838. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17839. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17840. }
  17841. if (this._waitingRenderList) {
  17842. this.renderList = [];
  17843. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17844. var id = this._waitingRenderList[index];
  17845. this.renderList.push(scene.getMeshByID(id));
  17846. }
  17847. delete this._waitingRenderList;
  17848. }
  17849. if (this.renderList && this.renderList.length === 0) {
  17850. return;
  17851. }
  17852. // Prepare renderingManager
  17853. this._renderingManager.reset();
  17854. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17855. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17856. var mesh = currentRenderList[meshIndex];
  17857. if (mesh) {
  17858. if (!mesh.isReady()) {
  17859. // Reset _currentRefreshId
  17860. this.resetRefreshCounter();
  17861. continue;
  17862. }
  17863. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17864. mesh._activate(scene.getRenderId());
  17865. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17866. var subMesh = mesh.subMeshes[subIndex];
  17867. scene._activeIndices += subMesh.indexCount;
  17868. this._renderingManager.dispatch(subMesh);
  17869. }
  17870. }
  17871. }
  17872. }
  17873. if (this.isCube) {
  17874. for (var face = 0; face < 6; face++) {
  17875. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17876. scene.incrementRenderId();
  17877. }
  17878. }
  17879. else {
  17880. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17881. }
  17882. if (this.onAfterUnbind) {
  17883. this.onAfterUnbind();
  17884. }
  17885. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17886. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17887. }
  17888. scene.resetCachedMaterial();
  17889. };
  17890. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17891. var scene = this.getScene();
  17892. var engine = scene.getEngine();
  17893. // Bind
  17894. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17895. if (this.isCube) {
  17896. engine.bindFramebuffer(this._texture, faceIndex);
  17897. }
  17898. else {
  17899. engine.bindFramebuffer(this._texture);
  17900. }
  17901. }
  17902. if (this.onBeforeRender) {
  17903. this.onBeforeRender(faceIndex);
  17904. }
  17905. // Clear
  17906. if (this.onClear) {
  17907. this.onClear(engine);
  17908. }
  17909. else {
  17910. engine.clear(scene.clearColor, true, true);
  17911. }
  17912. if (!this._doNotChangeAspectRatio) {
  17913. scene.updateTransformMatrix(true);
  17914. }
  17915. // Render
  17916. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17917. if (useCameraPostProcess) {
  17918. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17919. }
  17920. if (!this._doNotChangeAspectRatio) {
  17921. scene.updateTransformMatrix(true);
  17922. }
  17923. if (this.onAfterRender) {
  17924. this.onAfterRender(faceIndex);
  17925. }
  17926. // Dump ?
  17927. if (dumpForDebug) {
  17928. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17929. }
  17930. // Unbind
  17931. if (!this.isCube || faceIndex === 5) {
  17932. if (this.isCube) {
  17933. if (faceIndex === 5) {
  17934. engine.generateMipMapsForCubemap(this._texture);
  17935. }
  17936. }
  17937. engine.unBindFramebuffer(this._texture, this.isCube);
  17938. }
  17939. };
  17940. RenderTargetTexture.prototype.clone = function () {
  17941. var textureSize = this.getSize();
  17942. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17943. // Base texture
  17944. newTexture.hasAlpha = this.hasAlpha;
  17945. newTexture.level = this.level;
  17946. // RenderTarget Texture
  17947. newTexture.coordinatesMode = this.coordinatesMode;
  17948. newTexture.renderList = this.renderList.slice(0);
  17949. return newTexture;
  17950. };
  17951. RenderTargetTexture.prototype.serialize = function () {
  17952. if (!this.name) {
  17953. return null;
  17954. }
  17955. var serializationObject = _super.prototype.serialize.call(this);
  17956. serializationObject.renderTargetSize = this.getRenderSize();
  17957. serializationObject.renderList = [];
  17958. for (var index = 0; index < this.renderList.length; index++) {
  17959. serializationObject.renderList.push(this.renderList[index].id);
  17960. }
  17961. return serializationObject;
  17962. };
  17963. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17964. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17965. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17966. return RenderTargetTexture;
  17967. })(BABYLON.Texture);
  17968. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17969. })(BABYLON || (BABYLON = {}));
  17970. var BABYLON;
  17971. (function (BABYLON) {
  17972. var ProceduralTexture = (function (_super) {
  17973. __extends(ProceduralTexture, _super);
  17974. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  17975. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17976. if (isCube === void 0) { isCube = false; }
  17977. _super.call(this, null, scene, !generateMipMaps);
  17978. this.isCube = isCube;
  17979. this.isEnabled = true;
  17980. this._currentRefreshId = -1;
  17981. this._refreshRate = 1;
  17982. this._vertexDeclaration = [2];
  17983. this._vertexStrideSize = 2 * 4;
  17984. this._uniforms = new Array();
  17985. this._samplers = new Array();
  17986. this._textures = new Array();
  17987. this._floats = new Array();
  17988. this._floatsArrays = {};
  17989. this._colors3 = new Array();
  17990. this._colors4 = new Array();
  17991. this._vectors2 = new Array();
  17992. this._vectors3 = new Array();
  17993. this._matrices = new Array();
  17994. this._fallbackTextureUsed = false;
  17995. scene._proceduralTextures.push(this);
  17996. this.name = name;
  17997. this.isRenderTarget = true;
  17998. this._size = size;
  17999. this._generateMipMaps = generateMipMaps;
  18000. this.setFragment(fragment);
  18001. this._fallbackTexture = fallbackTexture;
  18002. if (isCube) {
  18003. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18004. this.setFloat("face", 0);
  18005. }
  18006. else {
  18007. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18008. }
  18009. // VBO
  18010. var vertices = [];
  18011. vertices.push(1, 1);
  18012. vertices.push(-1, 1);
  18013. vertices.push(-1, -1);
  18014. vertices.push(1, -1);
  18015. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18016. // Indices
  18017. var indices = [];
  18018. indices.push(0);
  18019. indices.push(1);
  18020. indices.push(2);
  18021. indices.push(0);
  18022. indices.push(2);
  18023. indices.push(3);
  18024. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18025. }
  18026. ProceduralTexture.prototype.reset = function () {
  18027. if (this._effect === undefined) {
  18028. return;
  18029. }
  18030. var engine = this.getScene().getEngine();
  18031. engine._releaseEffect(this._effect);
  18032. };
  18033. ProceduralTexture.prototype.isReady = function () {
  18034. var _this = this;
  18035. var engine = this.getScene().getEngine();
  18036. var shaders;
  18037. if (!this._fragment) {
  18038. return false;
  18039. }
  18040. if (this._fallbackTextureUsed) {
  18041. return true;
  18042. }
  18043. if (this._fragment.fragmentElement !== undefined) {
  18044. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18045. }
  18046. else {
  18047. shaders = { vertex: "procedural", fragment: this._fragment };
  18048. }
  18049. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18050. _this.releaseInternalTexture();
  18051. if (_this._fallbackTexture) {
  18052. _this._texture = _this._fallbackTexture._texture;
  18053. _this._texture.references++;
  18054. }
  18055. _this._fallbackTextureUsed = true;
  18056. });
  18057. return this._effect.isReady();
  18058. };
  18059. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18060. this._currentRefreshId = -1;
  18061. };
  18062. ProceduralTexture.prototype.setFragment = function (fragment) {
  18063. this._fragment = fragment;
  18064. };
  18065. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18066. get: function () {
  18067. return this._refreshRate;
  18068. },
  18069. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18070. set: function (value) {
  18071. this._refreshRate = value;
  18072. this.resetRefreshCounter();
  18073. },
  18074. enumerable: true,
  18075. configurable: true
  18076. });
  18077. ProceduralTexture.prototype._shouldRender = function () {
  18078. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18079. return false;
  18080. }
  18081. if (this._fallbackTextureUsed) {
  18082. return false;
  18083. }
  18084. if (this._currentRefreshId === -1) {
  18085. this._currentRefreshId = 1;
  18086. return true;
  18087. }
  18088. if (this.refreshRate === this._currentRefreshId) {
  18089. this._currentRefreshId = 1;
  18090. return true;
  18091. }
  18092. this._currentRefreshId++;
  18093. return false;
  18094. };
  18095. ProceduralTexture.prototype.getRenderSize = function () {
  18096. return this._size;
  18097. };
  18098. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18099. if (this._fallbackTextureUsed) {
  18100. return;
  18101. }
  18102. this.releaseInternalTexture();
  18103. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18104. };
  18105. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18106. if (this._uniforms.indexOf(uniformName) === -1) {
  18107. this._uniforms.push(uniformName);
  18108. }
  18109. };
  18110. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18111. if (this._samplers.indexOf(name) === -1) {
  18112. this._samplers.push(name);
  18113. }
  18114. this._textures[name] = texture;
  18115. return this;
  18116. };
  18117. ProceduralTexture.prototype.setFloat = function (name, value) {
  18118. this._checkUniform(name);
  18119. this._floats[name] = value;
  18120. return this;
  18121. };
  18122. ProceduralTexture.prototype.setFloats = function (name, value) {
  18123. this._checkUniform(name);
  18124. this._floatsArrays[name] = value;
  18125. return this;
  18126. };
  18127. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18128. this._checkUniform(name);
  18129. this._colors3[name] = value;
  18130. return this;
  18131. };
  18132. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18133. this._checkUniform(name);
  18134. this._colors4[name] = value;
  18135. return this;
  18136. };
  18137. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18138. this._checkUniform(name);
  18139. this._vectors2[name] = value;
  18140. return this;
  18141. };
  18142. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18143. this._checkUniform(name);
  18144. this._vectors3[name] = value;
  18145. return this;
  18146. };
  18147. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18148. this._checkUniform(name);
  18149. this._matrices[name] = value;
  18150. return this;
  18151. };
  18152. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18153. var scene = this.getScene();
  18154. var engine = scene.getEngine();
  18155. // Render
  18156. engine.enableEffect(this._effect);
  18157. engine.setState(false);
  18158. // Texture
  18159. for (var name in this._textures) {
  18160. this._effect.setTexture(name, this._textures[name]);
  18161. }
  18162. // Float
  18163. for (name in this._floats) {
  18164. this._effect.setFloat(name, this._floats[name]);
  18165. }
  18166. // Floats
  18167. for (name in this._floatsArrays) {
  18168. this._effect.setArray(name, this._floatsArrays[name]);
  18169. }
  18170. // Color3
  18171. for (name in this._colors3) {
  18172. this._effect.setColor3(name, this._colors3[name]);
  18173. }
  18174. // Color4
  18175. for (name in this._colors4) {
  18176. var color = this._colors4[name];
  18177. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18178. }
  18179. // Vector2
  18180. for (name in this._vectors2) {
  18181. this._effect.setVector2(name, this._vectors2[name]);
  18182. }
  18183. // Vector3
  18184. for (name in this._vectors3) {
  18185. this._effect.setVector3(name, this._vectors3[name]);
  18186. }
  18187. // Matrix
  18188. for (name in this._matrices) {
  18189. this._effect.setMatrix(name, this._matrices[name]);
  18190. }
  18191. // VBOs
  18192. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18193. if (this.isCube) {
  18194. for (var face = 0; face < 6; face++) {
  18195. engine.bindFramebuffer(this._texture, face);
  18196. this._effect.setFloat("face", face);
  18197. // Clear
  18198. engine.clear(scene.clearColor, true, true);
  18199. // Draw order
  18200. engine.draw(true, 0, 6);
  18201. // Mipmaps
  18202. if (face === 5) {
  18203. engine.generateMipMapsForCubemap(this._texture);
  18204. }
  18205. }
  18206. }
  18207. else {
  18208. engine.bindFramebuffer(this._texture);
  18209. // Clear
  18210. engine.clear(scene.clearColor, true, true);
  18211. // Draw order
  18212. engine.draw(true, 0, 6);
  18213. }
  18214. // Unbind
  18215. engine.unBindFramebuffer(this._texture, this.isCube);
  18216. if (this.onGenerated) {
  18217. this.onGenerated();
  18218. }
  18219. };
  18220. ProceduralTexture.prototype.clone = function () {
  18221. var textureSize = this.getSize();
  18222. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18223. // Base texture
  18224. newTexture.hasAlpha = this.hasAlpha;
  18225. newTexture.level = this.level;
  18226. // RenderTarget Texture
  18227. newTexture.coordinatesMode = this.coordinatesMode;
  18228. return newTexture;
  18229. };
  18230. ProceduralTexture.prototype.dispose = function () {
  18231. var index = this.getScene()._proceduralTextures.indexOf(this);
  18232. if (index >= 0) {
  18233. this.getScene()._proceduralTextures.splice(index, 1);
  18234. }
  18235. _super.prototype.dispose.call(this);
  18236. };
  18237. return ProceduralTexture;
  18238. })(BABYLON.Texture);
  18239. BABYLON.ProceduralTexture = ProceduralTexture;
  18240. })(BABYLON || (BABYLON = {}));
  18241. var BABYLON;
  18242. (function (BABYLON) {
  18243. var MirrorTexture = (function (_super) {
  18244. __extends(MirrorTexture, _super);
  18245. function MirrorTexture(name, size, scene, generateMipMaps) {
  18246. var _this = this;
  18247. _super.call(this, name, size, scene, generateMipMaps, true);
  18248. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18249. this._transformMatrix = BABYLON.Matrix.Zero();
  18250. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18251. this.onBeforeRender = function () {
  18252. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18253. _this._savedViewMatrix = scene.getViewMatrix();
  18254. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18255. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18256. scene.clipPlane = _this.mirrorPlane;
  18257. scene.getEngine().cullBackFaces = false;
  18258. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18259. };
  18260. this.onAfterRender = function () {
  18261. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18262. scene.getEngine().cullBackFaces = true;
  18263. scene._mirroredCameraPosition = null;
  18264. delete scene.clipPlane;
  18265. };
  18266. }
  18267. MirrorTexture.prototype.clone = function () {
  18268. var textureSize = this.getSize();
  18269. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18270. // Base texture
  18271. newTexture.hasAlpha = this.hasAlpha;
  18272. newTexture.level = this.level;
  18273. // Mirror Texture
  18274. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18275. newTexture.renderList = this.renderList.slice(0);
  18276. return newTexture;
  18277. };
  18278. MirrorTexture.prototype.serialize = function () {
  18279. if (!this.name) {
  18280. return null;
  18281. }
  18282. var serializationObject = _super.prototype.serialize.call(this);
  18283. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18284. return serializationObject;
  18285. };
  18286. return MirrorTexture;
  18287. })(BABYLON.RenderTargetTexture);
  18288. BABYLON.MirrorTexture = MirrorTexture;
  18289. })(BABYLON || (BABYLON = {}));
  18290. var BABYLON;
  18291. (function (BABYLON) {
  18292. /**
  18293. * Creates a refraction texture used by refraction channel of the standard material.
  18294. * @param name the texture name
  18295. * @param size size of the underlying texture
  18296. * @param scene root scene
  18297. */
  18298. var RefractionTexture = (function (_super) {
  18299. __extends(RefractionTexture, _super);
  18300. function RefractionTexture(name, size, scene, generateMipMaps) {
  18301. var _this = this;
  18302. _super.call(this, name, size, scene, generateMipMaps, true);
  18303. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18304. this.depth = 2.0;
  18305. this.onBeforeRender = function () {
  18306. scene.clipPlane = _this.refractionPlane;
  18307. };
  18308. this.onAfterRender = function () {
  18309. delete scene.clipPlane;
  18310. };
  18311. }
  18312. RefractionTexture.prototype.clone = function () {
  18313. var textureSize = this.getSize();
  18314. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18315. // Base texture
  18316. newTexture.hasAlpha = this.hasAlpha;
  18317. newTexture.level = this.level;
  18318. // Refraction Texture
  18319. newTexture.refractionPlane = this.refractionPlane.clone();
  18320. newTexture.renderList = this.renderList.slice(0);
  18321. newTexture.depth = this.depth;
  18322. return newTexture;
  18323. };
  18324. RefractionTexture.prototype.serialize = function () {
  18325. if (!this.name) {
  18326. return null;
  18327. }
  18328. var serializationObject = _super.prototype.serialize.call(this);
  18329. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18330. serializationObject.depth = this.depth;
  18331. return serializationObject;
  18332. };
  18333. return RefractionTexture;
  18334. })(BABYLON.RenderTargetTexture);
  18335. BABYLON.RefractionTexture = RefractionTexture;
  18336. })(BABYLON || (BABYLON = {}));
  18337. var BABYLON;
  18338. (function (BABYLON) {
  18339. var DynamicTexture = (function (_super) {
  18340. __extends(DynamicTexture, _super);
  18341. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18343. _super.call(this, null, scene, !generateMipMaps);
  18344. this.name = name;
  18345. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18346. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18347. this._generateMipMaps = generateMipMaps;
  18348. if (options.getContext) {
  18349. this._canvas = options;
  18350. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18351. }
  18352. else {
  18353. this._canvas = document.createElement("canvas");
  18354. if (options.width) {
  18355. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18356. }
  18357. else {
  18358. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18359. }
  18360. }
  18361. var textureSize = this.getSize();
  18362. this._canvas.width = textureSize.width;
  18363. this._canvas.height = textureSize.height;
  18364. this._context = this._canvas.getContext("2d");
  18365. }
  18366. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18367. get: function () {
  18368. return true;
  18369. },
  18370. enumerable: true,
  18371. configurable: true
  18372. });
  18373. DynamicTexture.prototype.scale = function (ratio) {
  18374. var textureSize = this.getSize();
  18375. textureSize.width *= ratio;
  18376. textureSize.height *= ratio;
  18377. this._canvas.width = textureSize.width;
  18378. this._canvas.height = textureSize.height;
  18379. this.releaseInternalTexture();
  18380. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18381. };
  18382. DynamicTexture.prototype.getContext = function () {
  18383. return this._context;
  18384. };
  18385. DynamicTexture.prototype.clear = function () {
  18386. var size = this.getSize();
  18387. this._context.fillRect(0, 0, size.width, size.height);
  18388. };
  18389. DynamicTexture.prototype.update = function (invertY) {
  18390. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18391. };
  18392. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18393. if (update === void 0) { update = true; }
  18394. var size = this.getSize();
  18395. if (clearColor) {
  18396. this._context.fillStyle = clearColor;
  18397. this._context.fillRect(0, 0, size.width, size.height);
  18398. }
  18399. this._context.font = font;
  18400. if (x === null) {
  18401. var textSize = this._context.measureText(text);
  18402. x = (size.width - textSize.width) / 2;
  18403. }
  18404. this._context.fillStyle = color;
  18405. this._context.fillText(text, x, y);
  18406. if (update) {
  18407. this.update(invertY);
  18408. }
  18409. };
  18410. DynamicTexture.prototype.clone = function () {
  18411. var textureSize = this.getSize();
  18412. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18413. // Base texture
  18414. newTexture.hasAlpha = this.hasAlpha;
  18415. newTexture.level = this.level;
  18416. // Dynamic Texture
  18417. newTexture.wrapU = this.wrapU;
  18418. newTexture.wrapV = this.wrapV;
  18419. return newTexture;
  18420. };
  18421. return DynamicTexture;
  18422. })(BABYLON.Texture);
  18423. BABYLON.DynamicTexture = DynamicTexture;
  18424. })(BABYLON || (BABYLON = {}));
  18425. var BABYLON;
  18426. (function (BABYLON) {
  18427. var VideoTexture = (function (_super) {
  18428. __extends(VideoTexture, _super);
  18429. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18430. var _this = this;
  18431. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18432. if (invertY === void 0) { invertY = false; }
  18433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18434. _super.call(this, null, scene, !generateMipMaps, invertY);
  18435. this._autoLaunch = true;
  18436. this.name = name;
  18437. this.video = document.createElement("video");
  18438. this.video.autoplay = false;
  18439. this.video.loop = true;
  18440. this.video.addEventListener("canplaythrough", function () {
  18441. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18442. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18443. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18444. }
  18445. else {
  18446. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18447. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18448. generateMipMaps = false;
  18449. }
  18450. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18451. _this._texture.isReady = true;
  18452. });
  18453. urls.forEach(function (url) {
  18454. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18455. var source = document.createElement("source");
  18456. source.src = url;
  18457. _this.video.appendChild(source);
  18458. });
  18459. this._lastUpdate = BABYLON.Tools.Now;
  18460. }
  18461. VideoTexture.prototype.update = function () {
  18462. if (this._autoLaunch) {
  18463. this._autoLaunch = false;
  18464. this.video.play();
  18465. }
  18466. var now = BABYLON.Tools.Now;
  18467. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18468. return false;
  18469. }
  18470. this._lastUpdate = now;
  18471. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18472. return true;
  18473. };
  18474. return VideoTexture;
  18475. })(BABYLON.Texture);
  18476. BABYLON.VideoTexture = VideoTexture;
  18477. })(BABYLON || (BABYLON = {}));
  18478. var BABYLON;
  18479. (function (BABYLON) {
  18480. var CustomProceduralTexture = (function (_super) {
  18481. __extends(CustomProceduralTexture, _super);
  18482. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18483. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18484. this._animate = true;
  18485. this._time = 0;
  18486. this._texturePath = texturePath;
  18487. //Try to load json
  18488. this.loadJson(texturePath);
  18489. this.refreshRate = 1;
  18490. }
  18491. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18492. var _this = this;
  18493. var that = this;
  18494. function noConfigFile() {
  18495. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18496. try {
  18497. that.setFragment(that._texturePath);
  18498. }
  18499. catch (ex) {
  18500. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18501. }
  18502. }
  18503. var configFileUrl = jsonUrl + "/config.json";
  18504. var xhr = new XMLHttpRequest();
  18505. xhr.open("GET", configFileUrl, true);
  18506. xhr.addEventListener("load", function () {
  18507. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18508. try {
  18509. _this._config = JSON.parse(xhr.response);
  18510. _this.updateShaderUniforms();
  18511. _this.updateTextures();
  18512. _this.setFragment(_this._texturePath + "/custom");
  18513. _this._animate = _this._config.animate;
  18514. _this.refreshRate = _this._config.refreshrate;
  18515. }
  18516. catch (ex) {
  18517. noConfigFile();
  18518. }
  18519. }
  18520. else {
  18521. noConfigFile();
  18522. }
  18523. }, false);
  18524. xhr.addEventListener("error", function () {
  18525. noConfigFile();
  18526. }, false);
  18527. try {
  18528. xhr.send();
  18529. }
  18530. catch (ex) {
  18531. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18532. }
  18533. };
  18534. CustomProceduralTexture.prototype.isReady = function () {
  18535. if (!_super.prototype.isReady.call(this)) {
  18536. return false;
  18537. }
  18538. for (var name in this._textures) {
  18539. var texture = this._textures[name];
  18540. if (!texture.isReady()) {
  18541. return false;
  18542. }
  18543. }
  18544. return true;
  18545. };
  18546. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18547. if (this._animate) {
  18548. this._time += this.getScene().getAnimationRatio() * 0.03;
  18549. this.updateShaderUniforms();
  18550. }
  18551. _super.prototype.render.call(this, useCameraPostProcess);
  18552. };
  18553. CustomProceduralTexture.prototype.updateTextures = function () {
  18554. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18555. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18556. }
  18557. };
  18558. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18559. if (this._config) {
  18560. for (var j = 0; j < this._config.uniforms.length; j++) {
  18561. var uniform = this._config.uniforms[j];
  18562. switch (uniform.type) {
  18563. case "float":
  18564. this.setFloat(uniform.name, uniform.value);
  18565. break;
  18566. case "color3":
  18567. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18568. break;
  18569. case "color4":
  18570. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18571. break;
  18572. case "vector2":
  18573. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18574. break;
  18575. case "vector3":
  18576. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18577. break;
  18578. }
  18579. }
  18580. }
  18581. this.setFloat("time", this._time);
  18582. };
  18583. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18584. get: function () {
  18585. return this._animate;
  18586. },
  18587. set: function (value) {
  18588. this._animate = value;
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. return CustomProceduralTexture;
  18594. })(BABYLON.ProceduralTexture);
  18595. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18596. })(BABYLON || (BABYLON = {}));
  18597. var BABYLON;
  18598. (function (BABYLON) {
  18599. var EffectFallbacks = (function () {
  18600. function EffectFallbacks() {
  18601. this._defines = {};
  18602. this._currentRank = 32;
  18603. this._maxRank = -1;
  18604. }
  18605. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18606. if (!this._defines[rank]) {
  18607. if (rank < this._currentRank) {
  18608. this._currentRank = rank;
  18609. }
  18610. if (rank > this._maxRank) {
  18611. this._maxRank = rank;
  18612. }
  18613. this._defines[rank] = new Array();
  18614. }
  18615. this._defines[rank].push(define);
  18616. };
  18617. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18618. this._meshRank = rank;
  18619. this._mesh = mesh;
  18620. if (rank > this._maxRank) {
  18621. this._maxRank = rank;
  18622. }
  18623. };
  18624. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18625. get: function () {
  18626. return this._currentRank <= this._maxRank;
  18627. },
  18628. enumerable: true,
  18629. configurable: true
  18630. });
  18631. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18632. var currentFallbacks = this._defines[this._currentRank];
  18633. for (var index = 0; index < currentFallbacks.length; index++) {
  18634. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18635. }
  18636. if (this._mesh && this._currentRank === this._meshRank) {
  18637. this._mesh.computeBonesUsingShaders = false;
  18638. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18639. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18640. }
  18641. this._currentRank++;
  18642. return currentDefines;
  18643. };
  18644. return EffectFallbacks;
  18645. })();
  18646. BABYLON.EffectFallbacks = EffectFallbacks;
  18647. var Effect = (function () {
  18648. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18649. var _this = this;
  18650. this._isReady = false;
  18651. this._compilationError = "";
  18652. this._valueCache = [];
  18653. this._engine = engine;
  18654. this.name = baseName;
  18655. this.defines = defines;
  18656. this._uniformsNames = uniformsNames.concat(samplers);
  18657. this._samplers = samplers;
  18658. this._attributesNames = attributesNames;
  18659. this.onError = onError;
  18660. this.onCompiled = onCompiled;
  18661. var vertexSource;
  18662. var fragmentSource;
  18663. if (baseName.vertexElement) {
  18664. vertexSource = document.getElementById(baseName.vertexElement);
  18665. if (!vertexSource) {
  18666. vertexSource = baseName.vertexElement;
  18667. }
  18668. }
  18669. else {
  18670. vertexSource = baseName.vertex || baseName;
  18671. }
  18672. if (baseName.fragmentElement) {
  18673. fragmentSource = document.getElementById(baseName.fragmentElement);
  18674. if (!fragmentSource) {
  18675. fragmentSource = baseName.fragmentElement;
  18676. }
  18677. }
  18678. else {
  18679. fragmentSource = baseName.fragment || baseName;
  18680. }
  18681. this._loadVertexShader(vertexSource, function (vertexCode) {
  18682. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18683. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18684. });
  18685. });
  18686. }
  18687. // Properties
  18688. Effect.prototype.isReady = function () {
  18689. return this._isReady;
  18690. };
  18691. Effect.prototype.getProgram = function () {
  18692. return this._program;
  18693. };
  18694. Effect.prototype.getAttributesNames = function () {
  18695. return this._attributesNames;
  18696. };
  18697. Effect.prototype.getAttributeLocation = function (index) {
  18698. return this._attributes[index];
  18699. };
  18700. Effect.prototype.getAttributeLocationByName = function (name) {
  18701. var index = this._attributesNames.indexOf(name);
  18702. return this._attributes[index];
  18703. };
  18704. Effect.prototype.getAttributesCount = function () {
  18705. return this._attributes.length;
  18706. };
  18707. Effect.prototype.getUniformIndex = function (uniformName) {
  18708. return this._uniformsNames.indexOf(uniformName);
  18709. };
  18710. Effect.prototype.getUniform = function (uniformName) {
  18711. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18712. };
  18713. Effect.prototype.getSamplers = function () {
  18714. return this._samplers;
  18715. };
  18716. Effect.prototype.getCompilationError = function () {
  18717. return this._compilationError;
  18718. };
  18719. // Methods
  18720. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18721. // DOM element ?
  18722. if (vertex instanceof HTMLElement) {
  18723. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18724. callback(vertexCode);
  18725. return;
  18726. }
  18727. // Is in local store ?
  18728. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18729. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18730. return;
  18731. }
  18732. var vertexShaderUrl;
  18733. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18734. vertexShaderUrl = vertex;
  18735. }
  18736. else {
  18737. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18738. }
  18739. // Vertex shader
  18740. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18741. };
  18742. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18743. // DOM element ?
  18744. if (fragment instanceof HTMLElement) {
  18745. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18746. callback(fragmentCode);
  18747. return;
  18748. }
  18749. // Is in local store ?
  18750. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18751. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18752. return;
  18753. }
  18754. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18755. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18756. return;
  18757. }
  18758. var fragmentShaderUrl;
  18759. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18760. fragmentShaderUrl = fragment;
  18761. }
  18762. else {
  18763. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18764. }
  18765. // Fragment shader
  18766. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18767. };
  18768. Effect.prototype._dumpShadersName = function () {
  18769. if (this.name.vertexElement) {
  18770. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18771. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18772. }
  18773. else if (this.name.vertex) {
  18774. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18775. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18776. }
  18777. else {
  18778. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18779. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18780. }
  18781. };
  18782. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18783. try {
  18784. var engine = this._engine;
  18785. if (!engine.getCaps().highPrecisionShaderSupported) {
  18786. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18787. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18788. }
  18789. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18790. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18791. this._attributes = engine.getAttributes(this._program, attributesNames);
  18792. for (var index = 0; index < this._samplers.length; index++) {
  18793. var sampler = this.getUniform(this._samplers[index]);
  18794. if (sampler == null) {
  18795. this._samplers.splice(index, 1);
  18796. index--;
  18797. }
  18798. }
  18799. engine.bindSamplers(this);
  18800. this._isReady = true;
  18801. if (this.onCompiled) {
  18802. this.onCompiled(this);
  18803. }
  18804. }
  18805. catch (e) {
  18806. // Is it a problem with precision?
  18807. if (e.message.indexOf("highp") !== -1) {
  18808. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18809. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18810. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18811. return;
  18812. }
  18813. // Let's go through fallbacks then
  18814. if (fallbacks && fallbacks.isMoreFallbacks) {
  18815. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18816. this._dumpShadersName();
  18817. defines = fallbacks.reduce(defines);
  18818. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18819. }
  18820. else {
  18821. BABYLON.Tools.Error("Unable to compile effect: ");
  18822. this._dumpShadersName();
  18823. BABYLON.Tools.Error("Defines: " + defines);
  18824. BABYLON.Tools.Error("Error: " + e.message);
  18825. this._compilationError = e.message;
  18826. if (this.onError) {
  18827. this.onError(this, this._compilationError);
  18828. }
  18829. }
  18830. }
  18831. };
  18832. Object.defineProperty(Effect.prototype, "isSupported", {
  18833. get: function () {
  18834. return this._compilationError === "";
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Effect.prototype._bindTexture = function (channel, texture) {
  18840. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18841. };
  18842. Effect.prototype.setTexture = function (channel, texture) {
  18843. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18844. };
  18845. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18846. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18847. };
  18848. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18849. if (!this._valueCache[uniformName]) {
  18850. this._valueCache[uniformName] = new BABYLON.Matrix();
  18851. }
  18852. for (var index = 0; index < 16; index++) {
  18853. this._valueCache[uniformName].m[index] = matrix.m[index];
  18854. }
  18855. };
  18856. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18857. if (!this._valueCache[uniformName]) {
  18858. this._valueCache[uniformName] = [x, y];
  18859. return;
  18860. }
  18861. this._valueCache[uniformName][0] = x;
  18862. this._valueCache[uniformName][1] = y;
  18863. };
  18864. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18865. if (!this._valueCache[uniformName]) {
  18866. this._valueCache[uniformName] = [x, y, z];
  18867. return;
  18868. }
  18869. this._valueCache[uniformName][0] = x;
  18870. this._valueCache[uniformName][1] = y;
  18871. this._valueCache[uniformName][2] = z;
  18872. };
  18873. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18874. if (!this._valueCache[uniformName]) {
  18875. this._valueCache[uniformName] = [x, y, z, w];
  18876. return;
  18877. }
  18878. this._valueCache[uniformName][0] = x;
  18879. this._valueCache[uniformName][1] = y;
  18880. this._valueCache[uniformName][2] = z;
  18881. this._valueCache[uniformName][3] = w;
  18882. };
  18883. Effect.prototype.setArray = function (uniformName, array) {
  18884. this._engine.setArray(this.getUniform(uniformName), array);
  18885. return this;
  18886. };
  18887. Effect.prototype.setArray2 = function (uniformName, array) {
  18888. this._engine.setArray2(this.getUniform(uniformName), array);
  18889. return this;
  18890. };
  18891. Effect.prototype.setArray3 = function (uniformName, array) {
  18892. this._engine.setArray3(this.getUniform(uniformName), array);
  18893. return this;
  18894. };
  18895. Effect.prototype.setArray4 = function (uniformName, array) {
  18896. this._engine.setArray4(this.getUniform(uniformName), array);
  18897. return this;
  18898. };
  18899. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18900. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18901. return this;
  18902. };
  18903. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18904. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18905. // return this;
  18906. // this._cacheMatrix(uniformName, matrix);
  18907. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18908. return this;
  18909. };
  18910. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18911. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18912. return this;
  18913. };
  18914. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18915. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18916. return this;
  18917. };
  18918. Effect.prototype.setFloat = function (uniformName, value) {
  18919. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18920. return this;
  18921. this._valueCache[uniformName] = value;
  18922. this._engine.setFloat(this.getUniform(uniformName), value);
  18923. return this;
  18924. };
  18925. Effect.prototype.setBool = function (uniformName, bool) {
  18926. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18927. return this;
  18928. this._valueCache[uniformName] = bool;
  18929. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18930. return this;
  18931. };
  18932. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18933. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18934. return this;
  18935. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18936. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18937. return this;
  18938. };
  18939. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18940. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18941. return this;
  18942. this._cacheFloat2(uniformName, x, y);
  18943. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18944. return this;
  18945. };
  18946. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18947. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18948. return this;
  18949. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18950. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18951. return this;
  18952. };
  18953. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18954. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18955. return this;
  18956. this._cacheFloat3(uniformName, x, y, z);
  18957. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18958. return this;
  18959. };
  18960. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18961. 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)
  18962. return this;
  18963. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18964. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18965. return this;
  18966. };
  18967. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18968. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18969. return this;
  18970. this._cacheFloat4(uniformName, x, y, z, w);
  18971. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18972. return this;
  18973. };
  18974. Effect.prototype.setColor3 = function (uniformName, color3) {
  18975. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18976. return this;
  18977. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18978. this._engine.setColor3(this.getUniform(uniformName), color3);
  18979. return this;
  18980. };
  18981. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18982. 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)
  18983. return this;
  18984. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18985. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18986. return this;
  18987. };
  18988. // Statics
  18989. Effect.ShadersStore = {};
  18990. return Effect;
  18991. })();
  18992. BABYLON.Effect = Effect;
  18993. })(BABYLON || (BABYLON = {}));
  18994. var BABYLON;
  18995. (function (BABYLON) {
  18996. var MaterialDefines = (function () {
  18997. function MaterialDefines() {
  18998. }
  18999. MaterialDefines.prototype.isEqual = function (other) {
  19000. for (var index = 0; index < this._keys.length; index++) {
  19001. var prop = this._keys[index];
  19002. if (this[prop] !== other[prop]) {
  19003. return false;
  19004. }
  19005. }
  19006. return true;
  19007. };
  19008. MaterialDefines.prototype.cloneTo = function (other) {
  19009. for (var index = 0; index < this._keys.length; index++) {
  19010. var prop = this._keys[index];
  19011. other[prop] = this[prop];
  19012. }
  19013. };
  19014. MaterialDefines.prototype.reset = function () {
  19015. for (var index = 0; index < this._keys.length; index++) {
  19016. var prop = this._keys[index];
  19017. if (typeof (this[prop]) === "number") {
  19018. this[prop] = 0;
  19019. }
  19020. else {
  19021. this[prop] = false;
  19022. }
  19023. }
  19024. };
  19025. MaterialDefines.prototype.toString = function () {
  19026. var result = "";
  19027. for (var index = 0; index < this._keys.length; index++) {
  19028. var prop = this._keys[index];
  19029. if (typeof (this[prop]) === "number") {
  19030. result += "#define " + prop + " " + this[prop] + "\n";
  19031. }
  19032. else if (this[prop]) {
  19033. result += "#define " + prop + "\n";
  19034. }
  19035. }
  19036. return result;
  19037. };
  19038. return MaterialDefines;
  19039. })();
  19040. BABYLON.MaterialDefines = MaterialDefines;
  19041. var Material = (function () {
  19042. function Material(name, scene, doNotAdd) {
  19043. this.name = name;
  19044. this.checkReadyOnEveryCall = false;
  19045. this.checkReadyOnlyOnce = false;
  19046. this.state = "";
  19047. this.alpha = 1.0;
  19048. this.backFaceCulling = true;
  19049. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19050. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19051. this.disableDepthWrite = false;
  19052. this.fogEnabled = true;
  19053. this._wasPreviouslyReady = false;
  19054. this._fillMode = Material.TriangleFillMode;
  19055. this.pointSize = 1.0;
  19056. this.zOffset = 0;
  19057. this.id = name;
  19058. this._scene = scene;
  19059. if (!doNotAdd) {
  19060. scene.materials.push(this);
  19061. }
  19062. }
  19063. Object.defineProperty(Material, "TriangleFillMode", {
  19064. get: function () {
  19065. return Material._TriangleFillMode;
  19066. },
  19067. enumerable: true,
  19068. configurable: true
  19069. });
  19070. Object.defineProperty(Material, "WireFrameFillMode", {
  19071. get: function () {
  19072. return Material._WireFrameFillMode;
  19073. },
  19074. enumerable: true,
  19075. configurable: true
  19076. });
  19077. Object.defineProperty(Material, "PointFillMode", {
  19078. get: function () {
  19079. return Material._PointFillMode;
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19085. get: function () {
  19086. return Material._ClockWiseSideOrientation;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19092. get: function () {
  19093. return Material._CounterClockWiseSideOrientation;
  19094. },
  19095. enumerable: true,
  19096. configurable: true
  19097. });
  19098. Object.defineProperty(Material.prototype, "wireframe", {
  19099. get: function () {
  19100. return this._fillMode === Material.WireFrameFillMode;
  19101. },
  19102. set: function (value) {
  19103. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(Material.prototype, "pointsCloud", {
  19109. get: function () {
  19110. return this._fillMode === Material.PointFillMode;
  19111. },
  19112. set: function (value) {
  19113. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19114. },
  19115. enumerable: true,
  19116. configurable: true
  19117. });
  19118. Object.defineProperty(Material.prototype, "fillMode", {
  19119. get: function () {
  19120. return this._fillMode;
  19121. },
  19122. set: function (value) {
  19123. this._fillMode = value;
  19124. },
  19125. enumerable: true,
  19126. configurable: true
  19127. });
  19128. Object.defineProperty(Material.prototype, "isFrozen", {
  19129. get: function () {
  19130. return this.checkReadyOnlyOnce;
  19131. },
  19132. enumerable: true,
  19133. configurable: true
  19134. });
  19135. Material.prototype.freeze = function () {
  19136. this.checkReadyOnlyOnce = true;
  19137. };
  19138. Material.prototype.unfreeze = function () {
  19139. this.checkReadyOnlyOnce = false;
  19140. };
  19141. Material.prototype.isReady = function (mesh, useInstances) {
  19142. return true;
  19143. };
  19144. Material.prototype.getEffect = function () {
  19145. return this._effect;
  19146. };
  19147. Material.prototype.getScene = function () {
  19148. return this._scene;
  19149. };
  19150. Material.prototype.needAlphaBlending = function () {
  19151. return (this.alpha < 1.0);
  19152. };
  19153. Material.prototype.needAlphaTesting = function () {
  19154. return false;
  19155. };
  19156. Material.prototype.getAlphaTestTexture = function () {
  19157. return null;
  19158. };
  19159. Material.prototype.trackCreation = function (onCompiled, onError) {
  19160. };
  19161. Material.prototype.markDirty = function () {
  19162. this._wasPreviouslyReady = false;
  19163. };
  19164. Material.prototype._preBind = function () {
  19165. var engine = this._scene.getEngine();
  19166. engine.enableEffect(this._effect);
  19167. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19168. };
  19169. Material.prototype.bind = function (world, mesh) {
  19170. this._scene._cachedMaterial = this;
  19171. if (this.onBind) {
  19172. this.onBind(this, mesh);
  19173. }
  19174. if (this.disableDepthWrite) {
  19175. var engine = this._scene.getEngine();
  19176. this._cachedDepthWriteState = engine.getDepthWrite();
  19177. engine.setDepthWrite(false);
  19178. }
  19179. };
  19180. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19181. };
  19182. Material.prototype.unbind = function () {
  19183. if (this.disableDepthWrite) {
  19184. var engine = this._scene.getEngine();
  19185. engine.setDepthWrite(this._cachedDepthWriteState);
  19186. }
  19187. };
  19188. Material.prototype.clone = function (name) {
  19189. return null;
  19190. };
  19191. Material.prototype.getBindedMeshes = function () {
  19192. var result = new Array();
  19193. for (var index = 0; index < this._scene.meshes.length; index++) {
  19194. var mesh = this._scene.meshes[index];
  19195. if (mesh.material === this) {
  19196. result.push(mesh);
  19197. }
  19198. }
  19199. return result;
  19200. };
  19201. Material.prototype.dispose = function (forceDisposeEffect) {
  19202. // Animations
  19203. this.getScene().stopAnimation(this);
  19204. // Remove from scene
  19205. var index = this._scene.materials.indexOf(this);
  19206. if (index >= 0) {
  19207. this._scene.materials.splice(index, 1);
  19208. }
  19209. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19210. if (forceDisposeEffect && this._effect) {
  19211. this._scene.getEngine()._releaseEffect(this._effect);
  19212. this._effect = null;
  19213. }
  19214. // Remove from meshes
  19215. for (index = 0; index < this._scene.meshes.length; index++) {
  19216. var mesh = this._scene.meshes[index];
  19217. if (mesh.material === this) {
  19218. mesh.material = null;
  19219. }
  19220. }
  19221. // Callback
  19222. if (this.onDispose) {
  19223. this.onDispose();
  19224. }
  19225. };
  19226. Material.prototype.copyTo = function (other) {
  19227. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19228. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19229. other.alpha = this.alpha;
  19230. other.fillMode = this.fillMode;
  19231. other.backFaceCulling = this.backFaceCulling;
  19232. other.fogEnabled = this.fogEnabled;
  19233. other.wireframe = this.wireframe;
  19234. other.zOffset = this.zOffset;
  19235. other.alphaMode = this.alphaMode;
  19236. other.sideOrientation = this.sideOrientation;
  19237. other.disableDepthWrite = this.disableDepthWrite;
  19238. other.pointSize = this.pointSize;
  19239. other.pointsCloud = this.pointsCloud;
  19240. };
  19241. Material.prototype.serialize = function () {
  19242. var serializationObject = {};
  19243. serializationObject.name = this.name;
  19244. serializationObject.alpha = this.alpha;
  19245. serializationObject.id = this.id;
  19246. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19247. serializationObject.backFaceCulling = this.backFaceCulling;
  19248. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19249. serializationObject.disableDepthWrite = this.disableDepthWrite;
  19250. return serializationObject;
  19251. };
  19252. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19253. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19254. multiMaterial.id = parsedMultiMaterial.id;
  19255. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19256. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19257. var subMatId = parsedMultiMaterial.materials[matIndex];
  19258. if (subMatId) {
  19259. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19260. }
  19261. else {
  19262. multiMaterial.subMaterials.push(null);
  19263. }
  19264. }
  19265. return multiMaterial;
  19266. };
  19267. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19268. if (!parsedMaterial.customType) {
  19269. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19270. }
  19271. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19272. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19273. ;
  19274. };
  19275. Material._TriangleFillMode = 0;
  19276. Material._WireFrameFillMode = 1;
  19277. Material._PointFillMode = 2;
  19278. Material._ClockWiseSideOrientation = 0;
  19279. Material._CounterClockWiseSideOrientation = 1;
  19280. return Material;
  19281. })();
  19282. BABYLON.Material = Material;
  19283. })(BABYLON || (BABYLON = {}));
  19284. var BABYLON;
  19285. (function (BABYLON) {
  19286. var maxSimultaneousLights = 4;
  19287. var FresnelParameters = (function () {
  19288. function FresnelParameters() {
  19289. this.isEnabled = true;
  19290. this.leftColor = BABYLON.Color3.White();
  19291. this.rightColor = BABYLON.Color3.Black();
  19292. this.bias = 0;
  19293. this.power = 1;
  19294. }
  19295. FresnelParameters.prototype.clone = function () {
  19296. var newFresnelParameters = new FresnelParameters();
  19297. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19298. return new FresnelParameters;
  19299. };
  19300. FresnelParameters.prototype.serialize = function () {
  19301. var serializationObject = {};
  19302. serializationObject.isEnabled = this.isEnabled;
  19303. serializationObject.leftColor = this.leftColor;
  19304. serializationObject.rightColor = this.rightColor;
  19305. serializationObject.bias = this.bias;
  19306. serializationObject.power = this.power;
  19307. return serializationObject;
  19308. };
  19309. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19310. var fresnelParameters = new FresnelParameters();
  19311. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19312. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19313. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19314. fresnelParameters.bias = parsedFresnelParameters.bias;
  19315. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19316. return fresnelParameters;
  19317. };
  19318. return FresnelParameters;
  19319. })();
  19320. BABYLON.FresnelParameters = FresnelParameters;
  19321. var StandardMaterialDefines = (function (_super) {
  19322. __extends(StandardMaterialDefines, _super);
  19323. function StandardMaterialDefines() {
  19324. _super.call(this);
  19325. this.DIFFUSE = false;
  19326. this.AMBIENT = false;
  19327. this.OPACITY = false;
  19328. this.OPACITYRGB = false;
  19329. this.REFLECTION = false;
  19330. this.EMISSIVE = false;
  19331. this.SPECULAR = false;
  19332. this.BUMP = false;
  19333. this.SPECULAROVERALPHA = false;
  19334. this.CLIPPLANE = false;
  19335. this.ALPHATEST = false;
  19336. this.ALPHAFROMDIFFUSE = false;
  19337. this.POINTSIZE = false;
  19338. this.FOG = false;
  19339. this.LIGHT0 = false;
  19340. this.LIGHT1 = false;
  19341. this.LIGHT2 = false;
  19342. this.LIGHT3 = false;
  19343. this.SPOTLIGHT0 = false;
  19344. this.SPOTLIGHT1 = false;
  19345. this.SPOTLIGHT2 = false;
  19346. this.SPOTLIGHT3 = false;
  19347. this.HEMILIGHT0 = false;
  19348. this.HEMILIGHT1 = false;
  19349. this.HEMILIGHT2 = false;
  19350. this.HEMILIGHT3 = false;
  19351. this.POINTLIGHT0 = false;
  19352. this.POINTLIGHT1 = false;
  19353. this.POINTLIGHT2 = false;
  19354. this.POINTLIGHT3 = false;
  19355. this.DIRLIGHT0 = false;
  19356. this.DIRLIGHT1 = false;
  19357. this.DIRLIGHT2 = false;
  19358. this.DIRLIGHT3 = false;
  19359. this.SPECULARTERM = false;
  19360. this.SHADOW0 = false;
  19361. this.SHADOW1 = false;
  19362. this.SHADOW2 = false;
  19363. this.SHADOW3 = false;
  19364. this.SHADOWS = false;
  19365. this.SHADOWVSM0 = false;
  19366. this.SHADOWVSM1 = false;
  19367. this.SHADOWVSM2 = false;
  19368. this.SHADOWVSM3 = false;
  19369. this.SHADOWPCF0 = false;
  19370. this.SHADOWPCF1 = false;
  19371. this.SHADOWPCF2 = false;
  19372. this.SHADOWPCF3 = false;
  19373. this.DIFFUSEFRESNEL = false;
  19374. this.OPACITYFRESNEL = false;
  19375. this.REFLECTIONFRESNEL = false;
  19376. this.REFRACTIONFRESNEL = false;
  19377. this.EMISSIVEFRESNEL = false;
  19378. this.FRESNEL = false;
  19379. this.NORMAL = false;
  19380. this.UV1 = false;
  19381. this.UV2 = false;
  19382. this.VERTEXCOLOR = false;
  19383. this.VERTEXALPHA = false;
  19384. this.NUM_BONE_INFLUENCERS = 0;
  19385. this.BonesPerMesh = 0;
  19386. this.INSTANCES = false;
  19387. this.GLOSSINESS = false;
  19388. this.ROUGHNESS = false;
  19389. this.EMISSIVEASILLUMINATION = false;
  19390. this.LINKEMISSIVEWITHDIFFUSE = false;
  19391. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19392. this.LIGHTMAP = false;
  19393. this.USELIGHTMAPASSHADOWMAP = false;
  19394. this.REFLECTIONMAP_3D = false;
  19395. this.REFLECTIONMAP_SPHERICAL = false;
  19396. this.REFLECTIONMAP_PLANAR = false;
  19397. this.REFLECTIONMAP_CUBIC = false;
  19398. this.REFLECTIONMAP_PROJECTION = false;
  19399. this.REFLECTIONMAP_SKYBOX = false;
  19400. this.REFLECTIONMAP_EXPLICIT = false;
  19401. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19402. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19403. this.INVERTCUBICMAP = false;
  19404. this.LOGARITHMICDEPTH = false;
  19405. this.REFRACTION = false;
  19406. this.REFRACTIONMAP_3D = false;
  19407. this._keys = Object.keys(this);
  19408. }
  19409. return StandardMaterialDefines;
  19410. })(BABYLON.MaterialDefines);
  19411. var StandardMaterial = (function (_super) {
  19412. __extends(StandardMaterial, _super);
  19413. function StandardMaterial(name, scene) {
  19414. var _this = this;
  19415. _super.call(this, name, scene);
  19416. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19417. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19418. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19419. this.specularPower = 64;
  19420. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19421. this.useAlphaFromDiffuseTexture = false;
  19422. this.useEmissiveAsIllumination = false;
  19423. this.linkEmissiveWithDiffuse = false;
  19424. this.useReflectionFresnelFromSpecular = false;
  19425. this.useSpecularOverAlpha = false;
  19426. this.disableLighting = false;
  19427. this.roughness = 0;
  19428. this.indexOfRefraction = 0.98;
  19429. this.invertRefractionY = true;
  19430. this.useLightmapAsShadowmap = false;
  19431. this.useGlossinessFromSpecularMapAlpha = false;
  19432. this._renderTargets = new BABYLON.SmartArray(16);
  19433. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19434. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19435. this._defines = new StandardMaterialDefines();
  19436. this._cachedDefines = new StandardMaterialDefines();
  19437. this._cachedDefines.BonesPerMesh = -1;
  19438. this.getRenderTargetTextures = function () {
  19439. _this._renderTargets.reset();
  19440. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19441. _this._renderTargets.push(_this.reflectionTexture);
  19442. }
  19443. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  19444. _this._renderTargets.push(_this.refractionTexture);
  19445. }
  19446. return _this._renderTargets;
  19447. };
  19448. }
  19449. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19450. get: function () {
  19451. return this._useLogarithmicDepth;
  19452. },
  19453. set: function (value) {
  19454. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. StandardMaterial.prototype.needAlphaBlending = function () {
  19460. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19461. };
  19462. StandardMaterial.prototype.needAlphaTesting = function () {
  19463. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19464. };
  19465. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19466. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19467. };
  19468. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19469. return this.diffuseTexture;
  19470. };
  19471. // Methods
  19472. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19473. if (!mesh) {
  19474. return true;
  19475. }
  19476. if (this._defines.INSTANCES !== useInstances) {
  19477. return false;
  19478. }
  19479. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19480. return true;
  19481. }
  19482. return false;
  19483. };
  19484. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19485. var lightIndex = 0;
  19486. var needNormals = false;
  19487. for (var index = 0; index < scene.lights.length; index++) {
  19488. var light = scene.lights[index];
  19489. if (!light.isEnabled()) {
  19490. continue;
  19491. }
  19492. // Excluded check
  19493. if (light._excludedMeshesIds.length > 0) {
  19494. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19495. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19496. if (excludedMesh) {
  19497. light.excludedMeshes.push(excludedMesh);
  19498. }
  19499. }
  19500. light._excludedMeshesIds = [];
  19501. }
  19502. // Included check
  19503. if (light._includedOnlyMeshesIds.length > 0) {
  19504. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19505. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19506. if (includedOnlyMesh) {
  19507. light.includedOnlyMeshes.push(includedOnlyMesh);
  19508. }
  19509. }
  19510. light._includedOnlyMeshesIds = [];
  19511. }
  19512. if (!light.canAffectMesh(mesh)) {
  19513. continue;
  19514. }
  19515. needNormals = true;
  19516. defines["LIGHT" + lightIndex] = true;
  19517. var type;
  19518. if (light instanceof BABYLON.SpotLight) {
  19519. type = "SPOTLIGHT" + lightIndex;
  19520. }
  19521. else if (light instanceof BABYLON.HemisphericLight) {
  19522. type = "HEMILIGHT" + lightIndex;
  19523. }
  19524. else if (light instanceof BABYLON.PointLight) {
  19525. type = "POINTLIGHT" + lightIndex;
  19526. }
  19527. else {
  19528. type = "DIRLIGHT" + lightIndex;
  19529. }
  19530. defines[type] = true;
  19531. // Specular
  19532. if (!light.specular.equalsFloats(0, 0, 0)) {
  19533. defines["SPECULARTERM"] = true;
  19534. }
  19535. // Shadows
  19536. if (scene.shadowsEnabled) {
  19537. var shadowGenerator = light.getShadowGenerator();
  19538. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19539. defines["SHADOW" + lightIndex] = true;
  19540. defines["SHADOWS"] = true;
  19541. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19542. defines["SHADOWVSM" + lightIndex] = true;
  19543. }
  19544. if (shadowGenerator.usePoissonSampling) {
  19545. defines["SHADOWPCF" + lightIndex] = true;
  19546. }
  19547. }
  19548. }
  19549. lightIndex++;
  19550. if (lightIndex === maxSimultaneousLights)
  19551. break;
  19552. }
  19553. return needNormals;
  19554. };
  19555. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19556. var lightIndex = 0;
  19557. var depthValuesAlreadySet = false;
  19558. for (var index = 0; index < scene.lights.length; index++) {
  19559. var light = scene.lights[index];
  19560. if (!light.isEnabled()) {
  19561. continue;
  19562. }
  19563. if (!light.canAffectMesh(mesh)) {
  19564. continue;
  19565. }
  19566. if (light instanceof BABYLON.PointLight) {
  19567. // Point Light
  19568. light.transferToEffect(effect, "vLightData" + lightIndex);
  19569. }
  19570. else if (light instanceof BABYLON.DirectionalLight) {
  19571. // Directional Light
  19572. light.transferToEffect(effect, "vLightData" + lightIndex);
  19573. }
  19574. else if (light instanceof BABYLON.SpotLight) {
  19575. // Spot Light
  19576. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19577. }
  19578. else if (light instanceof BABYLON.HemisphericLight) {
  19579. // Hemispheric Light
  19580. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19581. }
  19582. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19583. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19584. if (defines["SPECULARTERM"]) {
  19585. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19586. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19587. }
  19588. // Shadows
  19589. if (scene.shadowsEnabled) {
  19590. var shadowGenerator = light.getShadowGenerator();
  19591. if (mesh.receiveShadows && shadowGenerator) {
  19592. if (!light.needCube()) {
  19593. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19594. }
  19595. else {
  19596. if (!depthValuesAlreadySet) {
  19597. depthValuesAlreadySet = true;
  19598. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19599. }
  19600. }
  19601. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19602. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19603. }
  19604. }
  19605. lightIndex++;
  19606. if (lightIndex === maxSimultaneousLights)
  19607. break;
  19608. }
  19609. };
  19610. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19611. if (this.isFrozen) {
  19612. if (this._wasPreviouslyReady) {
  19613. return true;
  19614. }
  19615. }
  19616. var scene = this.getScene();
  19617. if (!this.checkReadyOnEveryCall) {
  19618. if (this._renderId === scene.getRenderId()) {
  19619. if (this._checkCache(scene, mesh, useInstances)) {
  19620. return true;
  19621. }
  19622. }
  19623. }
  19624. var engine = scene.getEngine();
  19625. var needNormals = false;
  19626. var needUVs = false;
  19627. this._defines.reset();
  19628. // Textures
  19629. if (scene.texturesEnabled) {
  19630. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19631. if (!this.diffuseTexture.isReady()) {
  19632. return false;
  19633. }
  19634. else {
  19635. needUVs = true;
  19636. this._defines.DIFFUSE = true;
  19637. }
  19638. }
  19639. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19640. if (!this.ambientTexture.isReady()) {
  19641. return false;
  19642. }
  19643. else {
  19644. needUVs = true;
  19645. this._defines.AMBIENT = true;
  19646. }
  19647. }
  19648. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19649. if (!this.opacityTexture.isReady()) {
  19650. return false;
  19651. }
  19652. else {
  19653. needUVs = true;
  19654. this._defines.OPACITY = true;
  19655. if (this.opacityTexture.getAlphaFromRGB) {
  19656. this._defines.OPACITYRGB = true;
  19657. }
  19658. }
  19659. }
  19660. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19661. if (!this.reflectionTexture.isReady()) {
  19662. return false;
  19663. }
  19664. else {
  19665. needNormals = true;
  19666. this._defines.REFLECTION = true;
  19667. if (this.roughness > 0) {
  19668. this._defines.ROUGHNESS = true;
  19669. }
  19670. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19671. this._defines.INVERTCUBICMAP = true;
  19672. }
  19673. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19674. switch (this.reflectionTexture.coordinatesMode) {
  19675. case BABYLON.Texture.CUBIC_MODE:
  19676. case BABYLON.Texture.INVCUBIC_MODE:
  19677. this._defines.REFLECTIONMAP_CUBIC = true;
  19678. break;
  19679. case BABYLON.Texture.EXPLICIT_MODE:
  19680. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19681. break;
  19682. case BABYLON.Texture.PLANAR_MODE:
  19683. this._defines.REFLECTIONMAP_PLANAR = true;
  19684. break;
  19685. case BABYLON.Texture.PROJECTION_MODE:
  19686. this._defines.REFLECTIONMAP_PROJECTION = true;
  19687. break;
  19688. case BABYLON.Texture.SKYBOX_MODE:
  19689. this._defines.REFLECTIONMAP_SKYBOX = true;
  19690. break;
  19691. case BABYLON.Texture.SPHERICAL_MODE:
  19692. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19693. break;
  19694. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19695. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19696. break;
  19697. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19698. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19699. break;
  19700. }
  19701. }
  19702. }
  19703. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19704. if (!this.emissiveTexture.isReady()) {
  19705. return false;
  19706. }
  19707. else {
  19708. needUVs = true;
  19709. this._defines.EMISSIVE = true;
  19710. }
  19711. }
  19712. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  19713. if (!this.lightmapTexture.isReady()) {
  19714. return false;
  19715. }
  19716. else {
  19717. needUVs = true;
  19718. this._defines.LIGHTMAP = true;
  19719. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19720. }
  19721. }
  19722. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19723. if (!this.specularTexture.isReady()) {
  19724. return false;
  19725. }
  19726. else {
  19727. needUVs = true;
  19728. this._defines.SPECULAR = true;
  19729. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19730. }
  19731. }
  19732. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19733. if (!this.bumpTexture.isReady()) {
  19734. return false;
  19735. }
  19736. else {
  19737. needUVs = true;
  19738. this._defines.BUMP = true;
  19739. }
  19740. }
  19741. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  19742. if (!this.refractionTexture.isReady()) {
  19743. return false;
  19744. }
  19745. else {
  19746. needUVs = true;
  19747. this._defines.REFRACTION = true;
  19748. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  19749. }
  19750. }
  19751. }
  19752. // Effect
  19753. if (scene.clipPlane) {
  19754. this._defines.CLIPPLANE = true;
  19755. }
  19756. if (engine.getAlphaTesting()) {
  19757. this._defines.ALPHATEST = true;
  19758. }
  19759. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19760. this._defines.ALPHAFROMDIFFUSE = true;
  19761. }
  19762. if (this.useEmissiveAsIllumination) {
  19763. this._defines.EMISSIVEASILLUMINATION = true;
  19764. }
  19765. if (this.linkEmissiveWithDiffuse) {
  19766. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19767. }
  19768. if (this.useReflectionFresnelFromSpecular) {
  19769. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19770. }
  19771. if (this.useLogarithmicDepth) {
  19772. this._defines.LOGARITHMICDEPTH = true;
  19773. }
  19774. // Point size
  19775. if (this.pointsCloud || scene.forcePointsCloud) {
  19776. this._defines.POINTSIZE = true;
  19777. }
  19778. // Fog
  19779. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19780. this._defines.FOG = true;
  19781. }
  19782. if (scene.lightsEnabled && !this.disableLighting) {
  19783. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19784. }
  19785. if (StandardMaterial.FresnelEnabled) {
  19786. // Fresnel
  19787. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19788. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19789. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19790. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  19791. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19792. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19793. this._defines.DIFFUSEFRESNEL = true;
  19794. }
  19795. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19796. this._defines.OPACITYFRESNEL = true;
  19797. }
  19798. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19799. this._defines.REFLECTIONFRESNEL = true;
  19800. }
  19801. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  19802. this._defines.REFRACTIONFRESNEL = true;
  19803. }
  19804. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19805. this._defines.EMISSIVEFRESNEL = true;
  19806. }
  19807. needNormals = true;
  19808. this._defines.FRESNEL = true;
  19809. }
  19810. }
  19811. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19812. this._defines.SPECULAROVERALPHA = true;
  19813. }
  19814. // Attribs
  19815. if (mesh) {
  19816. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19817. this._defines.NORMAL = true;
  19818. }
  19819. if (needUVs) {
  19820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19821. this._defines.UV1 = true;
  19822. }
  19823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19824. this._defines.UV2 = true;
  19825. }
  19826. }
  19827. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19828. this._defines.VERTEXCOLOR = true;
  19829. if (mesh.hasVertexAlpha) {
  19830. this._defines.VERTEXALPHA = true;
  19831. }
  19832. }
  19833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19834. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19835. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19836. }
  19837. // Instances
  19838. if (useInstances) {
  19839. this._defines.INSTANCES = true;
  19840. }
  19841. }
  19842. // Get correct effect
  19843. if (!this._defines.isEqual(this._cachedDefines)) {
  19844. this._defines.cloneTo(this._cachedDefines);
  19845. scene.resetCachedMaterial();
  19846. // Fallbacks
  19847. var fallbacks = new BABYLON.EffectFallbacks();
  19848. if (this._defines.REFLECTION) {
  19849. fallbacks.addFallback(0, "REFLECTION");
  19850. }
  19851. if (this._defines.SPECULAR) {
  19852. fallbacks.addFallback(0, "SPECULAR");
  19853. }
  19854. if (this._defines.BUMP) {
  19855. fallbacks.addFallback(0, "BUMP");
  19856. }
  19857. if (this._defines.SPECULAROVERALPHA) {
  19858. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19859. }
  19860. if (this._defines.FOG) {
  19861. fallbacks.addFallback(1, "FOG");
  19862. }
  19863. if (this._defines.POINTSIZE) {
  19864. fallbacks.addFallback(0, "POINTSIZE");
  19865. }
  19866. if (this._defines.LOGARITHMICDEPTH) {
  19867. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19868. }
  19869. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19870. if (!this._defines["LIGHT" + lightIndex]) {
  19871. continue;
  19872. }
  19873. if (lightIndex > 0) {
  19874. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19875. }
  19876. if (this._defines["SHADOW" + lightIndex]) {
  19877. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19878. }
  19879. if (this._defines["SHADOWPCF" + lightIndex]) {
  19880. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19881. }
  19882. if (this._defines["SHADOWVSM" + lightIndex]) {
  19883. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19884. }
  19885. }
  19886. if (this._defines.SPECULARTERM) {
  19887. fallbacks.addFallback(0, "SPECULARTERM");
  19888. }
  19889. if (this._defines.DIFFUSEFRESNEL) {
  19890. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19891. }
  19892. if (this._defines.OPACITYFRESNEL) {
  19893. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19894. }
  19895. if (this._defines.REFLECTIONFRESNEL) {
  19896. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19897. }
  19898. if (this._defines.EMISSIVEFRESNEL) {
  19899. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19900. }
  19901. if (this._defines.FRESNEL) {
  19902. fallbacks.addFallback(4, "FRESNEL");
  19903. }
  19904. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19905. fallbacks.addCPUSkinningFallback(0, mesh);
  19906. }
  19907. //Attributes
  19908. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19909. if (this._defines.NORMAL) {
  19910. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19911. }
  19912. if (this._defines.UV1) {
  19913. attribs.push(BABYLON.VertexBuffer.UVKind);
  19914. }
  19915. if (this._defines.UV2) {
  19916. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19917. }
  19918. if (this._defines.VERTEXCOLOR) {
  19919. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19920. }
  19921. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19922. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19923. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19924. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19927. }
  19928. }
  19929. if (this._defines.INSTANCES) {
  19930. attribs.push("world0");
  19931. attribs.push("world1");
  19932. attribs.push("world2");
  19933. attribs.push("world3");
  19934. }
  19935. // Legacy browser patch
  19936. var shaderName = "default";
  19937. if (!scene.getEngine().getCaps().standardDerivatives) {
  19938. shaderName = "legacydefault";
  19939. }
  19940. var join = this._defines.toString();
  19941. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19942. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19943. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19944. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19945. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19946. "vFogInfos", "vFogColor", "pointSize",
  19947. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  19948. "mBones",
  19949. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  19950. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19951. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  19952. "logarithmicDepthConstant"
  19953. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  19954. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19955. ], join, fallbacks, this.onCompiled, this.onError);
  19956. }
  19957. if (!this._effect.isReady()) {
  19958. return false;
  19959. }
  19960. this._renderId = scene.getRenderId();
  19961. this._wasPreviouslyReady = true;
  19962. if (mesh) {
  19963. if (!mesh._materialDefines) {
  19964. mesh._materialDefines = new StandardMaterialDefines();
  19965. }
  19966. this._defines.cloneTo(mesh._materialDefines);
  19967. }
  19968. return true;
  19969. };
  19970. StandardMaterial.prototype.unbind = function () {
  19971. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19972. this._effect.setTexture("reflection2DSampler", null);
  19973. }
  19974. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  19975. this._effect.setTexture("refraction2DSampler", null);
  19976. }
  19977. _super.prototype.unbind.call(this);
  19978. };
  19979. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19980. this._effect.setMatrix("world", world);
  19981. };
  19982. StandardMaterial.prototype.bind = function (world, mesh) {
  19983. var scene = this.getScene();
  19984. // Matrices
  19985. this.bindOnlyWorldMatrix(world);
  19986. // Bones
  19987. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19988. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19989. }
  19990. if (scene.getCachedMaterial() !== this) {
  19991. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19992. if (StandardMaterial.FresnelEnabled) {
  19993. // Fresnel
  19994. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19995. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19996. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19997. }
  19998. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19999. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20000. }
  20001. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20002. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20003. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20004. }
  20005. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20006. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20007. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20008. }
  20009. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20010. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20011. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20012. }
  20013. }
  20014. // Textures
  20015. if (scene.texturesEnabled) {
  20016. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20017. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20018. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20019. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20020. }
  20021. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20022. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20023. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20024. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20025. }
  20026. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20027. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20028. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20029. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20030. }
  20031. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20032. if (this.reflectionTexture.isCube) {
  20033. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20034. }
  20035. else {
  20036. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20037. }
  20038. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20039. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20040. }
  20041. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20042. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20043. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20044. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20045. }
  20046. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20047. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20048. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20049. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20050. }
  20051. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20052. this._effect.setTexture("specularSampler", this.specularTexture);
  20053. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20054. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20055. }
  20056. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20057. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20058. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20059. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20060. }
  20061. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20062. var depth = 1.0;
  20063. if (this.refractionTexture.isCube) {
  20064. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20065. }
  20066. else {
  20067. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20068. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20069. if (this.refractionTexture.depth) {
  20070. depth = this.refractionTexture.depth;
  20071. }
  20072. }
  20073. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20074. }
  20075. }
  20076. // Clip plane
  20077. if (scene.clipPlane) {
  20078. var clipPlane = scene.clipPlane;
  20079. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20080. }
  20081. // Point size
  20082. if (this.pointsCloud) {
  20083. this._effect.setFloat("pointSize", this.pointSize);
  20084. }
  20085. // Colors
  20086. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20087. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20088. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20089. if (this._defines.SPECULARTERM) {
  20090. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20091. }
  20092. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20093. }
  20094. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20095. // Diffuse
  20096. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20097. // Lights
  20098. if (scene.lightsEnabled && !this.disableLighting) {
  20099. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  20100. }
  20101. // View
  20102. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20103. this._effect.setMatrix("view", scene.getViewMatrix());
  20104. }
  20105. // Fog
  20106. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20107. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20108. this._effect.setColor3("vFogColor", scene.fogColor);
  20109. }
  20110. // Log. depth
  20111. if (this._defines.LOGARITHMICDEPTH) {
  20112. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20113. }
  20114. }
  20115. _super.prototype.bind.call(this, world, mesh);
  20116. };
  20117. StandardMaterial.prototype.getAnimatables = function () {
  20118. var results = [];
  20119. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20120. results.push(this.diffuseTexture);
  20121. }
  20122. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20123. results.push(this.ambientTexture);
  20124. }
  20125. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20126. results.push(this.opacityTexture);
  20127. }
  20128. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20129. results.push(this.reflectionTexture);
  20130. }
  20131. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20132. results.push(this.emissiveTexture);
  20133. }
  20134. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20135. results.push(this.specularTexture);
  20136. }
  20137. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20138. results.push(this.bumpTexture);
  20139. }
  20140. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20141. results.push(this.lightmapTexture);
  20142. }
  20143. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20144. results.push(this.refractionTexture);
  20145. }
  20146. return results;
  20147. };
  20148. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20149. if (this.diffuseTexture) {
  20150. this.diffuseTexture.dispose();
  20151. }
  20152. if (this.ambientTexture) {
  20153. this.ambientTexture.dispose();
  20154. }
  20155. if (this.opacityTexture) {
  20156. this.opacityTexture.dispose();
  20157. }
  20158. if (this.reflectionTexture) {
  20159. this.reflectionTexture.dispose();
  20160. }
  20161. if (this.emissiveTexture) {
  20162. this.emissiveTexture.dispose();
  20163. }
  20164. if (this.specularTexture) {
  20165. this.specularTexture.dispose();
  20166. }
  20167. if (this.bumpTexture) {
  20168. this.bumpTexture.dispose();
  20169. }
  20170. if (this.lightmapTexture) {
  20171. this.lightmapTexture.dispose();
  20172. }
  20173. if (this.refractionTexture) {
  20174. this.refractionTexture.dispose();
  20175. }
  20176. _super.prototype.dispose.call(this, forceDisposeEffect);
  20177. };
  20178. StandardMaterial.prototype.clone = function (name) {
  20179. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  20180. // Base material
  20181. this.copyTo(newStandardMaterial);
  20182. // Standard material
  20183. if (this.diffuseTexture && this.diffuseTexture.clone) {
  20184. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  20185. }
  20186. if (this.ambientTexture && this.ambientTexture.clone) {
  20187. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  20188. }
  20189. if (this.opacityTexture && this.opacityTexture.clone) {
  20190. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  20191. }
  20192. if (this.reflectionTexture && this.reflectionTexture.clone) {
  20193. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  20194. }
  20195. if (this.emissiveTexture && this.emissiveTexture.clone) {
  20196. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  20197. }
  20198. if (this.specularTexture && this.specularTexture.clone) {
  20199. newStandardMaterial.specularTexture = this.specularTexture.clone();
  20200. }
  20201. if (this.bumpTexture && this.bumpTexture.clone) {
  20202. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  20203. }
  20204. if (this.lightmapTexture && this.lightmapTexture.clone) {
  20205. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  20206. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20207. }
  20208. if (this.refractionTexture && this.refractionTexture.clone) {
  20209. newStandardMaterial.refractionTexture = this.refractionTexture.clone();
  20210. }
  20211. newStandardMaterial.ambientColor = this.ambientColor.clone();
  20212. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  20213. newStandardMaterial.specularColor = this.specularColor.clone();
  20214. newStandardMaterial.specularPower = this.specularPower;
  20215. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  20216. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  20217. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20218. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  20219. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20220. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  20221. newStandardMaterial.roughness = this.roughness;
  20222. newStandardMaterial.indexOfRefraction = this.indexOfRefraction;
  20223. newStandardMaterial.invertRefractionY = this.invertRefractionY;
  20224. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  20225. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  20226. }
  20227. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  20228. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  20229. }
  20230. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  20231. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  20232. }
  20233. if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
  20234. newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
  20235. }
  20236. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  20237. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  20238. }
  20239. return newStandardMaterial;
  20240. };
  20241. StandardMaterial.prototype.serialize = function () {
  20242. var serializationObject = _super.prototype.serialize.call(this);
  20243. serializationObject.ambient = this.ambientColor.asArray();
  20244. serializationObject.diffuse = this.diffuseColor.asArray();
  20245. serializationObject.specular = this.specularColor.asArray();
  20246. serializationObject.specularPower = this.specularPower;
  20247. serializationObject.emissive = this.emissiveColor.asArray();
  20248. serializationObject.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20249. serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20250. serializationObject.indexOfRefraction = this.indexOfRefraction;
  20251. serializationObject.invertRefractionY = this.invertRefractionY;
  20252. if (this.diffuseTexture) {
  20253. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  20254. }
  20255. if (this.diffuseFresnelParameters) {
  20256. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  20257. }
  20258. if (this.ambientTexture) {
  20259. serializationObject.ambientTexture = this.ambientTexture.serialize();
  20260. }
  20261. if (this.opacityTexture) {
  20262. serializationObject.opacityTexture = this.opacityTexture.serialize();
  20263. }
  20264. if (this.opacityFresnelParameters) {
  20265. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  20266. }
  20267. if (this.reflectionTexture) {
  20268. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  20269. }
  20270. if (this.reflectionFresnelParameters) {
  20271. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  20272. }
  20273. if (this.refractionFresnelParameters) {
  20274. serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
  20275. }
  20276. if (this.emissiveTexture) {
  20277. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  20278. }
  20279. if (this.lightmapTexture) {
  20280. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  20281. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20282. }
  20283. if (this.emissiveFresnelParameters) {
  20284. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  20285. }
  20286. if (this.specularTexture) {
  20287. serializationObject.specularTexture = this.specularTexture.serialize();
  20288. }
  20289. if (this.bumpTexture) {
  20290. serializationObject.bumpTexture = this.bumpTexture.serialize();
  20291. }
  20292. if (this.refractionTexture) {
  20293. serializationObject.refractionTexture = this.refractionTexture.serialize();
  20294. }
  20295. return serializationObject;
  20296. };
  20297. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20298. var material = new StandardMaterial(source.name, scene);
  20299. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  20300. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  20301. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  20302. material.specularPower = source.specularPower;
  20303. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  20304. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  20305. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  20306. material.indexOfRefraction = source.indexOfRefraction;
  20307. material.invertRefractionY = source.invertRefractionY;
  20308. material.alpha = source.alpha;
  20309. material.id = source.id;
  20310. if (source.disableDepthWrite) {
  20311. material.disableDepthWrite = source.disableDepthWrite;
  20312. }
  20313. BABYLON.Tags.AddTagsTo(material, source.tags);
  20314. material.backFaceCulling = source.backFaceCulling;
  20315. material.wireframe = source.wireframe;
  20316. if (source.diffuseTexture) {
  20317. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  20318. }
  20319. if (source.diffuseFresnelParameters) {
  20320. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  20321. }
  20322. if (source.ambientTexture) {
  20323. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  20324. }
  20325. if (source.opacityTexture) {
  20326. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  20327. }
  20328. if (source.opacityFresnelParameters) {
  20329. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  20330. }
  20331. if (source.reflectionTexture) {
  20332. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  20333. }
  20334. if (source.reflectionFresnelParameters) {
  20335. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  20336. }
  20337. if (source.refractionFresnelParameters) {
  20338. material.refractionFresnelParameters = FresnelParameters.Parse(source.refractionFresnelParameters);
  20339. }
  20340. if (source.emissiveTexture) {
  20341. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20342. }
  20343. if (source.lightmapTexture) {
  20344. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20345. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20346. }
  20347. if (source.emissiveFresnelParameters) {
  20348. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  20349. }
  20350. if (source.specularTexture) {
  20351. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20352. }
  20353. if (source.bumpTexture) {
  20354. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20355. }
  20356. if (source.refractionTexture) {
  20357. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  20358. }
  20359. if (source.checkReadyOnlyOnce) {
  20360. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20361. }
  20362. return material;
  20363. };
  20364. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  20365. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  20366. // Statics
  20367. // Flags used to enable or disable a type of texture for all Standard Materials
  20368. StandardMaterial.DiffuseTextureEnabled = true;
  20369. StandardMaterial.AmbientTextureEnabled = true;
  20370. StandardMaterial.OpacityTextureEnabled = true;
  20371. StandardMaterial.ReflectionTextureEnabled = true;
  20372. StandardMaterial.EmissiveTextureEnabled = true;
  20373. StandardMaterial.SpecularTextureEnabled = true;
  20374. StandardMaterial.BumpTextureEnabled = true;
  20375. StandardMaterial.FresnelEnabled = true;
  20376. StandardMaterial.LightmapTextureEnabled = true;
  20377. StandardMaterial.RefractionTextureEnabled = true;
  20378. return StandardMaterial;
  20379. })(BABYLON.Material);
  20380. BABYLON.StandardMaterial = StandardMaterial;
  20381. })(BABYLON || (BABYLON = {}));
  20382. var BABYLON;
  20383. (function (BABYLON) {
  20384. var MultiMaterial = (function (_super) {
  20385. __extends(MultiMaterial, _super);
  20386. function MultiMaterial(name, scene) {
  20387. _super.call(this, name, scene, true);
  20388. this.subMaterials = new Array();
  20389. scene.multiMaterials.push(this);
  20390. }
  20391. // Properties
  20392. MultiMaterial.prototype.getSubMaterial = function (index) {
  20393. if (index < 0 || index >= this.subMaterials.length) {
  20394. return this.getScene().defaultMaterial;
  20395. }
  20396. return this.subMaterials[index];
  20397. };
  20398. // Methods
  20399. MultiMaterial.prototype.isReady = function (mesh) {
  20400. for (var index = 0; index < this.subMaterials.length; index++) {
  20401. var subMaterial = this.subMaterials[index];
  20402. if (subMaterial) {
  20403. if (!this.subMaterials[index].isReady(mesh)) {
  20404. return false;
  20405. }
  20406. }
  20407. }
  20408. return true;
  20409. };
  20410. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20411. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20412. for (var index = 0; index < this.subMaterials.length; index++) {
  20413. var subMaterial = null;
  20414. if (cloneChildren) {
  20415. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20416. }
  20417. else {
  20418. subMaterial = this.subMaterials[index];
  20419. }
  20420. newMultiMaterial.subMaterials.push(subMaterial);
  20421. }
  20422. return newMultiMaterial;
  20423. };
  20424. MultiMaterial.prototype.serialize = function () {
  20425. var serializationObject = {};
  20426. serializationObject.name = this.name;
  20427. serializationObject.id = this.id;
  20428. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20429. serializationObject.materials = [];
  20430. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20431. var subMat = this.subMaterials[matIndex];
  20432. if (subMat) {
  20433. serializationObject.materials.push(subMat.id);
  20434. }
  20435. else {
  20436. serializationObject.materials.push(null);
  20437. }
  20438. }
  20439. return serializationObject;
  20440. };
  20441. return MultiMaterial;
  20442. })(BABYLON.Material);
  20443. BABYLON.MultiMaterial = MultiMaterial;
  20444. })(BABYLON || (BABYLON = {}));
  20445. var BABYLON;
  20446. (function (BABYLON) {
  20447. var SceneLoader = (function () {
  20448. function SceneLoader() {
  20449. }
  20450. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20451. get: function () {
  20452. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20453. },
  20454. set: function (value) {
  20455. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20456. },
  20457. enumerable: true,
  20458. configurable: true
  20459. });
  20460. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20461. get: function () {
  20462. return SceneLoader._ShowLoadingScreen;
  20463. },
  20464. set: function (value) {
  20465. SceneLoader._ShowLoadingScreen = value;
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20471. var dotPosition = sceneFilename.lastIndexOf(".");
  20472. var queryStringPosition = sceneFilename.indexOf("?");
  20473. if (queryStringPosition === -1) {
  20474. queryStringPosition = sceneFilename.length;
  20475. }
  20476. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20477. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20478. var plugin = this._registeredPlugins[index];
  20479. if (plugin.extensions.indexOf(extension) !== -1) {
  20480. return plugin;
  20481. }
  20482. }
  20483. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20484. };
  20485. // Public functions
  20486. SceneLoader.GetPluginForExtension = function (extension) {
  20487. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20488. var plugin = this._registeredPlugins[index];
  20489. if (plugin.extensions.indexOf(extension) !== -1) {
  20490. return plugin;
  20491. }
  20492. }
  20493. return null;
  20494. };
  20495. SceneLoader.RegisterPlugin = function (plugin) {
  20496. plugin.extensions = plugin.extensions.toLowerCase();
  20497. SceneLoader._registeredPlugins.push(plugin);
  20498. };
  20499. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20500. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20501. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20502. return;
  20503. }
  20504. var loadingToken = {};
  20505. scene._addPendingData(loadingToken);
  20506. var manifestChecked = function (success) {
  20507. scene.database = database;
  20508. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20509. var importMeshFromData = function (data) {
  20510. var meshes = [];
  20511. var particleSystems = [];
  20512. var skeletons = [];
  20513. try {
  20514. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20515. if (onerror) {
  20516. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20517. }
  20518. scene._removePendingData(loadingToken);
  20519. return;
  20520. }
  20521. }
  20522. catch (e) {
  20523. if (onerror) {
  20524. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20525. }
  20526. scene._removePendingData(loadingToken);
  20527. return;
  20528. }
  20529. if (onsuccess) {
  20530. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20531. onsuccess(meshes, particleSystems, skeletons);
  20532. scene._removePendingData(loadingToken);
  20533. }
  20534. };
  20535. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20536. // Direct load
  20537. importMeshFromData(sceneFilename.substr(5));
  20538. return;
  20539. }
  20540. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20541. importMeshFromData(data);
  20542. }, progressCallBack, database);
  20543. };
  20544. if (scene.getEngine().enableOfflineSupport) {
  20545. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20546. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20547. }
  20548. else {
  20549. manifestChecked(true);
  20550. }
  20551. };
  20552. /**
  20553. * Load a scene
  20554. * @param rootUrl a string that defines the root url for scene and resources
  20555. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20556. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20557. */
  20558. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20559. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20560. };
  20561. /**
  20562. * Append a scene
  20563. * @param rootUrl a string that defines the root url for scene and resources
  20564. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20565. * @param scene is the instance of BABYLON.Scene to append to
  20566. */
  20567. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20568. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20569. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20570. return;
  20571. }
  20572. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20573. var database;
  20574. var loadingToken = {};
  20575. scene._addPendingData(loadingToken);
  20576. if (SceneLoader.ShowLoadingScreen) {
  20577. scene.getEngine().displayLoadingUI();
  20578. }
  20579. var loadSceneFromData = function (data) {
  20580. scene.database = database;
  20581. if (!plugin.load(scene, data, rootUrl)) {
  20582. if (onerror) {
  20583. onerror(scene);
  20584. }
  20585. scene._removePendingData(loadingToken);
  20586. scene.getEngine().hideLoadingUI();
  20587. return;
  20588. }
  20589. if (onsuccess) {
  20590. onsuccess(scene);
  20591. }
  20592. scene._removePendingData(loadingToken);
  20593. if (SceneLoader.ShowLoadingScreen) {
  20594. scene.executeWhenReady(function () {
  20595. scene.getEngine().hideLoadingUI();
  20596. });
  20597. }
  20598. };
  20599. var manifestChecked = function (success) {
  20600. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20601. };
  20602. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20603. // Direct load
  20604. loadSceneFromData(sceneFilename.substr(5));
  20605. return;
  20606. }
  20607. if (rootUrl.indexOf("file:") === -1) {
  20608. if (scene.getEngine().enableOfflineSupport) {
  20609. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20610. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20611. }
  20612. else {
  20613. manifestChecked(true);
  20614. }
  20615. }
  20616. else {
  20617. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20618. }
  20619. };
  20620. // Flags
  20621. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20622. SceneLoader._ShowLoadingScreen = true;
  20623. // Members
  20624. SceneLoader._registeredPlugins = new Array();
  20625. return SceneLoader;
  20626. })();
  20627. BABYLON.SceneLoader = SceneLoader;
  20628. ;
  20629. })(BABYLON || (BABYLON = {}));
  20630. var BABYLON;
  20631. (function (BABYLON) {
  20632. var Internals;
  20633. (function (Internals) {
  20634. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20635. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20636. var parsedMaterial = parsedData.materials[index];
  20637. if (parsedMaterial.id === id) {
  20638. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20639. }
  20640. }
  20641. return null;
  20642. };
  20643. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20644. names = (names instanceof Array) ? names : [names];
  20645. for (var i in names) {
  20646. if (mesh.name === names[i]) {
  20647. hierarchyIds.push(mesh.id);
  20648. return true;
  20649. }
  20650. }
  20651. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20652. hierarchyIds.push(mesh.id);
  20653. return true;
  20654. }
  20655. return false;
  20656. };
  20657. BABYLON.SceneLoader.RegisterPlugin({
  20658. extensions: ".babylon",
  20659. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20660. var parsedData = JSON.parse(data);
  20661. var loadedSkeletonsIds = [];
  20662. var loadedMaterialsIds = [];
  20663. var hierarchyIds = [];
  20664. var index;
  20665. var cache;
  20666. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20667. var parsedMesh = parsedData.meshes[index];
  20668. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20669. if (meshesNames instanceof Array) {
  20670. // Remove found mesh name from list.
  20671. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20672. }
  20673. //Geometry?
  20674. if (parsedMesh.geometryId) {
  20675. //does the file contain geometries?
  20676. if (parsedData.geometries) {
  20677. //find the correct geometry and add it to the scene
  20678. var found = false;
  20679. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20680. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20681. return;
  20682. }
  20683. else {
  20684. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20685. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20686. switch (geometryType) {
  20687. case "boxes":
  20688. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20689. break;
  20690. case "spheres":
  20691. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20692. break;
  20693. case "cylinders":
  20694. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20695. break;
  20696. case "toruses":
  20697. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20698. break;
  20699. case "grounds":
  20700. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20701. break;
  20702. case "planes":
  20703. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20704. break;
  20705. case "torusKnots":
  20706. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20707. break;
  20708. case "vertexData":
  20709. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20710. break;
  20711. }
  20712. found = true;
  20713. }
  20714. });
  20715. }
  20716. });
  20717. if (!found) {
  20718. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20719. }
  20720. }
  20721. }
  20722. // Material ?
  20723. if (parsedMesh.materialId) {
  20724. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20725. if (!materialFound && parsedData.multiMaterials) {
  20726. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20727. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20728. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20729. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20730. var subMatId = parsedMultiMaterial.materials[matIndex];
  20731. loadedMaterialsIds.push(subMatId);
  20732. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20733. }
  20734. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20735. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20736. materialFound = true;
  20737. break;
  20738. }
  20739. }
  20740. }
  20741. if (!materialFound) {
  20742. loadedMaterialsIds.push(parsedMesh.materialId);
  20743. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20744. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20745. }
  20746. }
  20747. }
  20748. // Skeleton ?
  20749. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20750. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20751. if (!skeletonAlreadyLoaded) {
  20752. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20753. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20754. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20755. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20756. loadedSkeletonsIds.push(parsedSkeleton.id);
  20757. }
  20758. }
  20759. }
  20760. }
  20761. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20762. meshes.push(mesh);
  20763. }
  20764. }
  20765. // Connecting parents
  20766. var currentMesh;
  20767. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20768. currentMesh = scene.meshes[index];
  20769. if (currentMesh._waitingParentId) {
  20770. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20771. currentMesh._waitingParentId = undefined;
  20772. }
  20773. }
  20774. // freeze and compute world matrix application
  20775. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20776. currentMesh = scene.meshes[index];
  20777. if (currentMesh._waitingFreezeWorldMatrix) {
  20778. currentMesh.freezeWorldMatrix();
  20779. currentMesh._waitingFreezeWorldMatrix = undefined;
  20780. }
  20781. else {
  20782. currentMesh.computeWorldMatrix(true);
  20783. }
  20784. }
  20785. // Particles
  20786. if (parsedData.particleSystems) {
  20787. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20788. var parsedParticleSystem = parsedData.particleSystems[index];
  20789. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20790. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20791. }
  20792. }
  20793. }
  20794. return true;
  20795. },
  20796. load: function (scene, data, rootUrl) {
  20797. var parsedData = JSON.parse(data);
  20798. // Scene
  20799. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20800. scene.autoClear = parsedData.autoClear;
  20801. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20802. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20803. if (parsedData.gravity) {
  20804. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20805. }
  20806. // Fog
  20807. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20808. scene.fogMode = parsedData.fogMode;
  20809. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20810. scene.fogStart = parsedData.fogStart;
  20811. scene.fogEnd = parsedData.fogEnd;
  20812. scene.fogDensity = parsedData.fogDensity;
  20813. }
  20814. //Physics
  20815. if (parsedData.physicsEnabled) {
  20816. var physicsPlugin;
  20817. if (parsedData.physicsEngine === "cannon") {
  20818. physicsPlugin = new BABYLON.CannonJSPlugin();
  20819. }
  20820. else if (parsedData.physicsEngine === "oimo") {
  20821. physicsPlugin = new BABYLON.OimoJSPlugin();
  20822. }
  20823. //else - default engine, which is currently oimo
  20824. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20825. scene.enablePhysics(physicsGravity, physicsPlugin);
  20826. }
  20827. //collisions, if defined. otherwise, default is true
  20828. if (parsedData.collisionsEnabled != undefined) {
  20829. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20830. }
  20831. scene.workerCollisions = !!parsedData.workerCollisions;
  20832. var index;
  20833. var cache;
  20834. // Lights
  20835. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20836. var parsedLight = parsedData.lights[index];
  20837. BABYLON.Light.Parse(parsedLight, scene);
  20838. }
  20839. // Materials
  20840. if (parsedData.materials) {
  20841. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20842. var parsedMaterial = parsedData.materials[index];
  20843. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20844. }
  20845. }
  20846. if (parsedData.multiMaterials) {
  20847. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20848. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20849. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20850. }
  20851. }
  20852. // Skeletons
  20853. if (parsedData.skeletons) {
  20854. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20855. var parsedSkeleton = parsedData.skeletons[index];
  20856. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20857. }
  20858. }
  20859. // Geometries
  20860. var geometries = parsedData.geometries;
  20861. if (geometries) {
  20862. // Boxes
  20863. var boxes = geometries.boxes;
  20864. if (boxes) {
  20865. for (index = 0, cache = boxes.length; index < cache; index++) {
  20866. var parsedBox = boxes[index];
  20867. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20868. }
  20869. }
  20870. // Spheres
  20871. var spheres = geometries.spheres;
  20872. if (spheres) {
  20873. for (index = 0, cache = spheres.length; index < cache; index++) {
  20874. var parsedSphere = spheres[index];
  20875. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20876. }
  20877. }
  20878. // Cylinders
  20879. var cylinders = geometries.cylinders;
  20880. if (cylinders) {
  20881. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20882. var parsedCylinder = cylinders[index];
  20883. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20884. }
  20885. }
  20886. // Toruses
  20887. var toruses = geometries.toruses;
  20888. if (toruses) {
  20889. for (index = 0, cache = toruses.length; index < cache; index++) {
  20890. var parsedTorus = toruses[index];
  20891. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20892. }
  20893. }
  20894. // Grounds
  20895. var grounds = geometries.grounds;
  20896. if (grounds) {
  20897. for (index = 0, cache = grounds.length; index < cache; index++) {
  20898. var parsedGround = grounds[index];
  20899. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20900. }
  20901. }
  20902. // Planes
  20903. var planes = geometries.planes;
  20904. if (planes) {
  20905. for (index = 0, cache = planes.length; index < cache; index++) {
  20906. var parsedPlane = planes[index];
  20907. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20908. }
  20909. }
  20910. // TorusKnots
  20911. var torusKnots = geometries.torusKnots;
  20912. if (torusKnots) {
  20913. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20914. var parsedTorusKnot = torusKnots[index];
  20915. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20916. }
  20917. }
  20918. // VertexData
  20919. var vertexData = geometries.vertexData;
  20920. if (vertexData) {
  20921. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20922. var parsedVertexData = vertexData[index];
  20923. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20924. }
  20925. }
  20926. }
  20927. // Meshes
  20928. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20929. var parsedMesh = parsedData.meshes[index];
  20930. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20931. }
  20932. // Cameras
  20933. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20934. var parsedCamera = parsedData.cameras[index];
  20935. BABYLON.Camera.Parse(parsedCamera, scene);
  20936. }
  20937. if (parsedData.activeCameraID) {
  20938. scene.setActiveCameraByID(parsedData.activeCameraID);
  20939. }
  20940. // Browsing all the graph to connect the dots
  20941. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20942. var camera = scene.cameras[index];
  20943. if (camera._waitingParentId) {
  20944. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20945. camera._waitingParentId = undefined;
  20946. }
  20947. }
  20948. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20949. var light = scene.lights[index];
  20950. if (light._waitingParentId) {
  20951. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20952. light._waitingParentId = undefined;
  20953. }
  20954. }
  20955. // Sounds
  20956. var loadedSounds = [];
  20957. var loadedSound;
  20958. if (BABYLON.AudioEngine && parsedData.sounds) {
  20959. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20960. var parsedSound = parsedData.sounds[index];
  20961. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20962. if (!parsedSound.url)
  20963. parsedSound.url = parsedSound.name;
  20964. if (!loadedSounds[parsedSound.url]) {
  20965. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20966. loadedSounds[parsedSound.url] = loadedSound;
  20967. }
  20968. else {
  20969. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20970. }
  20971. }
  20972. else {
  20973. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20974. }
  20975. }
  20976. }
  20977. loadedSounds = [];
  20978. // Connect parents & children and parse actions
  20979. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20980. var mesh = scene.meshes[index];
  20981. if (mesh._waitingParentId) {
  20982. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20983. mesh._waitingParentId = undefined;
  20984. }
  20985. if (mesh._waitingActions) {
  20986. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20987. mesh._waitingActions = undefined;
  20988. }
  20989. }
  20990. // freeze world matrix application
  20991. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20992. var currentMesh = scene.meshes[index];
  20993. if (currentMesh._waitingFreezeWorldMatrix) {
  20994. currentMesh.freezeWorldMatrix();
  20995. currentMesh._waitingFreezeWorldMatrix = undefined;
  20996. }
  20997. else {
  20998. currentMesh.computeWorldMatrix(true);
  20999. }
  21000. }
  21001. // Particles Systems
  21002. if (parsedData.particleSystems) {
  21003. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21004. var parsedParticleSystem = parsedData.particleSystems[index];
  21005. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21006. }
  21007. }
  21008. // Lens flares
  21009. if (parsedData.lensFlareSystems) {
  21010. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21011. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21012. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21013. }
  21014. }
  21015. // Shadows
  21016. if (parsedData.shadowGenerators) {
  21017. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21018. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21019. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21020. }
  21021. }
  21022. // Actions (scene)
  21023. if (parsedData.actions) {
  21024. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21025. }
  21026. // Finish
  21027. return true;
  21028. }
  21029. });
  21030. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21031. })(BABYLON || (BABYLON = {}));
  21032. var BABYLON;
  21033. (function (BABYLON) {
  21034. var SpriteManager = (function () {
  21035. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21037. this.name = name;
  21038. this.cellSize = cellSize;
  21039. this.sprites = new Array();
  21040. this.renderingGroupId = 0;
  21041. this.layerMask = 0x0FFFFFFF;
  21042. this.fogEnabled = true;
  21043. this.isPickable = false;
  21044. this._vertexDeclaration = [4, 4, 4, 4];
  21045. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21046. this._capacity = capacity;
  21047. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21048. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21049. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21050. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21051. this._scene = scene;
  21052. this._scene.spriteManagers.push(this);
  21053. // VBO
  21054. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21055. var indices = [];
  21056. var index = 0;
  21057. for (var count = 0; count < capacity; count++) {
  21058. indices.push(index);
  21059. indices.push(index + 1);
  21060. indices.push(index + 2);
  21061. indices.push(index);
  21062. indices.push(index + 2);
  21063. indices.push(index + 3);
  21064. index += 4;
  21065. }
  21066. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21067. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21068. // Effects
  21069. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21070. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21071. }
  21072. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21073. var arrayOffset = index * 16;
  21074. if (offsetX === 0)
  21075. offsetX = this._epsilon;
  21076. else if (offsetX === 1)
  21077. offsetX = 1 - this._epsilon;
  21078. if (offsetY === 0)
  21079. offsetY = this._epsilon;
  21080. else if (offsetY === 1)
  21081. offsetY = 1 - this._epsilon;
  21082. this._vertices[arrayOffset] = sprite.position.x;
  21083. this._vertices[arrayOffset + 1] = sprite.position.y;
  21084. this._vertices[arrayOffset + 2] = sprite.position.z;
  21085. this._vertices[arrayOffset + 3] = sprite.angle;
  21086. this._vertices[arrayOffset + 4] = sprite.width;
  21087. this._vertices[arrayOffset + 5] = sprite.height;
  21088. this._vertices[arrayOffset + 6] = offsetX;
  21089. this._vertices[arrayOffset + 7] = offsetY;
  21090. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21091. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21092. var offset = (sprite.cellIndex / rowSize) >> 0;
  21093. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21094. this._vertices[arrayOffset + 11] = offset;
  21095. // Color
  21096. this._vertices[arrayOffset + 12] = sprite.color.r;
  21097. this._vertices[arrayOffset + 13] = sprite.color.g;
  21098. this._vertices[arrayOffset + 14] = sprite.color.b;
  21099. this._vertices[arrayOffset + 15] = sprite.color.a;
  21100. };
  21101. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21102. var count = Math.min(this._capacity, this.sprites.length);
  21103. var min = BABYLON.Vector3.Zero();
  21104. var max = BABYLON.Vector3.Zero();
  21105. var distance = Number.MAX_VALUE;
  21106. var currentSprite;
  21107. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21108. var cameraView = camera.getViewMatrix();
  21109. for (var index = 0; index < count; index++) {
  21110. var sprite = this.sprites[index];
  21111. if (!sprite) {
  21112. continue;
  21113. }
  21114. if (predicate) {
  21115. if (!predicate(sprite)) {
  21116. continue;
  21117. }
  21118. }
  21119. else if (!sprite.isPickable) {
  21120. continue;
  21121. }
  21122. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21123. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21124. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21125. if (ray.intersectsBoxMinMax(min, max)) {
  21126. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21127. if (distance > currentDistance) {
  21128. distance = currentDistance;
  21129. currentSprite = sprite;
  21130. if (fastCheck) {
  21131. break;
  21132. }
  21133. }
  21134. }
  21135. }
  21136. if (currentSprite) {
  21137. var result = new BABYLON.PickingInfo();
  21138. result.hit = true;
  21139. result.pickedSprite = currentSprite;
  21140. result.distance = distance;
  21141. return result;
  21142. }
  21143. return null;
  21144. };
  21145. SpriteManager.prototype.render = function () {
  21146. // Check
  21147. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21148. return;
  21149. var engine = this._scene.getEngine();
  21150. var baseSize = this._spriteTexture.getBaseSize();
  21151. // Sprites
  21152. var deltaTime = engine.getDeltaTime();
  21153. var max = Math.min(this._capacity, this.sprites.length);
  21154. var rowSize = baseSize.width / this.cellSize;
  21155. var offset = 0;
  21156. for (var index = 0; index < max; index++) {
  21157. var sprite = this.sprites[index];
  21158. if (!sprite) {
  21159. continue;
  21160. }
  21161. sprite._animate(deltaTime);
  21162. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21163. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21164. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21165. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21166. }
  21167. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21168. // Render
  21169. var effect = this._effectBase;
  21170. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21171. effect = this._effectFog;
  21172. }
  21173. engine.enableEffect(effect);
  21174. var viewMatrix = this._scene.getViewMatrix();
  21175. effect.setTexture("diffuseSampler", this._spriteTexture);
  21176. effect.setMatrix("view", viewMatrix);
  21177. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21178. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21179. // Fog
  21180. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21181. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21182. effect.setColor3("vFogColor", this._scene.fogColor);
  21183. }
  21184. // VBOs
  21185. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21186. // Draw order
  21187. engine.setDepthFunctionToLessOrEqual();
  21188. effect.setBool("alphaTest", true);
  21189. engine.setColorWrite(false);
  21190. engine.draw(true, 0, max * 6);
  21191. engine.setColorWrite(true);
  21192. effect.setBool("alphaTest", false);
  21193. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21194. engine.draw(true, 0, max * 6);
  21195. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21196. };
  21197. SpriteManager.prototype.dispose = function () {
  21198. if (this._vertexBuffer) {
  21199. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21200. this._vertexBuffer = null;
  21201. }
  21202. if (this._indexBuffer) {
  21203. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21204. this._indexBuffer = null;
  21205. }
  21206. if (this._spriteTexture) {
  21207. this._spriteTexture.dispose();
  21208. this._spriteTexture = null;
  21209. }
  21210. // Remove from scene
  21211. var index = this._scene.spriteManagers.indexOf(this);
  21212. this._scene.spriteManagers.splice(index, 1);
  21213. // Callback
  21214. if (this.onDispose) {
  21215. this.onDispose();
  21216. }
  21217. };
  21218. return SpriteManager;
  21219. })();
  21220. BABYLON.SpriteManager = SpriteManager;
  21221. })(BABYLON || (BABYLON = {}));
  21222. var BABYLON;
  21223. (function (BABYLON) {
  21224. var Sprite = (function () {
  21225. function Sprite(name, manager) {
  21226. this.name = name;
  21227. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21228. this.width = 1.0;
  21229. this.height = 1.0;
  21230. this.angle = 0;
  21231. this.cellIndex = 0;
  21232. this.invertU = 0;
  21233. this.invertV = 0;
  21234. this.animations = new Array();
  21235. this.isPickable = false;
  21236. this._animationStarted = false;
  21237. this._loopAnimation = false;
  21238. this._fromIndex = 0;
  21239. this._toIndex = 0;
  21240. this._delay = 0;
  21241. this._direction = 1;
  21242. this._frameCount = 0;
  21243. this._time = 0;
  21244. this._manager = manager;
  21245. this._manager.sprites.push(this);
  21246. this.position = BABYLON.Vector3.Zero();
  21247. }
  21248. Object.defineProperty(Sprite.prototype, "size", {
  21249. get: function () {
  21250. return this.width;
  21251. },
  21252. set: function (value) {
  21253. this.width = value;
  21254. this.height = value;
  21255. },
  21256. enumerable: true,
  21257. configurable: true
  21258. });
  21259. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21260. this._fromIndex = from;
  21261. this._toIndex = to;
  21262. this._loopAnimation = loop;
  21263. this._delay = delay;
  21264. this._animationStarted = true;
  21265. this._direction = from < to ? 1 : -1;
  21266. this.cellIndex = from;
  21267. this._time = 0;
  21268. };
  21269. Sprite.prototype.stopAnimation = function () {
  21270. this._animationStarted = false;
  21271. };
  21272. Sprite.prototype._animate = function (deltaTime) {
  21273. if (!this._animationStarted)
  21274. return;
  21275. this._time += deltaTime;
  21276. if (this._time > this._delay) {
  21277. this._time = this._time % this._delay;
  21278. this.cellIndex += this._direction;
  21279. if (this.cellIndex == this._toIndex) {
  21280. if (this._loopAnimation) {
  21281. this.cellIndex = this._fromIndex;
  21282. }
  21283. else {
  21284. this._animationStarted = false;
  21285. if (this.disposeWhenFinishedAnimating) {
  21286. this.dispose();
  21287. }
  21288. }
  21289. }
  21290. }
  21291. };
  21292. Sprite.prototype.dispose = function () {
  21293. for (var i = 0; i < this._manager.sprites.length; i++) {
  21294. if (this._manager.sprites[i] == this) {
  21295. this._manager.sprites.splice(i, 1);
  21296. }
  21297. }
  21298. };
  21299. return Sprite;
  21300. })();
  21301. BABYLON.Sprite = Sprite;
  21302. })(BABYLON || (BABYLON = {}));
  21303. var BABYLON;
  21304. (function (BABYLON) {
  21305. var Layer = (function () {
  21306. function Layer(name, imgUrl, scene, isBackground, color) {
  21307. this.name = name;
  21308. this.scale = new BABYLON.Vector2(1, 1);
  21309. this.offset = new BABYLON.Vector2(0, 0);
  21310. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21311. this._vertexDeclaration = [2];
  21312. this._vertexStrideSize = 2 * 4;
  21313. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21314. this.isBackground = isBackground === undefined ? true : isBackground;
  21315. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21316. this._scene = scene;
  21317. this._scene.layers.push(this);
  21318. // VBO
  21319. var vertices = [];
  21320. vertices.push(1, 1);
  21321. vertices.push(-1, 1);
  21322. vertices.push(-1, -1);
  21323. vertices.push(1, -1);
  21324. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21325. // Indices
  21326. var indices = [];
  21327. indices.push(0);
  21328. indices.push(1);
  21329. indices.push(2);
  21330. indices.push(0);
  21331. indices.push(2);
  21332. indices.push(3);
  21333. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21334. // Effects
  21335. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21336. }
  21337. Layer.prototype.render = function () {
  21338. // Check
  21339. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21340. return;
  21341. var engine = this._scene.getEngine();
  21342. // Render
  21343. engine.enableEffect(this._effect);
  21344. engine.setState(false);
  21345. // Texture
  21346. this._effect.setTexture("textureSampler", this.texture);
  21347. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21348. // Color
  21349. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21350. // Scale / offset
  21351. this._effect.setVector2("offset", this.offset);
  21352. this._effect.setVector2("scale", this.scale);
  21353. // VBOs
  21354. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21355. // Draw order
  21356. engine.setAlphaMode(this.alphaBlendingMode);
  21357. engine.draw(true, 0, 6);
  21358. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21359. };
  21360. Layer.prototype.dispose = function () {
  21361. if (this._vertexBuffer) {
  21362. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21363. this._vertexBuffer = null;
  21364. }
  21365. if (this._indexBuffer) {
  21366. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21367. this._indexBuffer = null;
  21368. }
  21369. if (this.texture) {
  21370. this.texture.dispose();
  21371. this.texture = null;
  21372. }
  21373. // Remove from scene
  21374. var index = this._scene.layers.indexOf(this);
  21375. this._scene.layers.splice(index, 1);
  21376. // Callback
  21377. if (this.onDispose) {
  21378. this.onDispose();
  21379. }
  21380. };
  21381. return Layer;
  21382. })();
  21383. BABYLON.Layer = Layer;
  21384. })(BABYLON || (BABYLON = {}));
  21385. var BABYLON;
  21386. (function (BABYLON) {
  21387. var Particle = (function () {
  21388. function Particle() {
  21389. this.position = BABYLON.Vector3.Zero();
  21390. this.direction = BABYLON.Vector3.Zero();
  21391. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21392. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21393. this.lifeTime = 1.0;
  21394. this.age = 0;
  21395. this.size = 0;
  21396. this.angle = 0;
  21397. this.angularSpeed = 0;
  21398. }
  21399. Particle.prototype.copyTo = function (other) {
  21400. other.position.copyFrom(this.position);
  21401. other.direction.copyFrom(this.direction);
  21402. other.color.copyFrom(this.color);
  21403. other.colorStep.copyFrom(this.colorStep);
  21404. other.lifeTime = this.lifeTime;
  21405. other.age = this.age;
  21406. other.size = this.size;
  21407. other.angle = this.angle;
  21408. other.angularSpeed = this.angularSpeed;
  21409. };
  21410. return Particle;
  21411. })();
  21412. BABYLON.Particle = Particle;
  21413. })(BABYLON || (BABYLON = {}));
  21414. var BABYLON;
  21415. (function (BABYLON) {
  21416. var randomNumber = function (min, max) {
  21417. if (min === max) {
  21418. return (min);
  21419. }
  21420. var random = Math.random();
  21421. return ((random * (max - min)) + min);
  21422. };
  21423. var ParticleSystem = (function () {
  21424. function ParticleSystem(name, capacity, scene, customEffect) {
  21425. var _this = this;
  21426. this.name = name;
  21427. this.renderingGroupId = 0;
  21428. this.emitter = null;
  21429. this.emitRate = 10;
  21430. this.manualEmitCount = -1;
  21431. this.updateSpeed = 0.01;
  21432. this.targetStopDuration = 0;
  21433. this.disposeOnStop = false;
  21434. this.minEmitPower = 1;
  21435. this.maxEmitPower = 1;
  21436. this.minLifeTime = 1;
  21437. this.maxLifeTime = 1;
  21438. this.minSize = 1;
  21439. this.maxSize = 1;
  21440. this.minAngularSpeed = 0;
  21441. this.maxAngularSpeed = 0;
  21442. this.layerMask = 0x0FFFFFFF;
  21443. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21444. this.forceDepthWrite = false;
  21445. this.gravity = BABYLON.Vector3.Zero();
  21446. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21447. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21448. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21449. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21450. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21451. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21452. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21453. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21454. this.particles = new Array();
  21455. this._vertexDeclaration = [3, 4, 4];
  21456. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21457. this._stockParticles = new Array();
  21458. this._newPartsExcess = 0;
  21459. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21460. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21461. this._scaledDirection = BABYLON.Vector3.Zero();
  21462. this._scaledGravity = BABYLON.Vector3.Zero();
  21463. this._currentRenderId = -1;
  21464. this._started = false;
  21465. this._stopped = false;
  21466. this._actualFrame = 0;
  21467. this.id = name;
  21468. this._capacity = capacity;
  21469. this._scene = scene;
  21470. this._customEffect = customEffect;
  21471. scene.particleSystems.push(this);
  21472. // VBO
  21473. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21474. var indices = [];
  21475. var index = 0;
  21476. for (var count = 0; count < capacity; count++) {
  21477. indices.push(index);
  21478. indices.push(index + 1);
  21479. indices.push(index + 2);
  21480. indices.push(index);
  21481. indices.push(index + 2);
  21482. indices.push(index + 3);
  21483. index += 4;
  21484. }
  21485. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21486. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21487. // Default behaviors
  21488. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21489. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21490. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21491. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21492. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21493. };
  21494. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21495. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21496. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21497. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21498. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21499. };
  21500. this.updateFunction = function (particles) {
  21501. for (var index = 0; index < particles.length; index++) {
  21502. var particle = particles[index];
  21503. particle.age += _this._scaledUpdateSpeed;
  21504. if (particle.age >= particle.lifeTime) {
  21505. _this.recycleParticle(particle);
  21506. index--;
  21507. continue;
  21508. }
  21509. else {
  21510. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21511. particle.color.addInPlace(_this._scaledColorStep);
  21512. if (particle.color.a < 0)
  21513. particle.color.a = 0;
  21514. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21515. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21516. particle.position.addInPlace(_this._scaledDirection);
  21517. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21518. particle.direction.addInPlace(_this._scaledGravity);
  21519. }
  21520. }
  21521. };
  21522. }
  21523. ParticleSystem.prototype.recycleParticle = function (particle) {
  21524. var lastParticle = this.particles.pop();
  21525. if (lastParticle !== particle) {
  21526. lastParticle.copyTo(particle);
  21527. this._stockParticles.push(lastParticle);
  21528. }
  21529. };
  21530. ParticleSystem.prototype.getCapacity = function () {
  21531. return this._capacity;
  21532. };
  21533. ParticleSystem.prototype.isAlive = function () {
  21534. return this._alive;
  21535. };
  21536. ParticleSystem.prototype.isStarted = function () {
  21537. return this._started;
  21538. };
  21539. ParticleSystem.prototype.start = function () {
  21540. this._started = true;
  21541. this._stopped = false;
  21542. this._actualFrame = 0;
  21543. };
  21544. ParticleSystem.prototype.stop = function () {
  21545. this._stopped = true;
  21546. };
  21547. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21548. var offset = index * 11;
  21549. this._vertices[offset] = particle.position.x;
  21550. this._vertices[offset + 1] = particle.position.y;
  21551. this._vertices[offset + 2] = particle.position.z;
  21552. this._vertices[offset + 3] = particle.color.r;
  21553. this._vertices[offset + 4] = particle.color.g;
  21554. this._vertices[offset + 5] = particle.color.b;
  21555. this._vertices[offset + 6] = particle.color.a;
  21556. this._vertices[offset + 7] = particle.angle;
  21557. this._vertices[offset + 8] = particle.size;
  21558. this._vertices[offset + 9] = offsetX;
  21559. this._vertices[offset + 10] = offsetY;
  21560. };
  21561. ParticleSystem.prototype._update = function (newParticles) {
  21562. // Update current
  21563. this._alive = this.particles.length > 0;
  21564. this.updateFunction(this.particles);
  21565. // Add new ones
  21566. var worldMatrix;
  21567. if (this.emitter.position) {
  21568. worldMatrix = this.emitter.getWorldMatrix();
  21569. }
  21570. else {
  21571. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21572. }
  21573. var particle;
  21574. for (var index = 0; index < newParticles; index++) {
  21575. if (this.particles.length === this._capacity) {
  21576. break;
  21577. }
  21578. if (this._stockParticles.length !== 0) {
  21579. particle = this._stockParticles.pop();
  21580. particle.age = 0;
  21581. }
  21582. else {
  21583. particle = new BABYLON.Particle();
  21584. }
  21585. this.particles.push(particle);
  21586. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21587. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21588. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21589. particle.size = randomNumber(this.minSize, this.maxSize);
  21590. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21591. this.startPositionFunction(worldMatrix, particle.position, particle);
  21592. var step = randomNumber(0, 1.0);
  21593. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21594. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21595. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21596. }
  21597. };
  21598. ParticleSystem.prototype._getEffect = function () {
  21599. if (this._customEffect) {
  21600. return this._customEffect;
  21601. }
  21602. ;
  21603. var defines = [];
  21604. if (this._scene.clipPlane) {
  21605. defines.push("#define CLIPPLANE");
  21606. }
  21607. // Effect
  21608. var join = defines.join("\n");
  21609. if (this._cachedDefines !== join) {
  21610. this._cachedDefines = join;
  21611. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21612. }
  21613. return this._effect;
  21614. };
  21615. ParticleSystem.prototype.animate = function () {
  21616. if (!this._started)
  21617. return;
  21618. var effect = this._getEffect();
  21619. // Check
  21620. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21621. return;
  21622. if (this._currentRenderId === this._scene.getRenderId()) {
  21623. return;
  21624. }
  21625. this._currentRenderId = this._scene.getRenderId();
  21626. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21627. // determine the number of particles we need to create
  21628. var newParticles;
  21629. if (this.manualEmitCount > -1) {
  21630. newParticles = this.manualEmitCount;
  21631. this._newPartsExcess = 0;
  21632. this.manualEmitCount = 0;
  21633. }
  21634. else {
  21635. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21636. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21637. }
  21638. if (this._newPartsExcess > 1.0) {
  21639. newParticles += this._newPartsExcess >> 0;
  21640. this._newPartsExcess -= this._newPartsExcess >> 0;
  21641. }
  21642. this._alive = false;
  21643. if (!this._stopped) {
  21644. this._actualFrame += this._scaledUpdateSpeed;
  21645. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21646. this.stop();
  21647. }
  21648. else {
  21649. newParticles = 0;
  21650. }
  21651. this._update(newParticles);
  21652. // Stopped?
  21653. if (this._stopped) {
  21654. if (!this._alive) {
  21655. this._started = false;
  21656. if (this.disposeOnStop) {
  21657. this._scene._toBeDisposed.push(this);
  21658. }
  21659. }
  21660. }
  21661. // Update VBO
  21662. var offset = 0;
  21663. for (var index = 0; index < this.particles.length; index++) {
  21664. var particle = this.particles[index];
  21665. this._appendParticleVertex(offset++, particle, 0, 0);
  21666. this._appendParticleVertex(offset++, particle, 1, 0);
  21667. this._appendParticleVertex(offset++, particle, 1, 1);
  21668. this._appendParticleVertex(offset++, particle, 0, 1);
  21669. }
  21670. var engine = this._scene.getEngine();
  21671. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21672. };
  21673. ParticleSystem.prototype.render = function () {
  21674. var effect = this._getEffect();
  21675. // Check
  21676. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21677. return 0;
  21678. var engine = this._scene.getEngine();
  21679. // Render
  21680. engine.enableEffect(effect);
  21681. engine.setState(false);
  21682. var viewMatrix = this._scene.getViewMatrix();
  21683. effect.setTexture("diffuseSampler", this.particleTexture);
  21684. effect.setMatrix("view", viewMatrix);
  21685. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21686. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21687. if (this._scene.clipPlane) {
  21688. var clipPlane = this._scene.clipPlane;
  21689. var invView = viewMatrix.clone();
  21690. invView.invert();
  21691. effect.setMatrix("invView", invView);
  21692. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21693. }
  21694. // VBOs
  21695. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21696. // Draw order
  21697. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21698. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21699. }
  21700. else {
  21701. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21702. }
  21703. if (this.forceDepthWrite) {
  21704. engine.setDepthWrite(true);
  21705. }
  21706. engine.draw(true, 0, this.particles.length * 6);
  21707. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21708. return this.particles.length;
  21709. };
  21710. ParticleSystem.prototype.dispose = function () {
  21711. if (this._vertexBuffer) {
  21712. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21713. this._vertexBuffer = null;
  21714. }
  21715. if (this._indexBuffer) {
  21716. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21717. this._indexBuffer = null;
  21718. }
  21719. if (this.particleTexture) {
  21720. this.particleTexture.dispose();
  21721. this.particleTexture = null;
  21722. }
  21723. // Remove from scene
  21724. var index = this._scene.particleSystems.indexOf(this);
  21725. this._scene.particleSystems.splice(index, 1);
  21726. // Callback
  21727. if (this.onDispose) {
  21728. this.onDispose();
  21729. }
  21730. };
  21731. // Clone
  21732. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21733. var result = new ParticleSystem(name, this._capacity, this._scene);
  21734. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21735. if (newEmitter === undefined) {
  21736. newEmitter = this.emitter;
  21737. }
  21738. result.emitter = newEmitter;
  21739. if (this.particleTexture) {
  21740. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21741. }
  21742. result.start();
  21743. return result;
  21744. };
  21745. ParticleSystem.prototype.serialize = function () {
  21746. var serializationObject = {};
  21747. serializationObject.name = this.name;
  21748. if (this.emitter.position) {
  21749. serializationObject.emitterId = this.emitter.id;
  21750. }
  21751. else {
  21752. serializationObject.emitter = this.emitter.asArray();
  21753. ;
  21754. }
  21755. serializationObject.capacity = this.getCapacity();
  21756. if (this.particleTexture) {
  21757. serializationObject.textureName = this.particleTexture.name;
  21758. }
  21759. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21760. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21761. serializationObject.minSize = this.minSize;
  21762. serializationObject.maxSize = this.maxSize;
  21763. serializationObject.minEmitPower = this.minEmitPower;
  21764. serializationObject.maxEmitPower = this.maxEmitPower;
  21765. serializationObject.minLifeTime = this.minLifeTime;
  21766. serializationObject.maxLifeTime = this.maxLifeTime;
  21767. serializationObject.emitRate = this.emitRate;
  21768. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21769. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21770. serializationObject.gravity = this.gravity.asArray();
  21771. serializationObject.direction1 = this.direction1.asArray();
  21772. serializationObject.direction2 = this.direction2.asArray();
  21773. serializationObject.color1 = this.color1.asArray();
  21774. serializationObject.color2 = this.color2.asArray();
  21775. serializationObject.colorDead = this.colorDead.asArray();
  21776. serializationObject.updateSpeed = this.updateSpeed;
  21777. serializationObject.targetStopDuration = this.targetStopDuration;
  21778. serializationObject.textureMask = this.textureMask.asArray();
  21779. serializationObject.blendMode = this.blendMode;
  21780. return serializationObject;
  21781. };
  21782. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21783. var name = parsedParticleSystem.name;
  21784. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21785. if (parsedParticleSystem.textureName) {
  21786. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21787. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21788. }
  21789. if (parsedParticleSystem.emitterId) {
  21790. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21791. }
  21792. else {
  21793. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21794. }
  21795. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21796. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21797. particleSystem.minSize = parsedParticleSystem.minSize;
  21798. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21799. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21800. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21801. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21802. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21803. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21804. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21805. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21806. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21807. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21808. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21809. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21810. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21811. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21812. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21813. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21814. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21815. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21816. particleSystem.start();
  21817. return particleSystem;
  21818. };
  21819. // Statics
  21820. ParticleSystem.BLENDMODE_ONEONE = 0;
  21821. ParticleSystem.BLENDMODE_STANDARD = 1;
  21822. return ParticleSystem;
  21823. })();
  21824. BABYLON.ParticleSystem = ParticleSystem;
  21825. })(BABYLON || (BABYLON = {}));
  21826. var BABYLON;
  21827. (function (BABYLON) {
  21828. var AnimationRange = (function () {
  21829. function AnimationRange(name, from, to) {
  21830. this.name = name;
  21831. this.from = from;
  21832. this.to = to;
  21833. }
  21834. return AnimationRange;
  21835. })();
  21836. BABYLON.AnimationRange = AnimationRange;
  21837. /**
  21838. * Composed of a frame, and an action function
  21839. */
  21840. var AnimationEvent = (function () {
  21841. function AnimationEvent(frame, action, onlyOnce) {
  21842. this.frame = frame;
  21843. this.action = action;
  21844. this.onlyOnce = onlyOnce;
  21845. this.isDone = false;
  21846. }
  21847. return AnimationEvent;
  21848. })();
  21849. BABYLON.AnimationEvent = AnimationEvent;
  21850. var Animation = (function () {
  21851. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21852. this.name = name;
  21853. this.targetProperty = targetProperty;
  21854. this.framePerSecond = framePerSecond;
  21855. this.dataType = dataType;
  21856. this.loopMode = loopMode;
  21857. this._offsetsCache = {};
  21858. this._highLimitsCache = {};
  21859. this._stopped = false;
  21860. // The set of event that will be linked to this animation
  21861. this._events = new Array();
  21862. this.allowMatricesInterpolation = false;
  21863. this._ranges = {};
  21864. this.targetPropertyPath = targetProperty.split(".");
  21865. this.dataType = dataType;
  21866. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21867. }
  21868. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21869. var dataType = undefined;
  21870. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21871. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21872. }
  21873. else if (from instanceof BABYLON.Quaternion) {
  21874. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21875. }
  21876. else if (from instanceof BABYLON.Vector3) {
  21877. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21878. }
  21879. else if (from instanceof BABYLON.Vector2) {
  21880. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21881. }
  21882. else if (from instanceof BABYLON.Color3) {
  21883. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21884. }
  21885. if (dataType == undefined) {
  21886. return null;
  21887. }
  21888. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21889. var keys = [];
  21890. keys.push({ frame: 0, value: from });
  21891. keys.push({ frame: totalFrame, value: to });
  21892. animation.setKeys(keys);
  21893. if (easingFunction !== undefined) {
  21894. animation.setEasingFunction(easingFunction);
  21895. }
  21896. return animation;
  21897. };
  21898. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21899. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21900. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21901. };
  21902. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21903. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21904. node.animations.push(animation);
  21905. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21906. };
  21907. // Methods
  21908. /**
  21909. * Add an event to this animation.
  21910. */
  21911. Animation.prototype.addEvent = function (event) {
  21912. this._events.push(event);
  21913. };
  21914. /**
  21915. * Remove all events found at the given frame
  21916. * @param frame
  21917. */
  21918. Animation.prototype.removeEvents = function (frame) {
  21919. for (var index = 0; index < this._events.length; index++) {
  21920. if (this._events[index].frame === frame) {
  21921. this._events.splice(index, 1);
  21922. index--;
  21923. }
  21924. }
  21925. };
  21926. Animation.prototype.createRange = function (name, from, to) {
  21927. // check name not already in use; could happen for bones after serialized
  21928. if (!this._ranges[name]) {
  21929. this._ranges[name] = new AnimationRange(name, from, to);
  21930. }
  21931. };
  21932. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21933. if (deleteFrames === void 0) { deleteFrames = true; }
  21934. if (this._ranges[name]) {
  21935. if (deleteFrames) {
  21936. var from = this._ranges[name].from;
  21937. var to = this._ranges[name].to;
  21938. // this loop MUST go high to low for multiple splices to work
  21939. for (var key = this._keys.length - 1; key >= 0; key--) {
  21940. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21941. this._keys.splice(key, 1);
  21942. }
  21943. }
  21944. }
  21945. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21946. }
  21947. };
  21948. Animation.prototype.getRange = function (name) {
  21949. return this._ranges[name];
  21950. };
  21951. Animation.prototype.reset = function () {
  21952. this._offsetsCache = {};
  21953. this._highLimitsCache = {};
  21954. this.currentFrame = 0;
  21955. };
  21956. Animation.prototype.isStopped = function () {
  21957. return this._stopped;
  21958. };
  21959. Animation.prototype.getKeys = function () {
  21960. return this._keys;
  21961. };
  21962. Animation.prototype.getHighestFrame = function () {
  21963. var ret = 0;
  21964. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21965. if (ret < this._keys[key].frame) {
  21966. ret = this._keys[key].frame;
  21967. }
  21968. }
  21969. return ret;
  21970. };
  21971. Animation.prototype.getEasingFunction = function () {
  21972. return this._easingFunction;
  21973. };
  21974. Animation.prototype.setEasingFunction = function (easingFunction) {
  21975. this._easingFunction = easingFunction;
  21976. };
  21977. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21978. return startValue + (endValue - startValue) * gradient;
  21979. };
  21980. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21981. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21982. };
  21983. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21984. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21985. };
  21986. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21987. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21988. };
  21989. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21990. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21991. };
  21992. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21993. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21994. };
  21995. Animation.prototype.clone = function () {
  21996. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21997. if (this._keys) {
  21998. clone.setKeys(this._keys);
  21999. }
  22000. return clone;
  22001. };
  22002. Animation.prototype.setKeys = function (values) {
  22003. this._keys = values.slice(0);
  22004. this._offsetsCache = {};
  22005. this._highLimitsCache = {};
  22006. };
  22007. Animation.prototype._getKeyValue = function (value) {
  22008. if (typeof value === "function") {
  22009. return value();
  22010. }
  22011. return value;
  22012. };
  22013. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22014. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22015. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22016. }
  22017. this.currentFrame = currentFrame;
  22018. // Try to get a hash to find the right key
  22019. 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));
  22020. if (this._keys[startKey].frame >= currentFrame) {
  22021. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22022. startKey--;
  22023. }
  22024. }
  22025. for (var key = startKey; key < this._keys.length; key++) {
  22026. if (this._keys[key + 1].frame >= currentFrame) {
  22027. var startValue = this._getKeyValue(this._keys[key].value);
  22028. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22029. // gradient : percent of currentFrame between the frame inf and the frame sup
  22030. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22031. // check for easingFunction and correction of gradient
  22032. if (this._easingFunction != null) {
  22033. gradient = this._easingFunction.ease(gradient);
  22034. }
  22035. switch (this.dataType) {
  22036. // Float
  22037. case Animation.ANIMATIONTYPE_FLOAT:
  22038. switch (loopMode) {
  22039. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22040. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22041. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22042. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22043. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22044. }
  22045. break;
  22046. // Quaternion
  22047. case Animation.ANIMATIONTYPE_QUATERNION:
  22048. var quaternion = null;
  22049. switch (loopMode) {
  22050. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22051. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22052. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22053. break;
  22054. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22055. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22056. break;
  22057. }
  22058. return quaternion;
  22059. // Vector3
  22060. case Animation.ANIMATIONTYPE_VECTOR3:
  22061. switch (loopMode) {
  22062. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22063. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22064. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22065. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22066. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22067. }
  22068. // Vector2
  22069. case Animation.ANIMATIONTYPE_VECTOR2:
  22070. switch (loopMode) {
  22071. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22072. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22073. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22074. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22075. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22076. }
  22077. // Color3
  22078. case Animation.ANIMATIONTYPE_COLOR3:
  22079. switch (loopMode) {
  22080. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22081. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22082. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22083. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22084. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22085. }
  22086. // Matrix
  22087. case Animation.ANIMATIONTYPE_MATRIX:
  22088. switch (loopMode) {
  22089. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22090. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22091. if (this.allowMatricesInterpolation) {
  22092. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22093. }
  22094. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22095. return startValue;
  22096. }
  22097. default:
  22098. break;
  22099. }
  22100. break;
  22101. }
  22102. }
  22103. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22104. };
  22105. Animation.prototype.setValue = function (currentValue) {
  22106. // Set value
  22107. if (this.targetPropertyPath.length > 1) {
  22108. var property = this._target[this.targetPropertyPath[0]];
  22109. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22110. property = property[this.targetPropertyPath[index]];
  22111. }
  22112. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22113. }
  22114. else {
  22115. this._target[this.targetPropertyPath[0]] = currentValue;
  22116. }
  22117. if (this._target.markAsDirty) {
  22118. this._target.markAsDirty(this.targetProperty);
  22119. }
  22120. };
  22121. Animation.prototype.goToFrame = function (frame) {
  22122. if (frame < this._keys[0].frame) {
  22123. frame = this._keys[0].frame;
  22124. }
  22125. else if (frame > this._keys[this._keys.length - 1].frame) {
  22126. frame = this._keys[this._keys.length - 1].frame;
  22127. }
  22128. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22129. this.setValue(currentValue);
  22130. };
  22131. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22132. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22133. this._stopped = true;
  22134. return false;
  22135. }
  22136. var returnValue = true;
  22137. // Adding a start key at frame 0 if missing
  22138. if (this._keys[0].frame !== 0) {
  22139. var newKey = { frame: 0, value: this._keys[0].value };
  22140. this._keys.splice(0, 0, newKey);
  22141. }
  22142. // Check limits
  22143. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22144. from = this._keys[0].frame;
  22145. }
  22146. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22147. to = this._keys[this._keys.length - 1].frame;
  22148. }
  22149. // Compute ratio
  22150. var range = to - from;
  22151. var offsetValue;
  22152. // ratio represents the frame delta between from and to
  22153. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22154. var highLimitValue = 0;
  22155. if (ratio > range && !loop) {
  22156. returnValue = false;
  22157. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22158. }
  22159. else {
  22160. // Get max value if required
  22161. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22162. var keyOffset = to.toString() + from.toString();
  22163. if (!this._offsetsCache[keyOffset]) {
  22164. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22165. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22166. switch (this.dataType) {
  22167. // Float
  22168. case Animation.ANIMATIONTYPE_FLOAT:
  22169. this._offsetsCache[keyOffset] = toValue - fromValue;
  22170. break;
  22171. // Quaternion
  22172. case Animation.ANIMATIONTYPE_QUATERNION:
  22173. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22174. break;
  22175. // Vector3
  22176. case Animation.ANIMATIONTYPE_VECTOR3:
  22177. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22178. // Vector2
  22179. case Animation.ANIMATIONTYPE_VECTOR2:
  22180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22181. // Color3
  22182. case Animation.ANIMATIONTYPE_COLOR3:
  22183. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22184. default:
  22185. break;
  22186. }
  22187. this._highLimitsCache[keyOffset] = toValue;
  22188. }
  22189. highLimitValue = this._highLimitsCache[keyOffset];
  22190. offsetValue = this._offsetsCache[keyOffset];
  22191. }
  22192. }
  22193. if (offsetValue === undefined) {
  22194. switch (this.dataType) {
  22195. // Float
  22196. case Animation.ANIMATIONTYPE_FLOAT:
  22197. offsetValue = 0;
  22198. break;
  22199. // Quaternion
  22200. case Animation.ANIMATIONTYPE_QUATERNION:
  22201. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22202. break;
  22203. // Vector3
  22204. case Animation.ANIMATIONTYPE_VECTOR3:
  22205. offsetValue = BABYLON.Vector3.Zero();
  22206. break;
  22207. // Vector2
  22208. case Animation.ANIMATIONTYPE_VECTOR2:
  22209. offsetValue = BABYLON.Vector2.Zero();
  22210. break;
  22211. // Color3
  22212. case Animation.ANIMATIONTYPE_COLOR3:
  22213. offsetValue = BABYLON.Color3.Black();
  22214. }
  22215. }
  22216. // Compute value
  22217. var repeatCount = (ratio / range) >> 0;
  22218. var currentFrame = returnValue ? from + ratio % range : to;
  22219. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22220. // Set value
  22221. this.setValue(currentValue);
  22222. // Check events
  22223. for (var index = 0; index < this._events.length; index++) {
  22224. if (currentFrame >= this._events[index].frame) {
  22225. var event = this._events[index];
  22226. if (!event.isDone) {
  22227. // If event should be done only once, remove it.
  22228. if (event.onlyOnce) {
  22229. this._events.splice(index, 1);
  22230. index--;
  22231. }
  22232. event.isDone = true;
  22233. event.action();
  22234. } // Don't do anything if the event has already be done.
  22235. }
  22236. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22237. // reset event, the animation is looping
  22238. this._events[index].isDone = false;
  22239. }
  22240. }
  22241. if (!returnValue) {
  22242. this._stopped = true;
  22243. }
  22244. return returnValue;
  22245. };
  22246. Animation.prototype.serialize = function () {
  22247. var serializationObject = {};
  22248. serializationObject.name = this.name;
  22249. serializationObject.property = this.targetProperty;
  22250. serializationObject.framePerSecond = this.framePerSecond;
  22251. serializationObject.dataType = this.dataType;
  22252. serializationObject.loopBehavior = this.loopMode;
  22253. var dataType = this.dataType;
  22254. serializationObject.keys = [];
  22255. var keys = this.getKeys();
  22256. for (var index = 0; index < keys.length; index++) {
  22257. var animationKey = keys[index];
  22258. var key = {};
  22259. key.frame = animationKey.frame;
  22260. switch (dataType) {
  22261. case Animation.ANIMATIONTYPE_FLOAT:
  22262. key.values = [animationKey.value];
  22263. break;
  22264. case Animation.ANIMATIONTYPE_QUATERNION:
  22265. case Animation.ANIMATIONTYPE_MATRIX:
  22266. case Animation.ANIMATIONTYPE_VECTOR3:
  22267. case Animation.ANIMATIONTYPE_COLOR3:
  22268. key.values = animationKey.value.asArray();
  22269. break;
  22270. }
  22271. serializationObject.keys.push(key);
  22272. }
  22273. serializationObject.ranges = [];
  22274. for (var name in this._ranges) {
  22275. var range = {};
  22276. range.name = name;
  22277. range.from = this._ranges[name].from;
  22278. range.to = this._ranges[name].to;
  22279. serializationObject.ranges.push(range);
  22280. }
  22281. return serializationObject;
  22282. };
  22283. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22284. get: function () {
  22285. return Animation._ANIMATIONTYPE_FLOAT;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22291. get: function () {
  22292. return Animation._ANIMATIONTYPE_VECTOR3;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22298. get: function () {
  22299. return Animation._ANIMATIONTYPE_VECTOR2;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22305. get: function () {
  22306. return Animation._ANIMATIONTYPE_QUATERNION;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22312. get: function () {
  22313. return Animation._ANIMATIONTYPE_MATRIX;
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22319. get: function () {
  22320. return Animation._ANIMATIONTYPE_COLOR3;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22326. get: function () {
  22327. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22333. get: function () {
  22334. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22340. get: function () {
  22341. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. Animation.Parse = function (parsedAnimation) {
  22347. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22348. var dataType = parsedAnimation.dataType;
  22349. var keys = [];
  22350. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22351. var key = parsedAnimation.keys[index];
  22352. var data;
  22353. switch (dataType) {
  22354. case Animation.ANIMATIONTYPE_FLOAT:
  22355. data = key.values[0];
  22356. break;
  22357. case Animation.ANIMATIONTYPE_QUATERNION:
  22358. data = BABYLON.Quaternion.FromArray(key.values);
  22359. break;
  22360. case Animation.ANIMATIONTYPE_MATRIX:
  22361. data = BABYLON.Matrix.FromArray(key.values);
  22362. break;
  22363. case Animation.ANIMATIONTYPE_COLOR3:
  22364. data = BABYLON.Color3.FromArray(key.values);
  22365. break;
  22366. case Animation.ANIMATIONTYPE_VECTOR3:
  22367. default:
  22368. data = BABYLON.Vector3.FromArray(key.values);
  22369. break;
  22370. }
  22371. keys.push({
  22372. frame: key.frame,
  22373. value: data
  22374. });
  22375. }
  22376. animation.setKeys(keys);
  22377. if (parsedAnimation.ranges) {
  22378. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22379. data = parsedAnimation.ranges[index];
  22380. animation.createRange(data.name, data.from, data.to);
  22381. }
  22382. }
  22383. return animation;
  22384. };
  22385. Animation.AppendSerializedAnimations = function (source, destination) {
  22386. if (source.animations) {
  22387. destination.animations = [];
  22388. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22389. var animation = source.animations[animationIndex];
  22390. destination.animations.push(animation.serialize());
  22391. }
  22392. }
  22393. };
  22394. // Statics
  22395. Animation._ANIMATIONTYPE_FLOAT = 0;
  22396. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22397. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22398. Animation._ANIMATIONTYPE_MATRIX = 3;
  22399. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22400. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22401. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22402. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22403. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22404. return Animation;
  22405. })();
  22406. BABYLON.Animation = Animation;
  22407. })(BABYLON || (BABYLON = {}));
  22408. var BABYLON;
  22409. (function (BABYLON) {
  22410. var Animatable = (function () {
  22411. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22412. if (fromFrame === void 0) { fromFrame = 0; }
  22413. if (toFrame === void 0) { toFrame = 100; }
  22414. if (loopAnimation === void 0) { loopAnimation = false; }
  22415. if (speedRatio === void 0) { speedRatio = 1.0; }
  22416. this.target = target;
  22417. this.fromFrame = fromFrame;
  22418. this.toFrame = toFrame;
  22419. this.loopAnimation = loopAnimation;
  22420. this.speedRatio = speedRatio;
  22421. this.onAnimationEnd = onAnimationEnd;
  22422. this._animations = new Array();
  22423. this._paused = false;
  22424. this.animationStarted = false;
  22425. if (animations) {
  22426. this.appendAnimations(target, animations);
  22427. }
  22428. this._scene = scene;
  22429. scene._activeAnimatables.push(this);
  22430. }
  22431. // Methods
  22432. Animatable.prototype.getAnimations = function () {
  22433. return this._animations;
  22434. };
  22435. Animatable.prototype.appendAnimations = function (target, animations) {
  22436. for (var index = 0; index < animations.length; index++) {
  22437. var animation = animations[index];
  22438. animation._target = target;
  22439. this._animations.push(animation);
  22440. }
  22441. };
  22442. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22443. var animations = this._animations;
  22444. for (var index = 0; index < animations.length; index++) {
  22445. if (animations[index].targetProperty === property) {
  22446. return animations[index];
  22447. }
  22448. }
  22449. return null;
  22450. };
  22451. Animatable.prototype.reset = function () {
  22452. var animations = this._animations;
  22453. for (var index = 0; index < animations.length; index++) {
  22454. animations[index].reset();
  22455. }
  22456. this._localDelayOffset = null;
  22457. this._pausedDelay = null;
  22458. };
  22459. Animatable.prototype.goToFrame = function (frame) {
  22460. var animations = this._animations;
  22461. for (var index = 0; index < animations.length; index++) {
  22462. animations[index].goToFrame(frame);
  22463. }
  22464. };
  22465. Animatable.prototype.pause = function () {
  22466. if (this._paused) {
  22467. return;
  22468. }
  22469. this._paused = true;
  22470. };
  22471. Animatable.prototype.restart = function () {
  22472. this._paused = false;
  22473. };
  22474. Animatable.prototype.stop = function () {
  22475. var index = this._scene._activeAnimatables.indexOf(this);
  22476. if (index > -1) {
  22477. this._scene._activeAnimatables.splice(index, 1);
  22478. }
  22479. if (this.onAnimationEnd) {
  22480. this.onAnimationEnd();
  22481. }
  22482. };
  22483. Animatable.prototype._animate = function (delay) {
  22484. if (this._paused) {
  22485. this.animationStarted = false;
  22486. if (!this._pausedDelay) {
  22487. this._pausedDelay = delay;
  22488. }
  22489. return true;
  22490. }
  22491. if (!this._localDelayOffset) {
  22492. this._localDelayOffset = delay;
  22493. }
  22494. else if (this._pausedDelay) {
  22495. this._localDelayOffset += delay - this._pausedDelay;
  22496. this._pausedDelay = null;
  22497. }
  22498. // Animating
  22499. var running = false;
  22500. var animations = this._animations;
  22501. var index;
  22502. for (index = 0; index < animations.length; index++) {
  22503. var animation = animations[index];
  22504. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22505. running = running || isRunning;
  22506. }
  22507. this.animationStarted = running;
  22508. if (!running) {
  22509. // Remove from active animatables
  22510. index = this._scene._activeAnimatables.indexOf(this);
  22511. this._scene._activeAnimatables.splice(index, 1);
  22512. }
  22513. if (!running && this.onAnimationEnd) {
  22514. this.onAnimationEnd();
  22515. }
  22516. return running;
  22517. };
  22518. return Animatable;
  22519. })();
  22520. BABYLON.Animatable = Animatable;
  22521. })(BABYLON || (BABYLON = {}));
  22522. var BABYLON;
  22523. (function (BABYLON) {
  22524. var EasingFunction = (function () {
  22525. function EasingFunction() {
  22526. // Properties
  22527. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22528. }
  22529. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22530. get: function () {
  22531. return EasingFunction._EASINGMODE_EASEIN;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22537. get: function () {
  22538. return EasingFunction._EASINGMODE_EASEOUT;
  22539. },
  22540. enumerable: true,
  22541. configurable: true
  22542. });
  22543. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22544. get: function () {
  22545. return EasingFunction._EASINGMODE_EASEINOUT;
  22546. },
  22547. enumerable: true,
  22548. configurable: true
  22549. });
  22550. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22551. var n = Math.min(Math.max(easingMode, 0), 2);
  22552. this._easingMode = n;
  22553. };
  22554. EasingFunction.prototype.getEasingMode = function () {
  22555. return this._easingMode;
  22556. };
  22557. EasingFunction.prototype.easeInCore = function (gradient) {
  22558. throw new Error('You must implement this method');
  22559. };
  22560. EasingFunction.prototype.ease = function (gradient) {
  22561. switch (this._easingMode) {
  22562. case EasingFunction.EASINGMODE_EASEIN:
  22563. return this.easeInCore(gradient);
  22564. case EasingFunction.EASINGMODE_EASEOUT:
  22565. return (1 - this.easeInCore(1 - gradient));
  22566. }
  22567. if (gradient >= 0.5) {
  22568. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22569. }
  22570. return (this.easeInCore(gradient * 2) * 0.5);
  22571. };
  22572. //Statics
  22573. EasingFunction._EASINGMODE_EASEIN = 0;
  22574. EasingFunction._EASINGMODE_EASEOUT = 1;
  22575. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22576. return EasingFunction;
  22577. })();
  22578. BABYLON.EasingFunction = EasingFunction;
  22579. var CircleEase = (function (_super) {
  22580. __extends(CircleEase, _super);
  22581. function CircleEase() {
  22582. _super.apply(this, arguments);
  22583. }
  22584. CircleEase.prototype.easeInCore = function (gradient) {
  22585. gradient = Math.max(0, Math.min(1, gradient));
  22586. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22587. };
  22588. return CircleEase;
  22589. })(EasingFunction);
  22590. BABYLON.CircleEase = CircleEase;
  22591. var BackEase = (function (_super) {
  22592. __extends(BackEase, _super);
  22593. function BackEase(amplitude) {
  22594. if (amplitude === void 0) { amplitude = 1; }
  22595. _super.call(this);
  22596. this.amplitude = amplitude;
  22597. }
  22598. BackEase.prototype.easeInCore = function (gradient) {
  22599. var num = Math.max(0, this.amplitude);
  22600. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22601. };
  22602. return BackEase;
  22603. })(EasingFunction);
  22604. BABYLON.BackEase = BackEase;
  22605. var BounceEase = (function (_super) {
  22606. __extends(BounceEase, _super);
  22607. function BounceEase(bounces, bounciness) {
  22608. if (bounces === void 0) { bounces = 3; }
  22609. if (bounciness === void 0) { bounciness = 2; }
  22610. _super.call(this);
  22611. this.bounces = bounces;
  22612. this.bounciness = bounciness;
  22613. }
  22614. BounceEase.prototype.easeInCore = function (gradient) {
  22615. var y = Math.max(0.0, this.bounces);
  22616. var bounciness = this.bounciness;
  22617. if (bounciness <= 1.0) {
  22618. bounciness = 1.001;
  22619. }
  22620. var num9 = Math.pow(bounciness, y);
  22621. var num5 = 1.0 - bounciness;
  22622. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22623. var num15 = gradient * num4;
  22624. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22625. var num3 = Math.floor(num65);
  22626. var num13 = num3 + 1.0;
  22627. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22628. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22629. var num7 = (num8 + num12) * 0.5;
  22630. var num6 = gradient - num7;
  22631. var num2 = num7 - num8;
  22632. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22633. };
  22634. return BounceEase;
  22635. })(EasingFunction);
  22636. BABYLON.BounceEase = BounceEase;
  22637. var CubicEase = (function (_super) {
  22638. __extends(CubicEase, _super);
  22639. function CubicEase() {
  22640. _super.apply(this, arguments);
  22641. }
  22642. CubicEase.prototype.easeInCore = function (gradient) {
  22643. return (gradient * gradient * gradient);
  22644. };
  22645. return CubicEase;
  22646. })(EasingFunction);
  22647. BABYLON.CubicEase = CubicEase;
  22648. var ElasticEase = (function (_super) {
  22649. __extends(ElasticEase, _super);
  22650. function ElasticEase(oscillations, springiness) {
  22651. if (oscillations === void 0) { oscillations = 3; }
  22652. if (springiness === void 0) { springiness = 3; }
  22653. _super.call(this);
  22654. this.oscillations = oscillations;
  22655. this.springiness = springiness;
  22656. }
  22657. ElasticEase.prototype.easeInCore = function (gradient) {
  22658. var num2;
  22659. var num3 = Math.max(0.0, this.oscillations);
  22660. var num = Math.max(0.0, this.springiness);
  22661. if (num == 0) {
  22662. num2 = gradient;
  22663. }
  22664. else {
  22665. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22666. }
  22667. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22668. };
  22669. return ElasticEase;
  22670. })(EasingFunction);
  22671. BABYLON.ElasticEase = ElasticEase;
  22672. var ExponentialEase = (function (_super) {
  22673. __extends(ExponentialEase, _super);
  22674. function ExponentialEase(exponent) {
  22675. if (exponent === void 0) { exponent = 2; }
  22676. _super.call(this);
  22677. this.exponent = exponent;
  22678. }
  22679. ExponentialEase.prototype.easeInCore = function (gradient) {
  22680. if (this.exponent <= 0) {
  22681. return gradient;
  22682. }
  22683. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22684. };
  22685. return ExponentialEase;
  22686. })(EasingFunction);
  22687. BABYLON.ExponentialEase = ExponentialEase;
  22688. var PowerEase = (function (_super) {
  22689. __extends(PowerEase, _super);
  22690. function PowerEase(power) {
  22691. if (power === void 0) { power = 2; }
  22692. _super.call(this);
  22693. this.power = power;
  22694. }
  22695. PowerEase.prototype.easeInCore = function (gradient) {
  22696. var y = Math.max(0.0, this.power);
  22697. return Math.pow(gradient, y);
  22698. };
  22699. return PowerEase;
  22700. })(EasingFunction);
  22701. BABYLON.PowerEase = PowerEase;
  22702. var QuadraticEase = (function (_super) {
  22703. __extends(QuadraticEase, _super);
  22704. function QuadraticEase() {
  22705. _super.apply(this, arguments);
  22706. }
  22707. QuadraticEase.prototype.easeInCore = function (gradient) {
  22708. return (gradient * gradient);
  22709. };
  22710. return QuadraticEase;
  22711. })(EasingFunction);
  22712. BABYLON.QuadraticEase = QuadraticEase;
  22713. var QuarticEase = (function (_super) {
  22714. __extends(QuarticEase, _super);
  22715. function QuarticEase() {
  22716. _super.apply(this, arguments);
  22717. }
  22718. QuarticEase.prototype.easeInCore = function (gradient) {
  22719. return (gradient * gradient * gradient * gradient);
  22720. };
  22721. return QuarticEase;
  22722. })(EasingFunction);
  22723. BABYLON.QuarticEase = QuarticEase;
  22724. var QuinticEase = (function (_super) {
  22725. __extends(QuinticEase, _super);
  22726. function QuinticEase() {
  22727. _super.apply(this, arguments);
  22728. }
  22729. QuinticEase.prototype.easeInCore = function (gradient) {
  22730. return (gradient * gradient * gradient * gradient * gradient);
  22731. };
  22732. return QuinticEase;
  22733. })(EasingFunction);
  22734. BABYLON.QuinticEase = QuinticEase;
  22735. var SineEase = (function (_super) {
  22736. __extends(SineEase, _super);
  22737. function SineEase() {
  22738. _super.apply(this, arguments);
  22739. }
  22740. SineEase.prototype.easeInCore = function (gradient) {
  22741. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22742. };
  22743. return SineEase;
  22744. })(EasingFunction);
  22745. BABYLON.SineEase = SineEase;
  22746. var BezierCurveEase = (function (_super) {
  22747. __extends(BezierCurveEase, _super);
  22748. function BezierCurveEase(x1, y1, x2, y2) {
  22749. if (x1 === void 0) { x1 = 0; }
  22750. if (y1 === void 0) { y1 = 0; }
  22751. if (x2 === void 0) { x2 = 1; }
  22752. if (y2 === void 0) { y2 = 1; }
  22753. _super.call(this);
  22754. this.x1 = x1;
  22755. this.y1 = y1;
  22756. this.x2 = x2;
  22757. this.y2 = y2;
  22758. }
  22759. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22760. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22761. };
  22762. return BezierCurveEase;
  22763. })(EasingFunction);
  22764. BABYLON.BezierCurveEase = BezierCurveEase;
  22765. })(BABYLON || (BABYLON = {}));
  22766. var BABYLON;
  22767. (function (BABYLON) {
  22768. var Bone = (function (_super) {
  22769. __extends(Bone, _super);
  22770. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22771. _super.call(this, name, skeleton.getScene());
  22772. this.name = name;
  22773. this.children = new Array();
  22774. this.animations = new Array();
  22775. this._worldTransform = new BABYLON.Matrix();
  22776. this._absoluteTransform = new BABYLON.Matrix();
  22777. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22778. this._skeleton = skeleton;
  22779. this._matrix = matrix;
  22780. this._baseMatrix = matrix;
  22781. this._restPose = restPose ? restPose : matrix.clone();
  22782. skeleton.bones.push(this);
  22783. if (parentBone) {
  22784. this._parent = parentBone;
  22785. parentBone.children.push(this);
  22786. }
  22787. else {
  22788. this._parent = null;
  22789. }
  22790. this._updateDifferenceMatrix();
  22791. }
  22792. // Members
  22793. Bone.prototype.getParent = function () {
  22794. return this._parent;
  22795. };
  22796. Bone.prototype.getLocalMatrix = function () {
  22797. return this._matrix;
  22798. };
  22799. Bone.prototype.getBaseMatrix = function () {
  22800. return this._baseMatrix;
  22801. };
  22802. Bone.prototype.getRestPose = function () {
  22803. return this._restPose;
  22804. };
  22805. Bone.prototype.returnToRest = function () {
  22806. this.updateMatrix(this._restPose.clone());
  22807. };
  22808. Bone.prototype.getWorldMatrix = function () {
  22809. return this._worldTransform;
  22810. };
  22811. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22812. return this._invertedAbsoluteTransform;
  22813. };
  22814. Bone.prototype.getAbsoluteTransform = function () {
  22815. return this._absoluteTransform;
  22816. };
  22817. // Methods
  22818. Bone.prototype.updateMatrix = function (matrix) {
  22819. this._baseMatrix = matrix.clone();
  22820. this._matrix = matrix.clone();
  22821. this._skeleton._markAsDirty();
  22822. this._updateDifferenceMatrix();
  22823. };
  22824. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  22825. if (!rootMatrix) {
  22826. rootMatrix = this._baseMatrix;
  22827. }
  22828. if (this._parent) {
  22829. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22830. }
  22831. else {
  22832. this._absoluteTransform.copyFrom(rootMatrix);
  22833. }
  22834. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22835. for (var index = 0; index < this.children.length; index++) {
  22836. this.children[index]._updateDifferenceMatrix();
  22837. }
  22838. };
  22839. Bone.prototype.markAsDirty = function () {
  22840. this._currentRenderId++;
  22841. this._skeleton._markAsDirty();
  22842. };
  22843. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22844. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22845. // all animation may be coming from a library skeleton, so may need to create animation
  22846. if (this.animations.length === 0) {
  22847. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22848. }
  22849. // get animation info / verify there is such a range from the source bone
  22850. var sourceRange = source.animations[0].getRange(rangeName);
  22851. if (!sourceRange) {
  22852. return false;
  22853. }
  22854. var from = sourceRange.from;
  22855. var to = sourceRange.to;
  22856. var sourceKeys = source.animations[0].getKeys();
  22857. // rescaling prep
  22858. var sourceBoneLength = source.length;
  22859. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22860. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22861. var destKeys = this.animations[0].getKeys();
  22862. // loop vars declaration / initialization
  22863. var orig;
  22864. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22865. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22866. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22867. var mat;
  22868. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22869. orig = sourceKeys[key];
  22870. if (orig.frame >= from && orig.frame <= to) {
  22871. if (scalingReqd) {
  22872. orig.value.decompose(origScale, origRotation, origTranslation);
  22873. origTranslation.scaleInPlace(ratio);
  22874. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22875. }
  22876. else {
  22877. mat = orig.value;
  22878. }
  22879. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22880. }
  22881. }
  22882. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22883. return true;
  22884. };
  22885. return Bone;
  22886. })(BABYLON.Node);
  22887. BABYLON.Bone = Bone;
  22888. })(BABYLON || (BABYLON = {}));
  22889. var BABYLON;
  22890. (function (BABYLON) {
  22891. var Skeleton = (function () {
  22892. function Skeleton(name, id, scene) {
  22893. this.name = name;
  22894. this.id = id;
  22895. this.bones = new Array();
  22896. this.needInitialSkinMatrix = false;
  22897. this._isDirty = true;
  22898. this._meshesWithPoseMatrix = new Array();
  22899. this._identity = BABYLON.Matrix.Identity();
  22900. this._ranges = {};
  22901. this.bones = [];
  22902. this._scene = scene;
  22903. scene.skeletons.push(this);
  22904. this.prepare();
  22905. //make sure it will recalculate the matrix next time prepare is called.
  22906. this._isDirty = true;
  22907. }
  22908. // Members
  22909. Skeleton.prototype.getTransformMatrices = function (mesh) {
  22910. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  22911. return mesh._bonesTransformMatrices;
  22912. }
  22913. return this._transformMatrices;
  22914. };
  22915. Skeleton.prototype.getScene = function () {
  22916. return this._scene;
  22917. };
  22918. // Methods
  22919. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22920. // check name not already in use
  22921. if (!this._ranges[name]) {
  22922. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22923. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22924. if (this.bones[i].animations[0]) {
  22925. this.bones[i].animations[0].createRange(name, from, to);
  22926. }
  22927. }
  22928. }
  22929. };
  22930. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22931. if (deleteFrames === void 0) { deleteFrames = true; }
  22932. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22933. if (this.bones[i].animations[0]) {
  22934. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22935. }
  22936. }
  22937. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22938. };
  22939. Skeleton.prototype.getAnimationRange = function (name) {
  22940. return this._ranges[name];
  22941. };
  22942. /**
  22943. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22944. */
  22945. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22946. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22947. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22948. return false;
  22949. }
  22950. var ret = true;
  22951. var frameOffset = this._getHighestAnimationFrame() + 1;
  22952. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22953. var boneDict = {};
  22954. var sourceBones = source.bones;
  22955. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22956. boneDict[sourceBones[i].name] = sourceBones[i];
  22957. }
  22958. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22959. var boneName = this.bones[i].name;
  22960. var sourceBone = boneDict[boneName];
  22961. if (sourceBone) {
  22962. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22963. }
  22964. else {
  22965. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22966. ret = false;
  22967. }
  22968. }
  22969. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22970. var range = source.getAnimationRange(name);
  22971. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22972. return ret;
  22973. };
  22974. Skeleton.prototype.returnToRest = function () {
  22975. for (var index = 0; index < this.bones.length; index++) {
  22976. this.bones[index].returnToRest();
  22977. }
  22978. };
  22979. Skeleton.prototype._getHighestAnimationFrame = function () {
  22980. var ret = 0;
  22981. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22982. if (this.bones[i].animations[0]) {
  22983. var highest = this.bones[i].animations[0].getHighestFrame();
  22984. if (ret < highest) {
  22985. ret = highest;
  22986. }
  22987. }
  22988. }
  22989. return ret;
  22990. };
  22991. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22992. var range = this.getAnimationRange(name);
  22993. if (!range) {
  22994. return null;
  22995. }
  22996. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22997. };
  22998. Skeleton.prototype._markAsDirty = function () {
  22999. this._isDirty = true;
  23000. };
  23001. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23002. this._meshesWithPoseMatrix.push(mesh);
  23003. };
  23004. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23005. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23006. if (index > -1) {
  23007. this._meshesWithPoseMatrix.splice(index, 1);
  23008. }
  23009. };
  23010. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23011. for (var index = 0; index < this.bones.length; index++) {
  23012. var bone = this.bones[index];
  23013. var parentBone = bone.getParent();
  23014. if (parentBone) {
  23015. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23016. }
  23017. else {
  23018. if (initialSkinMatrix) {
  23019. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23020. }
  23021. else {
  23022. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23023. }
  23024. }
  23025. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23026. }
  23027. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23028. };
  23029. Skeleton.prototype.prepare = function () {
  23030. if (!this._isDirty) {
  23031. return;
  23032. }
  23033. if (this.needInitialSkinMatrix) {
  23034. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23035. var mesh = this._meshesWithPoseMatrix[index];
  23036. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23037. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23038. }
  23039. var poseMatrix = mesh.getPoseMatrix();
  23040. // Prepare bones
  23041. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23042. var bone = this.bones[boneIndex];
  23043. if (!bone.getParent()) {
  23044. var matrix = bone.getBaseMatrix();
  23045. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23046. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23047. }
  23048. }
  23049. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23050. }
  23051. }
  23052. else {
  23053. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23054. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23055. }
  23056. this._computeTransformMatrices(this._transformMatrices, null);
  23057. }
  23058. this._isDirty = false;
  23059. this._scene._activeBones += this.bones.length;
  23060. };
  23061. Skeleton.prototype.getAnimatables = function () {
  23062. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23063. this._animatables = [];
  23064. for (var index = 0; index < this.bones.length; index++) {
  23065. this._animatables.push(this.bones[index]);
  23066. }
  23067. }
  23068. return this._animatables;
  23069. };
  23070. Skeleton.prototype.clone = function (name, id) {
  23071. var result = new Skeleton(name, id || name, this._scene);
  23072. for (var index = 0; index < this.bones.length; index++) {
  23073. var source = this.bones[index];
  23074. var parentBone = null;
  23075. if (source.getParent()) {
  23076. var parentIndex = this.bones.indexOf(source.getParent());
  23077. parentBone = result.bones[parentIndex];
  23078. }
  23079. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23080. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23081. }
  23082. return result;
  23083. };
  23084. Skeleton.prototype.dispose = function () {
  23085. this._meshesWithPoseMatrix = [];
  23086. // Animations
  23087. this.getScene().stopAnimation(this);
  23088. // Remove from scene
  23089. this.getScene().removeSkeleton(this);
  23090. };
  23091. Skeleton.prototype.serialize = function () {
  23092. var serializationObject = {};
  23093. serializationObject.name = this.name;
  23094. serializationObject.id = this.id;
  23095. serializationObject.bones = [];
  23096. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23097. for (var index = 0; index < this.bones.length; index++) {
  23098. var bone = this.bones[index];
  23099. var serializedBone = {
  23100. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23101. name: bone.name,
  23102. matrix: bone.getLocalMatrix().toArray(),
  23103. rest: bone.getRestPose().toArray()
  23104. };
  23105. serializationObject.bones.push(serializedBone);
  23106. if (bone.length) {
  23107. serializedBone.length = bone.length;
  23108. }
  23109. if (bone.animations && bone.animations.length > 0) {
  23110. serializedBone.animation = bone.animations[0].serialize();
  23111. }
  23112. serializationObject.ranges = [];
  23113. for (var name in this._ranges) {
  23114. var range = {};
  23115. range.name = name;
  23116. range.from = this._ranges[name].from;
  23117. range.to = this._ranges[name].to;
  23118. serializationObject.ranges.push(range);
  23119. }
  23120. }
  23121. return serializationObject;
  23122. };
  23123. Skeleton.Parse = function (parsedSkeleton, scene) {
  23124. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23125. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23126. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23127. var parsedBone = parsedSkeleton.bones[index];
  23128. var parentBone = null;
  23129. if (parsedBone.parentBoneIndex > -1) {
  23130. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23131. }
  23132. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23133. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23134. if (parsedBone.length) {
  23135. bone.length = parsedBone.length;
  23136. }
  23137. if (parsedBone.animation) {
  23138. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23139. }
  23140. }
  23141. // placed after bones, so createAnimationRange can cascade down
  23142. if (parsedSkeleton.ranges) {
  23143. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23144. var data = parsedSkeleton.ranges[index];
  23145. skeleton.createAnimationRange(data.name, data.from, data.to);
  23146. }
  23147. }
  23148. return skeleton;
  23149. };
  23150. return Skeleton;
  23151. })();
  23152. BABYLON.Skeleton = Skeleton;
  23153. })(BABYLON || (BABYLON = {}));
  23154. var BABYLON;
  23155. (function (BABYLON) {
  23156. var PostProcess = (function () {
  23157. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23159. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23160. this.name = name;
  23161. this.width = -1;
  23162. this.height = -1;
  23163. this._reusable = false;
  23164. this._textures = new BABYLON.SmartArray(2);
  23165. this._currentRenderTextureInd = 0;
  23166. if (camera != null) {
  23167. this._camera = camera;
  23168. this._scene = camera.getScene();
  23169. camera.attachPostProcess(this);
  23170. this._engine = this._scene.getEngine();
  23171. }
  23172. else {
  23173. this._engine = engine;
  23174. }
  23175. this._renderRatio = ratio;
  23176. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23177. this._reusable = reusable || false;
  23178. this._textureType = textureType;
  23179. this._samplers = samplers || [];
  23180. this._samplers.push("textureSampler");
  23181. this._fragmentUrl = fragmentUrl;
  23182. this._parameters = parameters || [];
  23183. this.updateEffect(defines);
  23184. }
  23185. PostProcess.prototype.updateEffect = function (defines) {
  23186. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23187. };
  23188. PostProcess.prototype.isReusable = function () {
  23189. return this._reusable;
  23190. };
  23191. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23192. camera = camera || this._camera;
  23193. var scene = camera.getScene();
  23194. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23195. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23196. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23197. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23198. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23199. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23200. if (this._textures.length > 0) {
  23201. for (var i = 0; i < this._textures.length; i++) {
  23202. this._engine._releaseTexture(this._textures.data[i]);
  23203. }
  23204. this._textures.reset();
  23205. }
  23206. this.width = desiredWidth;
  23207. this.height = desiredHeight;
  23208. 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 }));
  23209. if (this._reusable) {
  23210. 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 }));
  23211. }
  23212. if (this.onSizeChanged) {
  23213. this.onSizeChanged();
  23214. }
  23215. }
  23216. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23217. if (this.onActivate) {
  23218. this.onActivate(camera);
  23219. }
  23220. // Clear
  23221. if (this.clearColor) {
  23222. this._engine.clear(this.clearColor, true, true);
  23223. }
  23224. else {
  23225. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23226. }
  23227. if (this._reusable) {
  23228. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23229. }
  23230. };
  23231. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23232. get: function () {
  23233. return this._effect.isSupported;
  23234. },
  23235. enumerable: true,
  23236. configurable: true
  23237. });
  23238. PostProcess.prototype.apply = function () {
  23239. // Check
  23240. if (!this._effect.isReady())
  23241. return null;
  23242. // States
  23243. this._engine.enableEffect(this._effect);
  23244. this._engine.setState(false);
  23245. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23246. this._engine.setDepthBuffer(false);
  23247. this._engine.setDepthWrite(false);
  23248. // Texture
  23249. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23250. // Parameters
  23251. if (this.onApply) {
  23252. this.onApply(this._effect);
  23253. }
  23254. return this._effect;
  23255. };
  23256. PostProcess.prototype.dispose = function (camera) {
  23257. camera = camera || this._camera;
  23258. if (this._textures.length > 0) {
  23259. for (var i = 0; i < this._textures.length; i++) {
  23260. this._engine._releaseTexture(this._textures.data[i]);
  23261. }
  23262. this._textures.reset();
  23263. }
  23264. if (!camera) {
  23265. return;
  23266. }
  23267. camera.detachPostProcess(this);
  23268. var index = camera._postProcesses.indexOf(this);
  23269. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23270. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23271. }
  23272. };
  23273. return PostProcess;
  23274. })();
  23275. BABYLON.PostProcess = PostProcess;
  23276. })(BABYLON || (BABYLON = {}));
  23277. var BABYLON;
  23278. (function (BABYLON) {
  23279. var PostProcessManager = (function () {
  23280. function PostProcessManager(scene) {
  23281. this._vertexDeclaration = [2];
  23282. this._vertexStrideSize = 2 * 4;
  23283. this._scene = scene;
  23284. }
  23285. PostProcessManager.prototype._prepareBuffers = function () {
  23286. if (this._vertexBuffer) {
  23287. return;
  23288. }
  23289. // VBO
  23290. var vertices = [];
  23291. vertices.push(1, 1);
  23292. vertices.push(-1, 1);
  23293. vertices.push(-1, -1);
  23294. vertices.push(1, -1);
  23295. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23296. // Indices
  23297. var indices = [];
  23298. indices.push(0);
  23299. indices.push(1);
  23300. indices.push(2);
  23301. indices.push(0);
  23302. indices.push(2);
  23303. indices.push(3);
  23304. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23305. };
  23306. // Methods
  23307. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23308. var postProcesses = this._scene.activeCamera._postProcesses;
  23309. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23310. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23311. return false;
  23312. }
  23313. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23314. return true;
  23315. };
  23316. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23317. var engine = this._scene.getEngine();
  23318. for (var index = 0; index < postProcesses.length; index++) {
  23319. if (index < postProcesses.length - 1) {
  23320. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23321. }
  23322. else {
  23323. if (targetTexture) {
  23324. engine.bindFramebuffer(targetTexture);
  23325. }
  23326. else {
  23327. engine.restoreDefaultFramebuffer();
  23328. }
  23329. }
  23330. var pp = postProcesses[index];
  23331. var effect = pp.apply();
  23332. if (effect) {
  23333. if (pp.onBeforeRender) {
  23334. pp.onBeforeRender(effect);
  23335. }
  23336. // VBOs
  23337. this._prepareBuffers();
  23338. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23339. // Draw order
  23340. engine.draw(true, 0, 6);
  23341. if (pp.onAfterRender) {
  23342. pp.onAfterRender(effect);
  23343. }
  23344. }
  23345. }
  23346. // Restore depth buffer
  23347. engine.setDepthBuffer(true);
  23348. engine.setDepthWrite(true);
  23349. };
  23350. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23351. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23352. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23353. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23354. return;
  23355. }
  23356. var engine = this._scene.getEngine();
  23357. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23358. if (index < postProcessesTakenIndices.length - 1) {
  23359. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23360. }
  23361. else {
  23362. if (targetTexture) {
  23363. engine.bindFramebuffer(targetTexture, faceIndex);
  23364. }
  23365. else {
  23366. engine.restoreDefaultFramebuffer();
  23367. }
  23368. }
  23369. if (doNotPresent) {
  23370. break;
  23371. }
  23372. var pp = postProcesses[postProcessesTakenIndices[index]];
  23373. var effect = pp.apply();
  23374. if (effect) {
  23375. if (pp.onBeforeRender) {
  23376. pp.onBeforeRender(effect);
  23377. }
  23378. // VBOs
  23379. this._prepareBuffers();
  23380. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23381. // Draw order
  23382. engine.draw(true, 0, 6);
  23383. if (pp.onAfterRender) {
  23384. pp.onAfterRender(effect);
  23385. }
  23386. }
  23387. }
  23388. // Restore depth buffer
  23389. engine.setDepthBuffer(true);
  23390. engine.setDepthWrite(true);
  23391. };
  23392. PostProcessManager.prototype.dispose = function () {
  23393. if (this._vertexBuffer) {
  23394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23395. this._vertexBuffer = null;
  23396. }
  23397. if (this._indexBuffer) {
  23398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23399. this._indexBuffer = null;
  23400. }
  23401. };
  23402. return PostProcessManager;
  23403. })();
  23404. BABYLON.PostProcessManager = PostProcessManager;
  23405. })(BABYLON || (BABYLON = {}));
  23406. var BABYLON;
  23407. (function (BABYLON) {
  23408. var PassPostProcess = (function (_super) {
  23409. __extends(PassPostProcess, _super);
  23410. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23411. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23412. }
  23413. return PassPostProcess;
  23414. })(BABYLON.PostProcess);
  23415. BABYLON.PassPostProcess = PassPostProcess;
  23416. })(BABYLON || (BABYLON = {}));
  23417. var BABYLON;
  23418. (function (BABYLON) {
  23419. var PhysicsEngine = (function () {
  23420. function PhysicsEngine(plugin) {
  23421. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23422. }
  23423. PhysicsEngine.prototype._initialize = function (gravity) {
  23424. this._currentPlugin.initialize();
  23425. this._setGravity(gravity);
  23426. };
  23427. PhysicsEngine.prototype._runOneStep = function (delta) {
  23428. if (delta > 0.1) {
  23429. delta = 0.1;
  23430. }
  23431. else if (delta <= 0) {
  23432. delta = 1.0 / 60.0;
  23433. }
  23434. this._currentPlugin.runOneStep(delta);
  23435. };
  23436. PhysicsEngine.prototype._setGravity = function (gravity) {
  23437. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23438. this._currentPlugin.setGravity(this.gravity);
  23439. };
  23440. PhysicsEngine.prototype._getGravity = function () {
  23441. return this._currentPlugin.getGravity();
  23442. };
  23443. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23444. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23445. };
  23446. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23447. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23448. };
  23449. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23450. this._currentPlugin.unregisterMesh(mesh);
  23451. };
  23452. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23453. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23454. };
  23455. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23456. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23457. };
  23458. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23459. this._currentPlugin.updateBodyPosition(mesh);
  23460. };
  23461. PhysicsEngine.prototype.dispose = function () {
  23462. this._currentPlugin.dispose();
  23463. };
  23464. PhysicsEngine.prototype.isSupported = function () {
  23465. return this._currentPlugin.isSupported();
  23466. };
  23467. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23468. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23469. };
  23470. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23471. return this._currentPlugin.name;
  23472. };
  23473. PhysicsEngine.prototype.getWorldObject = function () {
  23474. return this._currentPlugin.getWorldObject();
  23475. };
  23476. // Statics
  23477. PhysicsEngine.NoImpostor = 0;
  23478. PhysicsEngine.SphereImpostor = 1;
  23479. PhysicsEngine.BoxImpostor = 2;
  23480. PhysicsEngine.PlaneImpostor = 3;
  23481. PhysicsEngine.MeshImpostor = 4;
  23482. PhysicsEngine.CapsuleImpostor = 5;
  23483. PhysicsEngine.ConeImpostor = 6;
  23484. PhysicsEngine.CylinderImpostor = 7;
  23485. PhysicsEngine.ConvexHullImpostor = 8;
  23486. PhysicsEngine.HeightmapImpostor = 9;
  23487. PhysicsEngine.Epsilon = 0.001;
  23488. return PhysicsEngine;
  23489. })();
  23490. BABYLON.PhysicsEngine = PhysicsEngine;
  23491. })(BABYLON || (BABYLON = {}));
  23492. var BABYLON;
  23493. (function (BABYLON) {
  23494. var VertexData = (function () {
  23495. function VertexData() {
  23496. }
  23497. VertexData.prototype.set = function (data, kind) {
  23498. switch (kind) {
  23499. case BABYLON.VertexBuffer.PositionKind:
  23500. this.positions = data;
  23501. break;
  23502. case BABYLON.VertexBuffer.NormalKind:
  23503. this.normals = data;
  23504. break;
  23505. case BABYLON.VertexBuffer.UVKind:
  23506. this.uvs = data;
  23507. break;
  23508. case BABYLON.VertexBuffer.UV2Kind:
  23509. this.uvs2 = data;
  23510. break;
  23511. case BABYLON.VertexBuffer.UV3Kind:
  23512. this.uvs3 = data;
  23513. break;
  23514. case BABYLON.VertexBuffer.UV4Kind:
  23515. this.uvs4 = data;
  23516. break;
  23517. case BABYLON.VertexBuffer.UV5Kind:
  23518. this.uvs5 = data;
  23519. break;
  23520. case BABYLON.VertexBuffer.UV6Kind:
  23521. this.uvs6 = data;
  23522. break;
  23523. case BABYLON.VertexBuffer.ColorKind:
  23524. this.colors = data;
  23525. break;
  23526. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23527. this.matricesIndices = data;
  23528. break;
  23529. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23530. this.matricesWeights = data;
  23531. break;
  23532. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23533. this.matricesIndicesExtra = data;
  23534. break;
  23535. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23536. this.matricesWeightsExtra = data;
  23537. break;
  23538. }
  23539. };
  23540. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23541. this._applyTo(mesh, updatable);
  23542. };
  23543. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23544. this._applyTo(geometry, updatable);
  23545. };
  23546. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23547. this._update(mesh);
  23548. };
  23549. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23550. this._update(geometry);
  23551. };
  23552. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23553. if (this.positions) {
  23554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23555. }
  23556. if (this.normals) {
  23557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23558. }
  23559. if (this.uvs) {
  23560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23561. }
  23562. if (this.uvs2) {
  23563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23564. }
  23565. if (this.uvs3) {
  23566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23567. }
  23568. if (this.uvs4) {
  23569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23570. }
  23571. if (this.uvs5) {
  23572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23573. }
  23574. if (this.uvs6) {
  23575. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23576. }
  23577. if (this.colors) {
  23578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23579. }
  23580. if (this.matricesIndices) {
  23581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23582. }
  23583. if (this.matricesWeights) {
  23584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23585. }
  23586. if (this.matricesIndicesExtra) {
  23587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23588. }
  23589. if (this.matricesWeightsExtra) {
  23590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23591. }
  23592. if (this.indices) {
  23593. meshOrGeometry.setIndices(this.indices);
  23594. }
  23595. };
  23596. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23597. if (this.positions) {
  23598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23599. }
  23600. if (this.normals) {
  23601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23602. }
  23603. if (this.uvs) {
  23604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23605. }
  23606. if (this.uvs2) {
  23607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23608. }
  23609. if (this.uvs3) {
  23610. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23611. }
  23612. if (this.uvs4) {
  23613. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23614. }
  23615. if (this.uvs5) {
  23616. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23617. }
  23618. if (this.uvs6) {
  23619. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23620. }
  23621. if (this.colors) {
  23622. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23623. }
  23624. if (this.matricesIndices) {
  23625. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23626. }
  23627. if (this.matricesWeights) {
  23628. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23629. }
  23630. if (this.matricesIndicesExtra) {
  23631. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23632. }
  23633. if (this.matricesWeightsExtra) {
  23634. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23635. }
  23636. if (this.indices) {
  23637. meshOrGeometry.setIndices(this.indices);
  23638. }
  23639. };
  23640. VertexData.prototype.transform = function (matrix) {
  23641. var transformed = BABYLON.Vector3.Zero();
  23642. var index;
  23643. if (this.positions) {
  23644. var position = BABYLON.Vector3.Zero();
  23645. for (index = 0; index < this.positions.length; index += 3) {
  23646. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23647. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23648. this.positions[index] = transformed.x;
  23649. this.positions[index + 1] = transformed.y;
  23650. this.positions[index + 2] = transformed.z;
  23651. }
  23652. }
  23653. if (this.normals) {
  23654. var normal = BABYLON.Vector3.Zero();
  23655. for (index = 0; index < this.normals.length; index += 3) {
  23656. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23657. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23658. this.normals[index] = transformed.x;
  23659. this.normals[index + 1] = transformed.y;
  23660. this.normals[index + 2] = transformed.z;
  23661. }
  23662. }
  23663. };
  23664. VertexData.prototype.merge = function (other) {
  23665. if (other.indices) {
  23666. if (!this.indices) {
  23667. this.indices = [];
  23668. }
  23669. var offset = this.positions ? this.positions.length / 3 : 0;
  23670. for (var index = 0; index < other.indices.length; index++) {
  23671. //TODO check type - if Int32Array!
  23672. this.indices.push(other.indices[index] + offset);
  23673. }
  23674. }
  23675. this.positions = this._mergeElement(this.positions, other.positions);
  23676. this.normals = this._mergeElement(this.normals, other.normals);
  23677. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23678. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23679. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23680. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23681. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23682. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23683. this.colors = this._mergeElement(this.colors, other.colors);
  23684. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23685. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23686. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23687. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23688. };
  23689. VertexData.prototype._mergeElement = function (source, other) {
  23690. if (!other)
  23691. return source;
  23692. if (!source)
  23693. return other;
  23694. var len = other.length + source.length;
  23695. var isSrcTypedArray = source instanceof Float32Array;
  23696. var isOthTypedArray = other instanceof Float32Array;
  23697. // use non-loop method when the source is Float32Array
  23698. if (isSrcTypedArray) {
  23699. var ret32 = new Float32Array(len);
  23700. ret32.set(source);
  23701. ret32.set(other, source.length);
  23702. return ret32;
  23703. }
  23704. else if (!isOthTypedArray) {
  23705. return source.concat(other);
  23706. }
  23707. else {
  23708. var ret = source.slice(0); // copy source to a separate array
  23709. for (var i = 0, len = other.length; i < len; i++) {
  23710. ret.push(other[i]);
  23711. }
  23712. return ret;
  23713. }
  23714. };
  23715. VertexData.prototype.serialize = function () {
  23716. var serializationObject = this.serialize();
  23717. if (this.positions) {
  23718. serializationObject.positions = this.positions;
  23719. }
  23720. if (this.normals) {
  23721. serializationObject.normals = this.normals;
  23722. }
  23723. if (this.uvs) {
  23724. serializationObject.uvs = this.uvs;
  23725. }
  23726. if (this.uvs2) {
  23727. serializationObject.uvs2 = this.uvs2;
  23728. }
  23729. if (this.uvs3) {
  23730. serializationObject.uvs3 = this.uvs3;
  23731. }
  23732. if (this.uvs4) {
  23733. serializationObject.uvs4 = this.uvs4;
  23734. }
  23735. if (this.uvs5) {
  23736. serializationObject.uvs5 = this.uvs5;
  23737. }
  23738. if (this.uvs6) {
  23739. serializationObject.uvs6 = this.uvs6;
  23740. }
  23741. if (this.colors) {
  23742. serializationObject.colors = this.colors;
  23743. }
  23744. if (this.matricesIndices) {
  23745. serializationObject.matricesIndices = this.matricesIndices;
  23746. serializationObject.matricesIndices._isExpanded = true;
  23747. }
  23748. if (this.matricesWeights) {
  23749. serializationObject.matricesWeights = this.matricesWeights;
  23750. }
  23751. if (this.matricesIndicesExtra) {
  23752. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23753. serializationObject.matricesIndicesExtra._isExpanded = true;
  23754. }
  23755. if (this.matricesWeightsExtra) {
  23756. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23757. }
  23758. serializationObject.indices = this.indices;
  23759. return serializationObject;
  23760. };
  23761. // Statics
  23762. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23763. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23764. };
  23765. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23766. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23767. };
  23768. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23769. var result = new VertexData();
  23770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23771. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23772. }
  23773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23774. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23775. }
  23776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23777. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23778. }
  23779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23780. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23781. }
  23782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23783. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23784. }
  23785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23786. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23787. }
  23788. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23789. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23790. }
  23791. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23792. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23793. }
  23794. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23795. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23796. }
  23797. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23798. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23799. }
  23800. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23801. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23802. }
  23803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23804. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23805. }
  23806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23807. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23808. }
  23809. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23810. return result;
  23811. };
  23812. VertexData.CreateRibbon = function (options) {
  23813. var pathArray = options.pathArray;
  23814. var closeArray = options.closeArray || false;
  23815. var closePath = options.closePath || false;
  23816. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23817. var offset = options.offset || defaultOffset;
  23818. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23819. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23820. var positions = [];
  23821. var indices = [];
  23822. var normals = [];
  23823. var uvs = [];
  23824. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23825. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23826. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23827. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23828. var minlg; // minimal length among all paths from pathArray
  23829. var lg = []; // array of path lengths : nb of vertex per path
  23830. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23831. var p; // path iterator
  23832. var i; // point iterator
  23833. var j; // point iterator
  23834. // if single path in pathArray
  23835. if (pathArray.length < 2) {
  23836. var ar1 = [];
  23837. var ar2 = [];
  23838. for (i = 0; i < pathArray[0].length - offset; i++) {
  23839. ar1.push(pathArray[0][i]);
  23840. ar2.push(pathArray[0][i + offset]);
  23841. }
  23842. pathArray = [ar1, ar2];
  23843. }
  23844. // positions and horizontal distances (u)
  23845. var idc = 0;
  23846. var closePathCorr = (closePath) ? 1 : 0;
  23847. var path;
  23848. var l;
  23849. minlg = pathArray[0].length;
  23850. var vectlg;
  23851. var dist;
  23852. for (p = 0; p < pathArray.length; p++) {
  23853. uTotalDistance[p] = 0;
  23854. us[p] = [0];
  23855. path = pathArray[p];
  23856. l = path.length;
  23857. minlg = (minlg < l) ? minlg : l;
  23858. j = 0;
  23859. while (j < l) {
  23860. positions.push(path[j].x, path[j].y, path[j].z);
  23861. if (j > 0) {
  23862. vectlg = path[j].subtract(path[j - 1]).length();
  23863. dist = vectlg + uTotalDistance[p];
  23864. us[p].push(dist);
  23865. uTotalDistance[p] = dist;
  23866. }
  23867. j++;
  23868. }
  23869. if (closePath) {
  23870. j--;
  23871. positions.push(path[0].x, path[0].y, path[0].z);
  23872. vectlg = path[j].subtract(path[0]).length();
  23873. dist = vectlg + uTotalDistance[p];
  23874. us[p].push(dist);
  23875. uTotalDistance[p] = dist;
  23876. }
  23877. lg[p] = l + closePathCorr;
  23878. idx[p] = idc;
  23879. idc += (l + closePathCorr);
  23880. }
  23881. // vertical distances (v)
  23882. var path1;
  23883. var path2;
  23884. var vertex1;
  23885. var vertex2;
  23886. for (i = 0; i < minlg + closePathCorr; i++) {
  23887. vTotalDistance[i] = 0;
  23888. vs[i] = [0];
  23889. for (p = 0; p < pathArray.length - 1; p++) {
  23890. path1 = pathArray[p];
  23891. path2 = pathArray[p + 1];
  23892. if (i === minlg) {
  23893. vertex1 = path1[0];
  23894. vertex2 = path2[0];
  23895. }
  23896. else {
  23897. vertex1 = path1[i];
  23898. vertex2 = path2[i];
  23899. }
  23900. vectlg = vertex2.subtract(vertex1).length();
  23901. dist = vectlg + vTotalDistance[i];
  23902. vs[i].push(dist);
  23903. vTotalDistance[i] = dist;
  23904. }
  23905. if (closeArray) {
  23906. path1 = pathArray[p];
  23907. path2 = pathArray[0];
  23908. if (i === minlg) {
  23909. vertex2 = path2[0];
  23910. }
  23911. vectlg = vertex2.subtract(vertex1).length();
  23912. dist = vectlg + vTotalDistance[i];
  23913. vTotalDistance[i] = dist;
  23914. }
  23915. }
  23916. // uvs
  23917. var u;
  23918. var v;
  23919. for (p = 0; p < pathArray.length; p++) {
  23920. for (i = 0; i < minlg + closePathCorr; i++) {
  23921. u = us[p][i] / uTotalDistance[p];
  23922. v = vs[i][p] / vTotalDistance[i];
  23923. uvs.push(u, v);
  23924. }
  23925. }
  23926. // indices
  23927. p = 0; // path index
  23928. var pi = 0; // positions array index
  23929. var l1 = lg[p] - 1; // path1 length
  23930. var l2 = lg[p + 1] - 1; // path2 length
  23931. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23932. var shft = idx[1] - idx[0]; // shift
  23933. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23934. while (pi <= min && p < path1nb) {
  23935. // 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
  23936. indices.push(pi, pi + shft, pi + 1);
  23937. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23938. pi += 1;
  23939. if (pi === min) {
  23940. p++;
  23941. if (p === lg.length - 1) {
  23942. shft = idx[0] - idx[p];
  23943. l1 = lg[p] - 1;
  23944. l2 = lg[0] - 1;
  23945. }
  23946. else {
  23947. shft = idx[p + 1] - idx[p];
  23948. l1 = lg[p] - 1;
  23949. l2 = lg[p + 1] - 1;
  23950. }
  23951. pi = idx[p];
  23952. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23953. }
  23954. }
  23955. // normals
  23956. VertexData.ComputeNormals(positions, indices, normals);
  23957. if (closePath) {
  23958. var indexFirst = 0;
  23959. var indexLast = 0;
  23960. for (p = 0; p < pathArray.length; p++) {
  23961. indexFirst = idx[p] * 3;
  23962. if (p + 1 < pathArray.length) {
  23963. indexLast = (idx[p + 1] - 1) * 3;
  23964. }
  23965. else {
  23966. indexLast = normals.length - 3;
  23967. }
  23968. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23969. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23970. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23971. normals[indexLast] = normals[indexFirst];
  23972. normals[indexLast + 1] = normals[indexFirst + 1];
  23973. normals[indexLast + 2] = normals[indexFirst + 2];
  23974. }
  23975. }
  23976. // sides
  23977. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23978. // Result
  23979. var vertexData = new VertexData();
  23980. vertexData.indices = indices;
  23981. vertexData.positions = positions;
  23982. vertexData.normals = normals;
  23983. vertexData.uvs = uvs;
  23984. if (closePath) {
  23985. vertexData._idx = idx;
  23986. }
  23987. return vertexData;
  23988. };
  23989. VertexData.CreateBox = function (options) {
  23990. var normalsSource = [
  23991. new BABYLON.Vector3(0, 0, 1),
  23992. new BABYLON.Vector3(0, 0, -1),
  23993. new BABYLON.Vector3(1, 0, 0),
  23994. new BABYLON.Vector3(-1, 0, 0),
  23995. new BABYLON.Vector3(0, 1, 0),
  23996. new BABYLON.Vector3(0, -1, 0)
  23997. ];
  23998. var indices = [];
  23999. var positions = [];
  24000. var normals = [];
  24001. var uvs = [];
  24002. var width = options.width || options.size || 1;
  24003. var height = options.height || options.size || 1;
  24004. var depth = options.depth || options.size || 1;
  24005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24006. var faceUV = options.faceUV || new Array(6);
  24007. var faceColors = options.faceColors;
  24008. var colors = [];
  24009. // default face colors and UV if undefined
  24010. for (var f = 0; f < 6; f++) {
  24011. if (faceUV[f] === undefined) {
  24012. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24013. }
  24014. if (faceColors && faceColors[f] === undefined) {
  24015. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24016. }
  24017. }
  24018. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24019. // Create each face in turn.
  24020. for (var index = 0; index < normalsSource.length; index++) {
  24021. var normal = normalsSource[index];
  24022. // Get two vectors perpendicular to the face normal and to each other.
  24023. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24024. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24025. // Six indices (two triangles) per face.
  24026. var verticesLength = positions.length / 3;
  24027. indices.push(verticesLength);
  24028. indices.push(verticesLength + 1);
  24029. indices.push(verticesLength + 2);
  24030. indices.push(verticesLength);
  24031. indices.push(verticesLength + 2);
  24032. indices.push(verticesLength + 3);
  24033. // Four vertices per face.
  24034. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24035. positions.push(vertex.x, vertex.y, vertex.z);
  24036. normals.push(normal.x, normal.y, normal.z);
  24037. uvs.push(faceUV[index].z, faceUV[index].w);
  24038. if (faceColors) {
  24039. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24040. }
  24041. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24042. positions.push(vertex.x, vertex.y, vertex.z);
  24043. normals.push(normal.x, normal.y, normal.z);
  24044. uvs.push(faceUV[index].x, faceUV[index].w);
  24045. if (faceColors) {
  24046. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24047. }
  24048. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24049. positions.push(vertex.x, vertex.y, vertex.z);
  24050. normals.push(normal.x, normal.y, normal.z);
  24051. uvs.push(faceUV[index].x, faceUV[index].y);
  24052. if (faceColors) {
  24053. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24054. }
  24055. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24056. positions.push(vertex.x, vertex.y, vertex.z);
  24057. normals.push(normal.x, normal.y, normal.z);
  24058. uvs.push(faceUV[index].z, faceUV[index].y);
  24059. if (faceColors) {
  24060. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24061. }
  24062. }
  24063. // sides
  24064. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24065. // Result
  24066. var vertexData = new VertexData();
  24067. vertexData.indices = indices;
  24068. vertexData.positions = positions;
  24069. vertexData.normals = normals;
  24070. vertexData.uvs = uvs;
  24071. if (faceColors) {
  24072. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24073. vertexData.colors = totalColors;
  24074. }
  24075. return vertexData;
  24076. };
  24077. VertexData.CreateSphere = function (options) {
  24078. var segments = options.segments || 32;
  24079. var diameterX = options.diameterX || options.diameter || 1;
  24080. var diameterY = options.diameterY || options.diameter || 1;
  24081. var diameterZ = options.diameterZ || options.diameter || 1;
  24082. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24083. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24084. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24085. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24086. var totalZRotationSteps = 2 + segments;
  24087. var totalYRotationSteps = 2 * totalZRotationSteps;
  24088. var indices = [];
  24089. var positions = [];
  24090. var normals = [];
  24091. var uvs = [];
  24092. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24093. var normalizedZ = zRotationStep / totalZRotationSteps;
  24094. var angleZ = normalizedZ * Math.PI * slice;
  24095. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24096. var normalizedY = yRotationStep / totalYRotationSteps;
  24097. var angleY = normalizedY * Math.PI * 2 * arc;
  24098. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24099. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24100. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24101. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24102. var vertex = complete.multiply(radius);
  24103. var normal = complete.divide(radius).normalize();
  24104. positions.push(vertex.x, vertex.y, vertex.z);
  24105. normals.push(normal.x, normal.y, normal.z);
  24106. uvs.push(normalizedY, normalizedZ);
  24107. }
  24108. if (zRotationStep > 0) {
  24109. var verticesCount = positions.length / 3;
  24110. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24111. indices.push((firstIndex));
  24112. indices.push((firstIndex + 1));
  24113. indices.push(firstIndex + totalYRotationSteps + 1);
  24114. indices.push((firstIndex + totalYRotationSteps + 1));
  24115. indices.push((firstIndex + 1));
  24116. indices.push((firstIndex + totalYRotationSteps + 2));
  24117. }
  24118. }
  24119. }
  24120. // Sides
  24121. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24122. // Result
  24123. var vertexData = new VertexData();
  24124. vertexData.indices = indices;
  24125. vertexData.positions = positions;
  24126. vertexData.normals = normals;
  24127. vertexData.uvs = uvs;
  24128. return vertexData;
  24129. };
  24130. // Cylinder and cone
  24131. VertexData.CreateCylinder = function (options) {
  24132. var height = options.height || 2;
  24133. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24134. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24135. var tessellation = options.tessellation || 24;
  24136. var subdivisions = options.subdivisions || 1;
  24137. var hasRings = options.hasRings;
  24138. var enclose = options.enclose;
  24139. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24140. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24141. var faceUV = options.faceUV || new Array(3);
  24142. var faceColors = options.faceColors;
  24143. // default face colors and UV if undefined
  24144. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24145. var ringNb = (hasRings) ? subdivisions : 1;
  24146. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24147. var f;
  24148. for (f = 0; f < surfaceNb; f++) {
  24149. if (faceColors && faceColors[f] === undefined) {
  24150. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24151. }
  24152. }
  24153. for (f = 0; f < surfaceNb; f++) {
  24154. if (faceUV && faceUV[f] === undefined) {
  24155. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24156. }
  24157. }
  24158. var indices = [];
  24159. var positions = [];
  24160. var normals = [];
  24161. var uvs = [];
  24162. var colors = [];
  24163. var angle_step = Math.PI * 2 * arc / tessellation;
  24164. var angle;
  24165. var h;
  24166. var radius;
  24167. var tan = (diameterBottom - diameterTop) / 2 / height;
  24168. var ringVertex = BABYLON.Vector3.Zero();
  24169. var ringNormal = BABYLON.Vector3.Zero();
  24170. var ringFirstVertex = BABYLON.Vector3.Zero();
  24171. var ringFirstNormal = BABYLON.Vector3.Zero();
  24172. var quadNormal = BABYLON.Vector3.Zero();
  24173. var Y = BABYLON.Axis.Y;
  24174. // positions, normals, uvs
  24175. var i;
  24176. var j;
  24177. var r;
  24178. var ringIdx = 1;
  24179. var s = 1; // surface index
  24180. var cs = 0;
  24181. var v = 0;
  24182. for (i = 0; i <= subdivisions; i++) {
  24183. h = i / subdivisions;
  24184. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24185. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24186. for (r = 0; r < ringIdx; r++) {
  24187. if (hasRings) {
  24188. s += r;
  24189. }
  24190. if (enclose) {
  24191. s += 2 * r;
  24192. }
  24193. for (j = 0; j <= tessellation; j++) {
  24194. angle = j * angle_step;
  24195. // position
  24196. ringVertex.x = Math.cos(-angle) * radius;
  24197. ringVertex.y = -height / 2 + h * height;
  24198. ringVertex.z = Math.sin(-angle) * radius;
  24199. // normal
  24200. if (diameterTop === 0 && i === subdivisions) {
  24201. // if no top cap, reuse former normals
  24202. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24203. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24204. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24205. }
  24206. else {
  24207. ringNormal.x = ringVertex.x;
  24208. ringNormal.z = ringVertex.z;
  24209. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24210. ringNormal.normalize();
  24211. }
  24212. // keep first ring vertex values for enclose
  24213. if (j === 0) {
  24214. ringFirstVertex.copyFrom(ringVertex);
  24215. ringFirstNormal.copyFrom(ringNormal);
  24216. }
  24217. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24218. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24219. if (hasRings) {
  24220. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24221. }
  24222. else {
  24223. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24224. }
  24225. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24226. if (faceColors) {
  24227. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24228. }
  24229. }
  24230. // if enclose, add four vertices and their dedicated normals
  24231. if (arc !== 1 && enclose) {
  24232. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24233. positions.push(0, ringVertex.y, 0);
  24234. positions.push(0, ringVertex.y, 0);
  24235. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24236. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24237. quadNormal.normalize();
  24238. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24239. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24240. quadNormal.normalize();
  24241. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24242. if (hasRings) {
  24243. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24244. }
  24245. else {
  24246. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24247. }
  24248. uvs.push(faceUV[s + 1].x, v);
  24249. uvs.push(faceUV[s + 1].z, v);
  24250. if (hasRings) {
  24251. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24252. }
  24253. else {
  24254. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24255. }
  24256. uvs.push(faceUV[s + 2].x, v);
  24257. uvs.push(faceUV[s + 2].z, v);
  24258. if (faceColors) {
  24259. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24260. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24261. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24262. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24263. }
  24264. }
  24265. if (cs !== s) {
  24266. cs = s;
  24267. }
  24268. }
  24269. }
  24270. // indices
  24271. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24272. var s;
  24273. i = 0;
  24274. for (s = 0; s < subdivisions; s++) {
  24275. for (j = 0; j < tessellation; j++) {
  24276. var i0 = i * (e + 1) + j;
  24277. var i1 = (i + 1) * (e + 1) + j;
  24278. var i2 = i * (e + 1) + (j + 1);
  24279. var i3 = (i + 1) * (e + 1) + (j + 1);
  24280. indices.push(i0, i1, i2);
  24281. indices.push(i3, i2, i1);
  24282. }
  24283. if (arc !== 1 && enclose) {
  24284. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24285. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24286. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24287. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24288. }
  24289. i = (hasRings) ? (i + 2) : (i + 1);
  24290. }
  24291. // Caps
  24292. var createCylinderCap = function (isTop) {
  24293. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24294. if (radius === 0) {
  24295. return;
  24296. }
  24297. // Cap positions, normals & uvs
  24298. var angle;
  24299. var circleVector;
  24300. var i;
  24301. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24302. var c;
  24303. if (faceColors) {
  24304. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24305. }
  24306. // cap center
  24307. var vbase = positions.length / 3;
  24308. var offset = isTop ? height / 2 : -height / 2;
  24309. var center = new BABYLON.Vector3(0, offset, 0);
  24310. positions.push(center.x, center.y, center.z);
  24311. normals.push(0, isTop ? 1 : -1, 0);
  24312. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24313. if (faceColors) {
  24314. colors.push(c.r, c.g, c.b, c.a);
  24315. }
  24316. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24317. for (i = 0; i <= tessellation; i++) {
  24318. angle = Math.PI * 2 * i * arc / tessellation;
  24319. var cos = Math.cos(-angle);
  24320. var sin = Math.sin(-angle);
  24321. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24322. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24323. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24324. normals.push(0, isTop ? 1 : -1, 0);
  24325. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24326. if (faceColors) {
  24327. colors.push(c.r, c.g, c.b, c.a);
  24328. }
  24329. }
  24330. // Cap indices
  24331. for (i = 0; i < tessellation; i++) {
  24332. if (!isTop) {
  24333. indices.push(vbase);
  24334. indices.push(vbase + (i + 1));
  24335. indices.push(vbase + (i + 2));
  24336. }
  24337. else {
  24338. indices.push(vbase);
  24339. indices.push(vbase + (i + 2));
  24340. indices.push(vbase + (i + 1));
  24341. }
  24342. }
  24343. };
  24344. // add caps to geometry
  24345. createCylinderCap(false);
  24346. createCylinderCap(true);
  24347. // Sides
  24348. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24349. var vertexData = new VertexData();
  24350. vertexData.indices = indices;
  24351. vertexData.positions = positions;
  24352. vertexData.normals = normals;
  24353. vertexData.uvs = uvs;
  24354. if (faceColors) {
  24355. vertexData.colors = colors;
  24356. }
  24357. return vertexData;
  24358. };
  24359. VertexData.CreateTorus = function (options) {
  24360. var indices = [];
  24361. var positions = [];
  24362. var normals = [];
  24363. var uvs = [];
  24364. var diameter = options.diameter || 1;
  24365. var thickness = options.thickness || 0.5;
  24366. var tessellation = options.tessellation || 16;
  24367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24368. var stride = tessellation + 1;
  24369. for (var i = 0; i <= tessellation; i++) {
  24370. var u = i / tessellation;
  24371. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24372. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24373. for (var j = 0; j <= tessellation; j++) {
  24374. var v = 1 - j / tessellation;
  24375. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24376. var dx = Math.cos(innerAngle);
  24377. var dy = Math.sin(innerAngle);
  24378. // Create a vertex.
  24379. var normal = new BABYLON.Vector3(dx, dy, 0);
  24380. var position = normal.scale(thickness / 2);
  24381. var textureCoordinate = new BABYLON.Vector2(u, v);
  24382. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24383. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24384. positions.push(position.x, position.y, position.z);
  24385. normals.push(normal.x, normal.y, normal.z);
  24386. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24387. // And create indices for two triangles.
  24388. var nextI = (i + 1) % stride;
  24389. var nextJ = (j + 1) % stride;
  24390. indices.push(i * stride + j);
  24391. indices.push(i * stride + nextJ);
  24392. indices.push(nextI * stride + j);
  24393. indices.push(i * stride + nextJ);
  24394. indices.push(nextI * stride + nextJ);
  24395. indices.push(nextI * stride + j);
  24396. }
  24397. }
  24398. // Sides
  24399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24400. // Result
  24401. var vertexData = new VertexData();
  24402. vertexData.indices = indices;
  24403. vertexData.positions = positions;
  24404. vertexData.normals = normals;
  24405. vertexData.uvs = uvs;
  24406. return vertexData;
  24407. };
  24408. VertexData.CreateLines = function (options) {
  24409. var indices = [];
  24410. var positions = [];
  24411. var points = options.points;
  24412. for (var index = 0; index < points.length; index++) {
  24413. positions.push(points[index].x, points[index].y, points[index].z);
  24414. if (index > 0) {
  24415. indices.push(index - 1);
  24416. indices.push(index);
  24417. }
  24418. }
  24419. // Result
  24420. var vertexData = new VertexData();
  24421. vertexData.indices = indices;
  24422. vertexData.positions = positions;
  24423. return vertexData;
  24424. };
  24425. VertexData.CreateDashedLines = function (options) {
  24426. var dashSize = options.dashSize || 3;
  24427. var gapSize = options.gapSize || 1;
  24428. var dashNb = options.dashNb || 200;
  24429. var points = options.points;
  24430. var positions = new Array();
  24431. var indices = new Array();
  24432. var curvect = BABYLON.Vector3.Zero();
  24433. var lg = 0;
  24434. var nb = 0;
  24435. var shft = 0;
  24436. var dashshft = 0;
  24437. var curshft = 0;
  24438. var idx = 0;
  24439. var i = 0;
  24440. for (i = 0; i < points.length - 1; i++) {
  24441. points[i + 1].subtractToRef(points[i], curvect);
  24442. lg += curvect.length();
  24443. }
  24444. shft = lg / dashNb;
  24445. dashshft = dashSize * shft / (dashSize + gapSize);
  24446. for (i = 0; i < points.length - 1; i++) {
  24447. points[i + 1].subtractToRef(points[i], curvect);
  24448. nb = Math.floor(curvect.length() / shft);
  24449. curvect.normalize();
  24450. for (var j = 0; j < nb; j++) {
  24451. curshft = shft * j;
  24452. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24453. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24454. indices.push(idx, idx + 1);
  24455. idx += 2;
  24456. }
  24457. }
  24458. // Result
  24459. var vertexData = new VertexData();
  24460. vertexData.positions = positions;
  24461. vertexData.indices = indices;
  24462. return vertexData;
  24463. };
  24464. VertexData.CreateGround = function (options) {
  24465. var indices = [];
  24466. var positions = [];
  24467. var normals = [];
  24468. var uvs = [];
  24469. var row, col;
  24470. var width = options.width || 1;
  24471. var height = options.height || 1;
  24472. var subdivisions = options.subdivisions || 1;
  24473. for (row = 0; row <= subdivisions; row++) {
  24474. for (col = 0; col <= subdivisions; col++) {
  24475. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24476. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24477. positions.push(position.x, position.y, position.z);
  24478. normals.push(normal.x, normal.y, normal.z);
  24479. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24480. }
  24481. }
  24482. for (row = 0; row < subdivisions; row++) {
  24483. for (col = 0; col < subdivisions; col++) {
  24484. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24485. indices.push(col + 1 + row * (subdivisions + 1));
  24486. indices.push(col + row * (subdivisions + 1));
  24487. indices.push(col + (row + 1) * (subdivisions + 1));
  24488. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24489. indices.push(col + row * (subdivisions + 1));
  24490. }
  24491. }
  24492. // Result
  24493. var vertexData = new VertexData();
  24494. vertexData.indices = indices;
  24495. vertexData.positions = positions;
  24496. vertexData.normals = normals;
  24497. vertexData.uvs = uvs;
  24498. return vertexData;
  24499. };
  24500. VertexData.CreateTiledGround = function (options) {
  24501. var xmin = options.xmin;
  24502. var zmin = options.zmin;
  24503. var xmax = options.xmax;
  24504. var zmax = options.zmax;
  24505. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24506. var precision = options.precision || { w: 1, h: 1 };
  24507. var indices = [];
  24508. var positions = [];
  24509. var normals = [];
  24510. var uvs = [];
  24511. var row, col, tileRow, tileCol;
  24512. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24513. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24514. precision.w = (precision.w < 1) ? 1 : precision.w;
  24515. precision.h = (precision.h < 1) ? 1 : precision.h;
  24516. var tileSize = {
  24517. 'w': (xmax - xmin) / subdivisions.w,
  24518. 'h': (zmax - zmin) / subdivisions.h
  24519. };
  24520. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24521. // Indices
  24522. var base = positions.length / 3;
  24523. var rowLength = precision.w + 1;
  24524. for (row = 0; row < precision.h; row++) {
  24525. for (col = 0; col < precision.w; col++) {
  24526. var square = [
  24527. base + col + row * rowLength,
  24528. base + (col + 1) + row * rowLength,
  24529. base + (col + 1) + (row + 1) * rowLength,
  24530. base + col + (row + 1) * rowLength
  24531. ];
  24532. indices.push(square[1]);
  24533. indices.push(square[2]);
  24534. indices.push(square[3]);
  24535. indices.push(square[0]);
  24536. indices.push(square[1]);
  24537. indices.push(square[3]);
  24538. }
  24539. }
  24540. // Position, normals and uvs
  24541. var position = BABYLON.Vector3.Zero();
  24542. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24543. for (row = 0; row <= precision.h; row++) {
  24544. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24545. for (col = 0; col <= precision.w; col++) {
  24546. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24547. position.y = 0;
  24548. positions.push(position.x, position.y, position.z);
  24549. normals.push(normal.x, normal.y, normal.z);
  24550. uvs.push(col / precision.w, row / precision.h);
  24551. }
  24552. }
  24553. }
  24554. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24555. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24556. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24557. }
  24558. }
  24559. // Result
  24560. var vertexData = new VertexData();
  24561. vertexData.indices = indices;
  24562. vertexData.positions = positions;
  24563. vertexData.normals = normals;
  24564. vertexData.uvs = uvs;
  24565. return vertexData;
  24566. };
  24567. VertexData.CreateGroundFromHeightMap = function (options) {
  24568. var indices = [];
  24569. var positions = [];
  24570. var normals = [];
  24571. var uvs = [];
  24572. var row, col;
  24573. // Vertices
  24574. for (row = 0; row <= options.subdivisions; row++) {
  24575. for (col = 0; col <= options.subdivisions; col++) {
  24576. 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));
  24577. // Compute height
  24578. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24579. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24580. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24581. var r = options.buffer[pos] / 255.0;
  24582. var g = options.buffer[pos + 1] / 255.0;
  24583. var b = options.buffer[pos + 2] / 255.0;
  24584. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24585. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24586. // Add vertex
  24587. positions.push(position.x, position.y, position.z);
  24588. normals.push(0, 0, 0);
  24589. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24590. }
  24591. }
  24592. // Indices
  24593. for (row = 0; row < options.subdivisions; row++) {
  24594. for (col = 0; col < options.subdivisions; col++) {
  24595. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24596. indices.push(col + 1 + row * (options.subdivisions + 1));
  24597. indices.push(col + row * (options.subdivisions + 1));
  24598. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24599. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24600. indices.push(col + row * (options.subdivisions + 1));
  24601. }
  24602. }
  24603. // Normals
  24604. VertexData.ComputeNormals(positions, indices, normals);
  24605. // Result
  24606. var vertexData = new VertexData();
  24607. vertexData.indices = indices;
  24608. vertexData.positions = positions;
  24609. vertexData.normals = normals;
  24610. vertexData.uvs = uvs;
  24611. return vertexData;
  24612. };
  24613. VertexData.CreatePlane = function (options) {
  24614. var indices = [];
  24615. var positions = [];
  24616. var normals = [];
  24617. var uvs = [];
  24618. var width = options.width || options.size || 1;
  24619. var height = options.height || options.size || 1;
  24620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24621. // Vertices
  24622. var halfWidth = width / 2.0;
  24623. var halfHeight = height / 2.0;
  24624. positions.push(-halfWidth, -halfHeight, 0);
  24625. normals.push(0, 0, -1.0);
  24626. uvs.push(0.0, 0.0);
  24627. positions.push(halfWidth, -halfHeight, 0);
  24628. normals.push(0, 0, -1.0);
  24629. uvs.push(1.0, 0.0);
  24630. positions.push(halfWidth, halfHeight, 0);
  24631. normals.push(0, 0, -1.0);
  24632. uvs.push(1.0, 1.0);
  24633. positions.push(-halfWidth, halfHeight, 0);
  24634. normals.push(0, 0, -1.0);
  24635. uvs.push(0.0, 1.0);
  24636. // Indices
  24637. indices.push(0);
  24638. indices.push(1);
  24639. indices.push(2);
  24640. indices.push(0);
  24641. indices.push(2);
  24642. indices.push(3);
  24643. // Sides
  24644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24645. // Result
  24646. var vertexData = new VertexData();
  24647. vertexData.indices = indices;
  24648. vertexData.positions = positions;
  24649. vertexData.normals = normals;
  24650. vertexData.uvs = uvs;
  24651. return vertexData;
  24652. };
  24653. VertexData.CreateDisc = function (options) {
  24654. var positions = [];
  24655. var indices = [];
  24656. var normals = [];
  24657. var uvs = [];
  24658. var radius = options.radius || 0.5;
  24659. var tessellation = options.tessellation || 64;
  24660. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24662. // positions and uvs
  24663. positions.push(0, 0, 0); // disc center first
  24664. uvs.push(0.5, 0.5);
  24665. var theta = Math.PI * 2 * arc;
  24666. var step = theta / tessellation;
  24667. for (var a = 0; a < theta; a += step) {
  24668. var x = Math.cos(a);
  24669. var y = Math.sin(a);
  24670. var u = (x + 1) / 2;
  24671. var v = (1 - y) / 2;
  24672. positions.push(radius * x, radius * y, 0);
  24673. uvs.push(u, v);
  24674. }
  24675. if (arc === 1) {
  24676. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24677. uvs.push(uvs[2], uvs[3]);
  24678. }
  24679. //indices
  24680. var vertexNb = positions.length / 3;
  24681. for (var i = 1; i < vertexNb - 1; i++) {
  24682. indices.push(i + 1, 0, i);
  24683. }
  24684. // result
  24685. VertexData.ComputeNormals(positions, indices, normals);
  24686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24687. var vertexData = new VertexData();
  24688. vertexData.indices = indices;
  24689. vertexData.positions = positions;
  24690. vertexData.normals = normals;
  24691. vertexData.uvs = uvs;
  24692. return vertexData;
  24693. };
  24694. VertexData.CreateIcoSphere = function (options) {
  24695. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24696. var radius = options.radius || 1;
  24697. var flat = (options.flat === undefined) ? true : options.flat;
  24698. var subdivisions = options.subdivisions || 4;
  24699. var radiusX = options.radiusX || radius;
  24700. var radiusY = options.radiusY || radius;
  24701. var radiusZ = options.radiusZ || radius;
  24702. var t = (1 + Math.sqrt(5)) / 2;
  24703. // 12 vertex x,y,z
  24704. var ico_vertices = [
  24705. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24706. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24707. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24708. ];
  24709. // index of 3 vertex makes a face of icopshere
  24710. var ico_indices = [
  24711. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24712. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24713. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24714. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24715. ];
  24716. // vertex for uv have aliased position, not for UV
  24717. var vertices_unalias_id = [
  24718. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24719. // vertex alias
  24720. 0,
  24721. 2,
  24722. 3,
  24723. 3,
  24724. 3,
  24725. 4,
  24726. 7,
  24727. 8,
  24728. 9,
  24729. 9,
  24730. 10,
  24731. 11 // 23: B + 12
  24732. ];
  24733. // uv as integer step (not pixels !)
  24734. var ico_vertexuv = [
  24735. 5, 1, 3, 1, 6, 4, 0, 0,
  24736. 5, 3, 4, 2, 2, 2, 4, 0,
  24737. 2, 0, 1, 1, 6, 0, 6, 2,
  24738. // vertex alias (for same vertex on different faces)
  24739. 0, 4,
  24740. 3, 3,
  24741. 4, 4,
  24742. 3, 1,
  24743. 4, 2,
  24744. 4, 4,
  24745. 0, 2,
  24746. 1, 1,
  24747. 2, 2,
  24748. 3, 3,
  24749. 1, 3,
  24750. 2, 4 // 23: B + 12
  24751. ];
  24752. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24753. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24754. // First island of uv mapping
  24755. // v = 4h 3+ 2
  24756. // v = 3h 9+ 4
  24757. // v = 2h 9+ 5 B
  24758. // v = 1h 9 1 0
  24759. // v = 0h 3 8 7 A
  24760. // u = 0 1 2 3 4 5 6 *a
  24761. // Second island of uv mapping
  24762. // v = 4h 0+ B+ 4+
  24763. // v = 3h A+ 2+
  24764. // v = 2h 7+ 6 3+
  24765. // v = 1h 8+ 3+
  24766. // v = 0h
  24767. // u = 0 1 2 3 4 5 6 *a
  24768. // Face layout on texture UV mapping
  24769. // ============
  24770. // \ 4 /\ 16 / ======
  24771. // \ / \ / /\ 11 /
  24772. // \/ 7 \/ / \ /
  24773. // ======= / 10 \/
  24774. // /\ 17 /\ =======
  24775. // / \ / \ \ 15 /\
  24776. // / 8 \/ 12 \ \ / \
  24777. // ============ \/ 6 \
  24778. // \ 18 /\ ============
  24779. // \ / \ \ 5 /\ 0 /
  24780. // \/ 13 \ \ / \ /
  24781. // ======= \/ 1 \/
  24782. // =============
  24783. // /\ 19 /\ 2 /\
  24784. // / \ / \ / \
  24785. // / 14 \/ 9 \/ 3 \
  24786. // ===================
  24787. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24788. var ustep = 138 / 1024;
  24789. var vstep = 239 / 1024;
  24790. var uoffset = 60 / 1024;
  24791. var voffset = 26 / 1024;
  24792. // Second island should have margin, not to touch the first island
  24793. // avoid any borderline artefact in pixel rounding
  24794. var island_u_offset = -40 / 1024;
  24795. var island_v_offset = +20 / 1024;
  24796. // face is either island 0 or 1 :
  24797. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24798. var island = [
  24799. 0, 0, 0, 0, 1,
  24800. 0, 0, 1, 1, 0,
  24801. 0, 0, 1, 1, 0,
  24802. 0, 1, 1, 1, 0 // 15 - 19
  24803. ];
  24804. var indices = [];
  24805. var positions = [];
  24806. var normals = [];
  24807. var uvs = [];
  24808. var current_indice = 0;
  24809. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24810. var face_vertex_pos = new Array(3);
  24811. var face_vertex_uv = new Array(3);
  24812. var v012;
  24813. for (v012 = 0; v012 < 3; v012++) {
  24814. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24815. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24816. }
  24817. // create all with normals
  24818. for (var face = 0; face < 20; face++) {
  24819. // 3 vertex per face
  24820. for (v012 = 0; v012 < 3; v012++) {
  24821. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24822. var v_id = ico_indices[3 * face + v012];
  24823. // vertex have 3D position (x,y,z)
  24824. 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]);
  24825. // Normalize to get normal, then scale to radius
  24826. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24827. // uv Coordinates from vertex ID
  24828. 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);
  24829. }
  24830. // Subdivide the face (interpolate pos, norm, uv)
  24831. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24832. // - norm is linear interpolation of vertex corner normal
  24833. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24834. // - uv is linear interpolation
  24835. //
  24836. // Topology is as below for sub-divide by 2
  24837. // vertex shown as v0,v1,v2
  24838. // interp index is i1 to progress in range [v0,v1[
  24839. // interp index is i2 to progress in range [v0,v2[
  24840. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24841. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24842. //
  24843. //
  24844. // i2 v2
  24845. // ^ ^
  24846. // / / \
  24847. // / / \
  24848. // / / \
  24849. // / / (0,1) \
  24850. // / #---------\
  24851. // / / \ (0,0)'/ \
  24852. // / / \ / \
  24853. // / / \ / \
  24854. // / / (0,0) \ / (1,0) \
  24855. // / #---------#---------\
  24856. // v0 v1
  24857. //
  24858. // --------------------> i1
  24859. //
  24860. // interp of (i1,i2):
  24861. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24862. // along i1 : lerp(x0,x1, i1/(S-i2))
  24863. //
  24864. // centroid of triangle is needed to get help normal computation
  24865. // (c1,c2) are used for centroid location
  24866. var interp_vertex = function (i1, i2, c1, c2) {
  24867. // vertex is interpolated from
  24868. // - face_vertex_pos[0..2]
  24869. // - face_vertex_uv[0..2]
  24870. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24871. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24872. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24873. pos_interp.normalize();
  24874. var vertex_normal;
  24875. if (flat) {
  24876. // in flat mode, recalculate normal as face centroid normal
  24877. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24878. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24879. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24880. }
  24881. else {
  24882. // in smooth mode, recalculate normal from each single vertex position
  24883. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24884. }
  24885. // Vertex normal need correction due to X,Y,Z radius scaling
  24886. vertex_normal.x /= radiusX;
  24887. vertex_normal.y /= radiusY;
  24888. vertex_normal.z /= radiusZ;
  24889. vertex_normal.normalize();
  24890. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24891. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24892. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24893. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24894. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24895. uvs.push(uv_interp.x, uv_interp.y);
  24896. // push each vertex has member of a face
  24897. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24898. indices.push(current_indice);
  24899. current_indice++;
  24900. };
  24901. for (var i2 = 0; i2 < subdivisions; i2++) {
  24902. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24903. // face : (i1,i2) for /\ :
  24904. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24905. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24906. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24907. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24908. if (i1 + i2 + 1 < subdivisions) {
  24909. // face : (i1,i2)' for \/ :
  24910. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24911. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24912. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24913. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24914. }
  24915. }
  24916. }
  24917. }
  24918. // Sides
  24919. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24920. // Result
  24921. var vertexData = new VertexData();
  24922. vertexData.indices = indices;
  24923. vertexData.positions = positions;
  24924. vertexData.normals = normals;
  24925. vertexData.uvs = uvs;
  24926. return vertexData;
  24927. };
  24928. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24929. VertexData.CreatePolyhedron = function (options) {
  24930. // provided polyhedron types :
  24931. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24932. // 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)
  24933. var polyhedra = [];
  24934. 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]] };
  24935. 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]] };
  24936. polyhedra[2] = {
  24937. 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]],
  24938. 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]]
  24939. };
  24940. polyhedra[3] = {
  24941. 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]],
  24942. 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]]
  24943. };
  24944. polyhedra[4] = {
  24945. 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]],
  24946. 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]]
  24947. };
  24948. 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]] };
  24949. 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]] };
  24950. 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]] };
  24951. 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]] };
  24952. 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]] };
  24953. 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]] };
  24954. 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]] };
  24955. 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]] };
  24956. 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]] };
  24957. polyhedra[14] = {
  24958. 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]],
  24959. 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]]
  24960. };
  24961. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24962. var size = options.size;
  24963. var sizeX = options.sizeX || size || 1;
  24964. var sizeY = options.sizeY || size || 1;
  24965. var sizeZ = options.sizeZ || size || 1;
  24966. var data = options.custom || polyhedra[type];
  24967. var nbfaces = data.face.length;
  24968. var faceUV = options.faceUV || new Array(nbfaces);
  24969. var faceColors = options.faceColors;
  24970. var flat = (options.flat === undefined) ? true : options.flat;
  24971. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24972. var positions = [];
  24973. var indices = [];
  24974. var normals = [];
  24975. var uvs = [];
  24976. var colors = [];
  24977. var index = 0;
  24978. var faceIdx = 0; // face cursor in the array "indexes"
  24979. var indexes = [];
  24980. var i = 0;
  24981. var f = 0;
  24982. var u, v, ang, x, y, tmp;
  24983. // default face colors and UV if undefined
  24984. if (flat) {
  24985. for (f = 0; f < nbfaces; f++) {
  24986. if (faceColors && faceColors[f] === undefined) {
  24987. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24988. }
  24989. if (faceUV && faceUV[f] === undefined) {
  24990. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24991. }
  24992. }
  24993. }
  24994. if (!flat) {
  24995. for (i = 0; i < data.vertex.length; i++) {
  24996. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24997. uvs.push(0, 0);
  24998. }
  24999. for (f = 0; f < nbfaces; f++) {
  25000. for (i = 0; i < data.face[f].length - 2; i++) {
  25001. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25002. }
  25003. }
  25004. }
  25005. else {
  25006. for (f = 0; f < nbfaces; f++) {
  25007. var fl = data.face[f].length; // number of vertices of the current face
  25008. ang = 2 * Math.PI / fl;
  25009. x = 0.5 * Math.tan(ang / 2);
  25010. y = 0.5;
  25011. // positions, uvs, colors
  25012. for (i = 0; i < fl; i++) {
  25013. // positions
  25014. 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);
  25015. indexes.push(index);
  25016. index++;
  25017. // uvs
  25018. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25019. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25020. uvs.push(u, v);
  25021. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25022. y = x * Math.sin(ang) + y * Math.cos(ang);
  25023. x = tmp;
  25024. // colors
  25025. if (faceColors) {
  25026. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25027. }
  25028. }
  25029. // indices from indexes
  25030. for (i = 0; i < fl - 2; i++) {
  25031. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25032. }
  25033. faceIdx += fl;
  25034. }
  25035. }
  25036. VertexData.ComputeNormals(positions, indices, normals);
  25037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25038. var vertexData = new VertexData();
  25039. vertexData.positions = positions;
  25040. vertexData.indices = indices;
  25041. vertexData.normals = normals;
  25042. vertexData.uvs = uvs;
  25043. if (faceColors && flat) {
  25044. vertexData.colors = colors;
  25045. }
  25046. return vertexData;
  25047. };
  25048. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25049. VertexData.CreateTorusKnot = function (options) {
  25050. var indices = [];
  25051. var positions = [];
  25052. var normals = [];
  25053. var uvs = [];
  25054. var radius = options.radius || 2;
  25055. var tube = options.tube || 0.5;
  25056. var radialSegments = options.radialSegments || 32;
  25057. var tubularSegments = options.tubularSegments || 32;
  25058. var p = options.p || 2;
  25059. var q = options.q || 3;
  25060. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25061. // Helper
  25062. var getPos = function (angle) {
  25063. var cu = Math.cos(angle);
  25064. var su = Math.sin(angle);
  25065. var quOverP = q / p * angle;
  25066. var cs = Math.cos(quOverP);
  25067. var tx = radius * (2 + cs) * 0.5 * cu;
  25068. var ty = radius * (2 + cs) * su * 0.5;
  25069. var tz = radius * Math.sin(quOverP) * 0.5;
  25070. return new BABYLON.Vector3(tx, ty, tz);
  25071. };
  25072. // Vertices
  25073. var i;
  25074. var j;
  25075. for (i = 0; i <= radialSegments; i++) {
  25076. var modI = i % radialSegments;
  25077. var u = modI / radialSegments * 2 * p * Math.PI;
  25078. var p1 = getPos(u);
  25079. var p2 = getPos(u + 0.01);
  25080. var tang = p2.subtract(p1);
  25081. var n = p2.add(p1);
  25082. var bitan = BABYLON.Vector3.Cross(tang, n);
  25083. n = BABYLON.Vector3.Cross(bitan, tang);
  25084. bitan.normalize();
  25085. n.normalize();
  25086. for (j = 0; j < tubularSegments; j++) {
  25087. var modJ = j % tubularSegments;
  25088. var v = modJ / tubularSegments * 2 * Math.PI;
  25089. var cx = -tube * Math.cos(v);
  25090. var cy = tube * Math.sin(v);
  25091. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25092. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25093. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25094. uvs.push(i / radialSegments);
  25095. uvs.push(j / tubularSegments);
  25096. }
  25097. }
  25098. for (i = 0; i < radialSegments; i++) {
  25099. for (j = 0; j < tubularSegments; j++) {
  25100. var jNext = (j + 1) % tubularSegments;
  25101. var a = i * tubularSegments + j;
  25102. var b = (i + 1) * tubularSegments + j;
  25103. var c = (i + 1) * tubularSegments + jNext;
  25104. var d = i * tubularSegments + jNext;
  25105. indices.push(d);
  25106. indices.push(b);
  25107. indices.push(a);
  25108. indices.push(d);
  25109. indices.push(c);
  25110. indices.push(b);
  25111. }
  25112. }
  25113. // Normals
  25114. VertexData.ComputeNormals(positions, indices, normals);
  25115. // Sides
  25116. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25117. // Result
  25118. var vertexData = new VertexData();
  25119. vertexData.indices = indices;
  25120. vertexData.positions = positions;
  25121. vertexData.normals = normals;
  25122. vertexData.uvs = uvs;
  25123. return vertexData;
  25124. };
  25125. // Tools
  25126. /**
  25127. * @param {any} - positions (number[] or Float32Array)
  25128. * @param {any} - indices (number[] or Uint16Array)
  25129. * @param {any} - normals (number[] or Float32Array)
  25130. */
  25131. VertexData.ComputeNormals = function (positions, indices, normals) {
  25132. var index = 0;
  25133. var p1p2x = 0.0;
  25134. var p1p2y = 0.0;
  25135. var p1p2z = 0.0;
  25136. var p3p2x = 0.0;
  25137. var p3p2y = 0.0;
  25138. var p3p2z = 0.0;
  25139. var faceNormalx = 0.0;
  25140. var faceNormaly = 0.0;
  25141. var faceNormalz = 0.0;
  25142. var length = 0.0;
  25143. var i1 = 0;
  25144. var i2 = 0;
  25145. var i3 = 0;
  25146. for (index = 0; index < positions.length; index++) {
  25147. normals[index] = 0.0;
  25148. }
  25149. // indice triplet = 1 face
  25150. var nbFaces = indices.length / 3;
  25151. for (index = 0; index < nbFaces; index++) {
  25152. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25153. i2 = indices[index * 3 + 1];
  25154. i3 = indices[index * 3 + 2];
  25155. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25156. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25157. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25158. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25159. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25160. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25161. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25162. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25163. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25164. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25165. length = (length === 0) ? 1.0 : length;
  25166. faceNormalx /= length; // normalize this normal
  25167. faceNormaly /= length;
  25168. faceNormalz /= length;
  25169. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25170. normals[i1 * 3 + 1] += faceNormaly;
  25171. normals[i1 * 3 + 2] += faceNormalz;
  25172. normals[i2 * 3] += faceNormalx;
  25173. normals[i2 * 3 + 1] += faceNormaly;
  25174. normals[i2 * 3 + 2] += faceNormalz;
  25175. normals[i3 * 3] += faceNormalx;
  25176. normals[i3 * 3 + 1] += faceNormaly;
  25177. normals[i3 * 3 + 2] += faceNormalz;
  25178. }
  25179. // last normalization of each normal
  25180. for (index = 0; index < normals.length / 3; index++) {
  25181. faceNormalx = normals[index * 3];
  25182. faceNormaly = normals[index * 3 + 1];
  25183. faceNormalz = normals[index * 3 + 2];
  25184. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25185. length = (length === 0) ? 1.0 : length;
  25186. faceNormalx /= length;
  25187. faceNormaly /= length;
  25188. faceNormalz /= length;
  25189. normals[index * 3] = faceNormalx;
  25190. normals[index * 3 + 1] = faceNormaly;
  25191. normals[index * 3 + 2] = faceNormalz;
  25192. }
  25193. };
  25194. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25195. var li = indices.length;
  25196. var ln = normals.length;
  25197. var i;
  25198. var n;
  25199. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25200. switch (sideOrientation) {
  25201. case BABYLON.Mesh.FRONTSIDE:
  25202. // nothing changed
  25203. break;
  25204. case BABYLON.Mesh.BACKSIDE:
  25205. var tmp;
  25206. // indices
  25207. for (i = 0; i < li; i += 3) {
  25208. tmp = indices[i];
  25209. indices[i] = indices[i + 2];
  25210. indices[i + 2] = tmp;
  25211. }
  25212. // normals
  25213. for (n = 0; n < ln; n++) {
  25214. normals[n] = -normals[n];
  25215. }
  25216. break;
  25217. case BABYLON.Mesh.DOUBLESIDE:
  25218. // positions
  25219. var lp = positions.length;
  25220. var l = lp / 3;
  25221. for (var p = 0; p < lp; p++) {
  25222. positions[lp + p] = positions[p];
  25223. }
  25224. // indices
  25225. for (i = 0; i < li; i += 3) {
  25226. indices[i + li] = indices[i + 2] + l;
  25227. indices[i + 1 + li] = indices[i + 1] + l;
  25228. indices[i + 2 + li] = indices[i] + l;
  25229. }
  25230. // normals
  25231. for (n = 0; n < ln; n++) {
  25232. normals[ln + n] = -normals[n];
  25233. }
  25234. // uvs
  25235. var lu = uvs.length;
  25236. for (var u = 0; u < lu; u++) {
  25237. uvs[u + lu] = uvs[u];
  25238. }
  25239. break;
  25240. }
  25241. };
  25242. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25243. var vertexData = new VertexData();
  25244. // positions
  25245. var positions = parsedVertexData.positions;
  25246. if (positions) {
  25247. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25248. }
  25249. // normals
  25250. var normals = parsedVertexData.normals;
  25251. if (normals) {
  25252. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25253. }
  25254. // uvs
  25255. var uvs = parsedVertexData.uvs;
  25256. if (uvs) {
  25257. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25258. }
  25259. // uv2s
  25260. var uv2s = parsedVertexData.uv2s;
  25261. if (uv2s) {
  25262. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25263. }
  25264. // uv3s
  25265. var uv3s = parsedVertexData.uv3s;
  25266. if (uv3s) {
  25267. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25268. }
  25269. // uv4s
  25270. var uv4s = parsedVertexData.uv4s;
  25271. if (uv4s) {
  25272. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25273. }
  25274. // uv5s
  25275. var uv5s = parsedVertexData.uv5s;
  25276. if (uv5s) {
  25277. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25278. }
  25279. // uv6s
  25280. var uv6s = parsedVertexData.uv6s;
  25281. if (uv6s) {
  25282. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25283. }
  25284. // colors
  25285. var colors = parsedVertexData.colors;
  25286. if (colors) {
  25287. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25288. }
  25289. // matricesIndices
  25290. var matricesIndices = parsedVertexData.matricesIndices;
  25291. if (matricesIndices) {
  25292. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25293. }
  25294. // matricesWeights
  25295. var matricesWeights = parsedVertexData.matricesWeights;
  25296. if (matricesWeights) {
  25297. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25298. }
  25299. // indices
  25300. var indices = parsedVertexData.indices;
  25301. if (indices) {
  25302. vertexData.indices = indices;
  25303. }
  25304. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25305. };
  25306. return VertexData;
  25307. })();
  25308. BABYLON.VertexData = VertexData;
  25309. })(BABYLON || (BABYLON = {}));
  25310. var BABYLON;
  25311. (function (BABYLON) {
  25312. var Tags = (function () {
  25313. function Tags() {
  25314. }
  25315. Tags.EnableFor = function (obj) {
  25316. obj._tags = obj._tags || {};
  25317. obj.hasTags = function () {
  25318. return Tags.HasTags(obj);
  25319. };
  25320. obj.addTags = function (tagsString) {
  25321. return Tags.AddTagsTo(obj, tagsString);
  25322. };
  25323. obj.removeTags = function (tagsString) {
  25324. return Tags.RemoveTagsFrom(obj, tagsString);
  25325. };
  25326. obj.matchesTagsQuery = function (tagsQuery) {
  25327. return Tags.MatchesQuery(obj, tagsQuery);
  25328. };
  25329. };
  25330. Tags.DisableFor = function (obj) {
  25331. delete obj._tags;
  25332. delete obj.hasTags;
  25333. delete obj.addTags;
  25334. delete obj.removeTags;
  25335. delete obj.matchesTagsQuery;
  25336. };
  25337. Tags.HasTags = function (obj) {
  25338. if (!obj._tags) {
  25339. return false;
  25340. }
  25341. return !BABYLON.Tools.IsEmpty(obj._tags);
  25342. };
  25343. Tags.GetTags = function (obj, asString) {
  25344. if (asString === void 0) { asString = true; }
  25345. if (!obj._tags) {
  25346. return null;
  25347. }
  25348. if (asString) {
  25349. var tagsArray = [];
  25350. for (var tag in obj._tags) {
  25351. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25352. tagsArray.push(tag);
  25353. }
  25354. }
  25355. return tagsArray.join(" ");
  25356. }
  25357. else {
  25358. return obj._tags;
  25359. }
  25360. };
  25361. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25362. // a tag cannot start with '||', '&&', and '!'
  25363. // it cannot contain whitespaces
  25364. Tags.AddTagsTo = function (obj, tagsString) {
  25365. if (!tagsString) {
  25366. return;
  25367. }
  25368. if (typeof tagsString !== "string") {
  25369. return;
  25370. }
  25371. var tags = tagsString.split(" ");
  25372. for (var t in tags) {
  25373. Tags._AddTagTo(obj, tags[t]);
  25374. }
  25375. };
  25376. Tags._AddTagTo = function (obj, tag) {
  25377. tag = tag.trim();
  25378. if (tag === "" || tag === "true" || tag === "false") {
  25379. return;
  25380. }
  25381. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25382. return;
  25383. }
  25384. Tags.EnableFor(obj);
  25385. obj._tags[tag] = true;
  25386. };
  25387. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25388. if (!Tags.HasTags(obj)) {
  25389. return;
  25390. }
  25391. var tags = tagsString.split(" ");
  25392. for (var t in tags) {
  25393. Tags._RemoveTagFrom(obj, tags[t]);
  25394. }
  25395. };
  25396. Tags._RemoveTagFrom = function (obj, tag) {
  25397. delete obj._tags[tag];
  25398. };
  25399. Tags.MatchesQuery = function (obj, tagsQuery) {
  25400. if (tagsQuery === undefined) {
  25401. return true;
  25402. }
  25403. if (tagsQuery === "") {
  25404. return Tags.HasTags(obj);
  25405. }
  25406. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25407. };
  25408. return Tags;
  25409. })();
  25410. BABYLON.Tags = Tags;
  25411. })(BABYLON || (BABYLON = {}));
  25412. var BABYLON;
  25413. (function (BABYLON) {
  25414. var Internals;
  25415. (function (Internals) {
  25416. var AndOrNotEvaluator = (function () {
  25417. function AndOrNotEvaluator() {
  25418. }
  25419. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25420. if (!query.match(/\([^\(\)]*\)/g)) {
  25421. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25422. }
  25423. else {
  25424. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25425. // remove parenthesis
  25426. r = r.slice(1, r.length - 1);
  25427. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25428. });
  25429. }
  25430. if (query === "true") {
  25431. return true;
  25432. }
  25433. if (query === "false") {
  25434. return false;
  25435. }
  25436. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25437. };
  25438. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25439. evaluateCallback = evaluateCallback || (function (r) {
  25440. return r === "true" ? true : false;
  25441. });
  25442. var result;
  25443. var or = parenthesisContent.split("||");
  25444. for (var i in or) {
  25445. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25446. var and = ori.split("&&");
  25447. if (and.length > 1) {
  25448. for (var j = 0; j < and.length; ++j) {
  25449. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25450. if (andj !== "true" && andj !== "false") {
  25451. if (andj[0] === "!") {
  25452. result = !evaluateCallback(andj.substring(1));
  25453. }
  25454. else {
  25455. result = evaluateCallback(andj);
  25456. }
  25457. }
  25458. else {
  25459. result = andj === "true" ? true : false;
  25460. }
  25461. if (!result) {
  25462. ori = "false";
  25463. break;
  25464. }
  25465. }
  25466. }
  25467. if (result || ori === "true") {
  25468. result = true;
  25469. break;
  25470. }
  25471. // result equals false (or undefined)
  25472. if (ori !== "true" && ori !== "false") {
  25473. if (ori[0] === "!") {
  25474. result = !evaluateCallback(ori.substring(1));
  25475. }
  25476. else {
  25477. result = evaluateCallback(ori);
  25478. }
  25479. }
  25480. else {
  25481. result = ori === "true" ? true : false;
  25482. }
  25483. }
  25484. // the whole parenthesis scope is replaced by 'true' or 'false'
  25485. return result ? "true" : "false";
  25486. };
  25487. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25488. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25489. // remove whitespaces
  25490. r = r.replace(/[\s]/g, function () { return ""; });
  25491. return r.length % 2 ? "!" : "";
  25492. });
  25493. booleanString = booleanString.trim();
  25494. if (booleanString === "!true") {
  25495. booleanString = "false";
  25496. }
  25497. else if (booleanString === "!false") {
  25498. booleanString = "true";
  25499. }
  25500. return booleanString;
  25501. };
  25502. return AndOrNotEvaluator;
  25503. })();
  25504. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25506. })(BABYLON || (BABYLON = {}));
  25507. var BABYLON;
  25508. (function (BABYLON) {
  25509. var PostProcessRenderPass = (function () {
  25510. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25511. this._enabled = true;
  25512. this._refCount = 0;
  25513. this._name = name;
  25514. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25515. this.setRenderList(renderList);
  25516. this._renderTexture.onBeforeRender = beforeRender;
  25517. this._renderTexture.onAfterRender = afterRender;
  25518. this._scene = scene;
  25519. this._renderList = renderList;
  25520. }
  25521. // private
  25522. PostProcessRenderPass.prototype._incRefCount = function () {
  25523. if (this._refCount === 0) {
  25524. this._scene.customRenderTargets.push(this._renderTexture);
  25525. }
  25526. return ++this._refCount;
  25527. };
  25528. PostProcessRenderPass.prototype._decRefCount = function () {
  25529. this._refCount--;
  25530. if (this._refCount <= 0) {
  25531. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25532. }
  25533. return this._refCount;
  25534. };
  25535. PostProcessRenderPass.prototype._update = function () {
  25536. this.setRenderList(this._renderList);
  25537. };
  25538. // public
  25539. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25540. this._renderTexture.renderList = renderList;
  25541. };
  25542. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25543. return this._renderTexture;
  25544. };
  25545. return PostProcessRenderPass;
  25546. })();
  25547. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25548. })(BABYLON || (BABYLON = {}));
  25549. var BABYLON;
  25550. (function (BABYLON) {
  25551. var PostProcessRenderEffect = (function () {
  25552. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25553. this._engine = engine;
  25554. this._name = name;
  25555. this._singleInstance = singleInstance || true;
  25556. this._getPostProcess = getPostProcess;
  25557. this._cameras = [];
  25558. this._indicesForCamera = [];
  25559. this._postProcesses = {};
  25560. this._renderPasses = {};
  25561. this._renderEffectAsPasses = {};
  25562. }
  25563. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25564. get: function () {
  25565. for (var index in this._postProcesses) {
  25566. if (!this._postProcesses[index].isSupported) {
  25567. return false;
  25568. }
  25569. }
  25570. return true;
  25571. },
  25572. enumerable: true,
  25573. configurable: true
  25574. });
  25575. PostProcessRenderEffect.prototype._update = function () {
  25576. for (var renderPassName in this._renderPasses) {
  25577. this._renderPasses[renderPassName]._update();
  25578. }
  25579. };
  25580. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25581. this._renderPasses[renderPass._name] = renderPass;
  25582. this._linkParameters();
  25583. };
  25584. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25585. delete this._renderPasses[renderPass._name];
  25586. this._linkParameters();
  25587. };
  25588. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25589. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25590. this._linkParameters();
  25591. };
  25592. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25593. for (var renderPassName in this._renderPasses) {
  25594. if (renderPassName === passName) {
  25595. return this._renderPasses[passName];
  25596. }
  25597. }
  25598. };
  25599. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25600. this._renderPasses = {};
  25601. this._linkParameters();
  25602. };
  25603. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25604. var cameraKey;
  25605. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25606. for (var i = 0; i < _cam.length; i++) {
  25607. var camera = _cam[i];
  25608. var cameraName = camera.name;
  25609. if (this._singleInstance) {
  25610. cameraKey = 0;
  25611. }
  25612. else {
  25613. cameraKey = cameraName;
  25614. }
  25615. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25616. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25617. if (!this._indicesForCamera[cameraName]) {
  25618. this._indicesForCamera[cameraName] = [];
  25619. }
  25620. this._indicesForCamera[cameraName].push(index);
  25621. if (this._cameras.indexOf(camera) === -1) {
  25622. this._cameras[cameraName] = camera;
  25623. }
  25624. for (var passName in this._renderPasses) {
  25625. this._renderPasses[passName]._incRefCount();
  25626. }
  25627. }
  25628. this._linkParameters();
  25629. };
  25630. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25631. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25632. for (var i = 0; i < _cam.length; i++) {
  25633. var camera = _cam[i];
  25634. var cameraName = camera.name;
  25635. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25636. var index = this._cameras.indexOf(cameraName);
  25637. this._indicesForCamera.splice(index, 1);
  25638. this._cameras.splice(index, 1);
  25639. for (var passName in this._renderPasses) {
  25640. this._renderPasses[passName]._decRefCount();
  25641. }
  25642. }
  25643. };
  25644. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25646. for (var i = 0; i < _cam.length; i++) {
  25647. var camera = _cam[i];
  25648. var cameraName = camera.name;
  25649. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25650. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25651. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25652. }
  25653. }
  25654. for (var passName in this._renderPasses) {
  25655. this._renderPasses[passName]._incRefCount();
  25656. }
  25657. }
  25658. };
  25659. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25660. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25661. for (var i = 0; i < _cam.length; i++) {
  25662. var camera = _cam[i];
  25663. var cameraName = camera.Name;
  25664. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25665. for (var passName in this._renderPasses) {
  25666. this._renderPasses[passName]._decRefCount();
  25667. }
  25668. }
  25669. };
  25670. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25671. if (this._singleInstance) {
  25672. return this._postProcesses[0];
  25673. }
  25674. else {
  25675. return this._postProcesses[camera.name];
  25676. }
  25677. };
  25678. PostProcessRenderEffect.prototype._linkParameters = function () {
  25679. var _this = this;
  25680. for (var index in this._postProcesses) {
  25681. if (this.applyParameters) {
  25682. this.applyParameters(this._postProcesses[index]);
  25683. }
  25684. this._postProcesses[index].onBeforeRender = function (effect) {
  25685. _this._linkTextures(effect);
  25686. };
  25687. }
  25688. };
  25689. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25690. for (var renderPassName in this._renderPasses) {
  25691. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25692. }
  25693. for (var renderEffectName in this._renderEffectAsPasses) {
  25694. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25695. }
  25696. };
  25697. return PostProcessRenderEffect;
  25698. })();
  25699. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25700. })(BABYLON || (BABYLON = {}));
  25701. var BABYLON;
  25702. (function (BABYLON) {
  25703. var PostProcessRenderPipeline = (function () {
  25704. function PostProcessRenderPipeline(engine, name) {
  25705. this._engine = engine;
  25706. this._name = name;
  25707. this._renderEffects = {};
  25708. this._renderEffectsForIsolatedPass = {};
  25709. this._cameras = [];
  25710. }
  25711. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25712. get: function () {
  25713. for (var renderEffectName in this._renderEffects) {
  25714. if (!this._renderEffects[renderEffectName].isSupported) {
  25715. return false;
  25716. }
  25717. }
  25718. return true;
  25719. },
  25720. enumerable: true,
  25721. configurable: true
  25722. });
  25723. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25724. this._renderEffects[renderEffect._name] = renderEffect;
  25725. };
  25726. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25727. var renderEffects = this._renderEffects[renderEffectName];
  25728. if (!renderEffects) {
  25729. return;
  25730. }
  25731. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25732. };
  25733. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25734. var renderEffects = this._renderEffects[renderEffectName];
  25735. if (!renderEffects) {
  25736. return;
  25737. }
  25738. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25739. };
  25740. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25741. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25742. var indicesToDelete = [];
  25743. var i;
  25744. for (i = 0; i < _cam.length; i++) {
  25745. var camera = _cam[i];
  25746. var cameraName = camera.name;
  25747. if (this._cameras.indexOf(camera) === -1) {
  25748. this._cameras[cameraName] = camera;
  25749. }
  25750. else if (unique) {
  25751. indicesToDelete.push(i);
  25752. }
  25753. }
  25754. for (i = 0; i < indicesToDelete.length; i++) {
  25755. cameras.splice(indicesToDelete[i], 1);
  25756. }
  25757. for (var renderEffectName in this._renderEffects) {
  25758. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25759. }
  25760. };
  25761. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25762. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25763. for (var renderEffectName in this._renderEffects) {
  25764. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25765. }
  25766. for (var i = 0; i < _cam.length; i++) {
  25767. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25768. }
  25769. };
  25770. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25771. var _this = this;
  25772. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25773. var pass = null;
  25774. var renderEffectName;
  25775. for (renderEffectName in this._renderEffects) {
  25776. pass = this._renderEffects[renderEffectName].getPass(passName);
  25777. if (pass != null) {
  25778. break;
  25779. }
  25780. }
  25781. if (pass === null) {
  25782. return;
  25783. }
  25784. for (renderEffectName in this._renderEffects) {
  25785. this._renderEffects[renderEffectName]._disable(_cam);
  25786. }
  25787. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25788. for (var i = 0; i < _cam.length; i++) {
  25789. var camera = _cam[i];
  25790. var cameraName = camera.name;
  25791. 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); });
  25792. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25793. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25794. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25795. }
  25796. };
  25797. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25798. var _this = this;
  25799. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25800. for (var i = 0; i < _cam.length; i++) {
  25801. var camera = _cam[i];
  25802. var cameraName = camera.name;
  25803. 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); });
  25804. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25805. }
  25806. for (var renderEffectName in this._renderEffects) {
  25807. this._renderEffects[renderEffectName]._enable(_cam);
  25808. }
  25809. };
  25810. PostProcessRenderPipeline.prototype._update = function () {
  25811. for (var renderEffectName in this._renderEffects) {
  25812. this._renderEffects[renderEffectName]._update();
  25813. }
  25814. for (var i = 0; i < this._cameras.length; i++) {
  25815. var cameraName = this._cameras[i].name;
  25816. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25817. this._renderEffectsForIsolatedPass[cameraName]._update();
  25818. }
  25819. }
  25820. };
  25821. PostProcessRenderPipeline.prototype.dispose = function () {
  25822. // Must be implemented by children
  25823. };
  25824. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25825. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25826. return PostProcessRenderPipeline;
  25827. })();
  25828. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25829. })(BABYLON || (BABYLON = {}));
  25830. var BABYLON;
  25831. (function (BABYLON) {
  25832. var PostProcessRenderPipelineManager = (function () {
  25833. function PostProcessRenderPipelineManager() {
  25834. this._renderPipelines = {};
  25835. }
  25836. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25837. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25838. };
  25839. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25840. var renderPipeline = this._renderPipelines[renderPipelineName];
  25841. if (!renderPipeline) {
  25842. return;
  25843. }
  25844. renderPipeline._attachCameras(cameras, unique);
  25845. };
  25846. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25847. var renderPipeline = this._renderPipelines[renderPipelineName];
  25848. if (!renderPipeline) {
  25849. return;
  25850. }
  25851. renderPipeline._detachCameras(cameras);
  25852. };
  25853. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25854. var renderPipeline = this._renderPipelines[renderPipelineName];
  25855. if (!renderPipeline) {
  25856. return;
  25857. }
  25858. renderPipeline._enableEffect(renderEffectName, cameras);
  25859. };
  25860. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25861. var renderPipeline = this._renderPipelines[renderPipelineName];
  25862. if (!renderPipeline) {
  25863. return;
  25864. }
  25865. renderPipeline._disableEffect(renderEffectName, cameras);
  25866. };
  25867. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25868. var renderPipeline = this._renderPipelines[renderPipelineName];
  25869. if (!renderPipeline) {
  25870. return;
  25871. }
  25872. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25873. };
  25874. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25875. var renderPipeline = this._renderPipelines[renderPipelineName];
  25876. if (!renderPipeline) {
  25877. return;
  25878. }
  25879. renderPipeline._disableDisplayOnlyPass(cameras);
  25880. };
  25881. PostProcessRenderPipelineManager.prototype.update = function () {
  25882. for (var renderPipelineName in this._renderPipelines) {
  25883. var pipeline = this._renderPipelines[renderPipelineName];
  25884. if (!pipeline.isSupported) {
  25885. pipeline.dispose();
  25886. delete this._renderPipelines[renderPipelineName];
  25887. }
  25888. else {
  25889. pipeline._update();
  25890. }
  25891. }
  25892. };
  25893. return PostProcessRenderPipelineManager;
  25894. })();
  25895. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25896. })(BABYLON || (BABYLON = {}));
  25897. var BABYLON;
  25898. (function (BABYLON) {
  25899. var BoundingBoxRenderer = (function () {
  25900. function BoundingBoxRenderer(scene) {
  25901. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25902. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25903. this.showBackLines = true;
  25904. this.renderList = new BABYLON.SmartArray(32);
  25905. this._scene = scene;
  25906. }
  25907. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25908. if (this._colorShader) {
  25909. return;
  25910. }
  25911. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25912. attributes: ["position"],
  25913. uniforms: ["worldViewProjection", "color"]
  25914. });
  25915. var engine = this._scene.getEngine();
  25916. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25917. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25918. 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]);
  25919. };
  25920. BoundingBoxRenderer.prototype.reset = function () {
  25921. this.renderList.reset();
  25922. };
  25923. BoundingBoxRenderer.prototype.render = function () {
  25924. if (this.renderList.length === 0) {
  25925. return;
  25926. }
  25927. this._prepareRessources();
  25928. if (!this._colorShader.isReady()) {
  25929. return;
  25930. }
  25931. var engine = this._scene.getEngine();
  25932. engine.setDepthWrite(false);
  25933. this._colorShader._preBind();
  25934. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25935. var boundingBox = this.renderList.data[boundingBoxIndex];
  25936. var min = boundingBox.minimum;
  25937. var max = boundingBox.maximum;
  25938. var diff = max.subtract(min);
  25939. var median = min.add(diff.scale(0.5));
  25940. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25941. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25942. .multiply(boundingBox.getWorldMatrix());
  25943. // VBOs
  25944. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25945. if (this.showBackLines) {
  25946. // Back
  25947. engine.setDepthFunctionToGreaterOrEqual();
  25948. this._scene.resetCachedMaterial();
  25949. this._colorShader.setColor4("color", this.backColor.toColor4());
  25950. this._colorShader.bind(worldMatrix);
  25951. // Draw order
  25952. engine.draw(false, 0, 24);
  25953. }
  25954. // Front
  25955. engine.setDepthFunctionToLess();
  25956. this._scene.resetCachedMaterial();
  25957. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25958. this._colorShader.bind(worldMatrix);
  25959. // Draw order
  25960. engine.draw(false, 0, 24);
  25961. }
  25962. this._colorShader.unbind();
  25963. engine.setDepthFunctionToLessOrEqual();
  25964. engine.setDepthWrite(true);
  25965. };
  25966. BoundingBoxRenderer.prototype.dispose = function () {
  25967. if (!this._colorShader) {
  25968. return;
  25969. }
  25970. this._colorShader.dispose();
  25971. this._vb.dispose();
  25972. this._scene.getEngine()._releaseBuffer(this._ib);
  25973. };
  25974. return BoundingBoxRenderer;
  25975. })();
  25976. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25977. })(BABYLON || (BABYLON = {}));
  25978. var BABYLON;
  25979. (function (BABYLON) {
  25980. var Condition = (function () {
  25981. function Condition(actionManager) {
  25982. this._actionManager = actionManager;
  25983. }
  25984. Condition.prototype.isValid = function () {
  25985. return true;
  25986. };
  25987. Condition.prototype._getProperty = function (propertyPath) {
  25988. return this._actionManager._getProperty(propertyPath);
  25989. };
  25990. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25991. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25992. };
  25993. return Condition;
  25994. })();
  25995. BABYLON.Condition = Condition;
  25996. var ValueCondition = (function (_super) {
  25997. __extends(ValueCondition, _super);
  25998. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25999. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26000. _super.call(this, actionManager);
  26001. this.propertyPath = propertyPath;
  26002. this.value = value;
  26003. this.operator = operator;
  26004. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26005. this._property = this._getProperty(this.propertyPath);
  26006. }
  26007. Object.defineProperty(ValueCondition, "IsEqual", {
  26008. get: function () {
  26009. return ValueCondition._IsEqual;
  26010. },
  26011. enumerable: true,
  26012. configurable: true
  26013. });
  26014. Object.defineProperty(ValueCondition, "IsDifferent", {
  26015. get: function () {
  26016. return ValueCondition._IsDifferent;
  26017. },
  26018. enumerable: true,
  26019. configurable: true
  26020. });
  26021. Object.defineProperty(ValueCondition, "IsGreater", {
  26022. get: function () {
  26023. return ValueCondition._IsGreater;
  26024. },
  26025. enumerable: true,
  26026. configurable: true
  26027. });
  26028. Object.defineProperty(ValueCondition, "IsLesser", {
  26029. get: function () {
  26030. return ValueCondition._IsLesser;
  26031. },
  26032. enumerable: true,
  26033. configurable: true
  26034. });
  26035. // Methods
  26036. ValueCondition.prototype.isValid = function () {
  26037. switch (this.operator) {
  26038. case ValueCondition.IsGreater:
  26039. return this._target[this._property] > this.value;
  26040. case ValueCondition.IsLesser:
  26041. return this._target[this._property] < this.value;
  26042. case ValueCondition.IsEqual:
  26043. case ValueCondition.IsDifferent:
  26044. var check;
  26045. if (this.value.equals) {
  26046. check = this.value.equals(this._target[this._property]);
  26047. }
  26048. else {
  26049. check = this.value === this._target[this._property];
  26050. }
  26051. return this.operator === ValueCondition.IsEqual ? check : !check;
  26052. }
  26053. return false;
  26054. };
  26055. // Statics
  26056. ValueCondition._IsEqual = 0;
  26057. ValueCondition._IsDifferent = 1;
  26058. ValueCondition._IsGreater = 2;
  26059. ValueCondition._IsLesser = 3;
  26060. return ValueCondition;
  26061. })(Condition);
  26062. BABYLON.ValueCondition = ValueCondition;
  26063. var PredicateCondition = (function (_super) {
  26064. __extends(PredicateCondition, _super);
  26065. function PredicateCondition(actionManager, predicate) {
  26066. _super.call(this, actionManager);
  26067. this.predicate = predicate;
  26068. }
  26069. PredicateCondition.prototype.isValid = function () {
  26070. return this.predicate();
  26071. };
  26072. return PredicateCondition;
  26073. })(Condition);
  26074. BABYLON.PredicateCondition = PredicateCondition;
  26075. var StateCondition = (function (_super) {
  26076. __extends(StateCondition, _super);
  26077. function StateCondition(actionManager, target, value) {
  26078. _super.call(this, actionManager);
  26079. this.value = value;
  26080. this._target = target;
  26081. }
  26082. // Methods
  26083. StateCondition.prototype.isValid = function () {
  26084. return this._target.state === this.value;
  26085. };
  26086. return StateCondition;
  26087. })(Condition);
  26088. BABYLON.StateCondition = StateCondition;
  26089. })(BABYLON || (BABYLON = {}));
  26090. var BABYLON;
  26091. (function (BABYLON) {
  26092. var Action = (function () {
  26093. function Action(triggerOptions, condition) {
  26094. this.triggerOptions = triggerOptions;
  26095. if (triggerOptions.parameter) {
  26096. this.trigger = triggerOptions.trigger;
  26097. this._triggerParameter = triggerOptions.parameter;
  26098. }
  26099. else {
  26100. this.trigger = triggerOptions;
  26101. }
  26102. this._nextActiveAction = this;
  26103. this._condition = condition;
  26104. }
  26105. // Methods
  26106. Action.prototype._prepare = function () {
  26107. };
  26108. Action.prototype.getTriggerParameter = function () {
  26109. return this._triggerParameter;
  26110. };
  26111. Action.prototype._executeCurrent = function (evt) {
  26112. if (this._nextActiveAction._condition) {
  26113. var condition = this._nextActiveAction._condition;
  26114. var currentRenderId = this._actionManager.getScene().getRenderId();
  26115. // We cache the current evaluation for the current frame
  26116. if (condition._evaluationId === currentRenderId) {
  26117. if (!condition._currentResult) {
  26118. return;
  26119. }
  26120. }
  26121. else {
  26122. condition._evaluationId = currentRenderId;
  26123. if (!condition.isValid()) {
  26124. condition._currentResult = false;
  26125. return;
  26126. }
  26127. condition._currentResult = true;
  26128. }
  26129. }
  26130. this._nextActiveAction.execute(evt);
  26131. this.skipToNextActiveAction();
  26132. };
  26133. Action.prototype.execute = function (evt) {
  26134. };
  26135. Action.prototype.skipToNextActiveAction = function () {
  26136. if (this._nextActiveAction._child) {
  26137. if (!this._nextActiveAction._child._actionManager) {
  26138. this._nextActiveAction._child._actionManager = this._actionManager;
  26139. }
  26140. this._nextActiveAction = this._nextActiveAction._child;
  26141. }
  26142. else {
  26143. this._nextActiveAction = this;
  26144. }
  26145. };
  26146. Action.prototype.then = function (action) {
  26147. this._child = action;
  26148. action._actionManager = this._actionManager;
  26149. action._prepare();
  26150. return action;
  26151. };
  26152. Action.prototype._getProperty = function (propertyPath) {
  26153. return this._actionManager._getProperty(propertyPath);
  26154. };
  26155. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26156. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26157. };
  26158. return Action;
  26159. })();
  26160. BABYLON.Action = Action;
  26161. })(BABYLON || (BABYLON = {}));
  26162. var BABYLON;
  26163. (function (BABYLON) {
  26164. /**
  26165. * ActionEvent is the event beint sent when an action is triggered.
  26166. */
  26167. var ActionEvent = (function () {
  26168. /**
  26169. * @constructor
  26170. * @param source The mesh or sprite that triggered the action.
  26171. * @param pointerX The X mouse cursor position at the time of the event
  26172. * @param pointerY The Y mouse cursor position at the time of the event
  26173. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26174. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26175. */
  26176. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26177. this.source = source;
  26178. this.pointerX = pointerX;
  26179. this.pointerY = pointerY;
  26180. this.meshUnderPointer = meshUnderPointer;
  26181. this.sourceEvent = sourceEvent;
  26182. this.additionalData = additionalData;
  26183. }
  26184. /**
  26185. * Helper function to auto-create an ActionEvent from a source mesh.
  26186. * @param source The source mesh that triggered the event
  26187. * @param evt {Event} The original (browser) event
  26188. */
  26189. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26190. var scene = source.getScene();
  26191. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26192. };
  26193. /**
  26194. * Helper function to auto-create an ActionEvent from a source mesh.
  26195. * @param source The source sprite that triggered the event
  26196. * @param scene Scene associated with the sprite
  26197. * @param evt {Event} The original (browser) event
  26198. */
  26199. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26200. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26201. };
  26202. /**
  26203. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26204. * @param scene the scene where the event occurred
  26205. * @param evt {Event} The original (browser) event
  26206. */
  26207. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26208. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26209. };
  26210. return ActionEvent;
  26211. })();
  26212. BABYLON.ActionEvent = ActionEvent;
  26213. /**
  26214. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26215. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26216. */
  26217. var ActionManager = (function () {
  26218. function ActionManager(scene) {
  26219. // Members
  26220. this.actions = new Array();
  26221. this._scene = scene;
  26222. scene._actionManagers.push(this);
  26223. }
  26224. Object.defineProperty(ActionManager, "NothingTrigger", {
  26225. get: function () {
  26226. return ActionManager._NothingTrigger;
  26227. },
  26228. enumerable: true,
  26229. configurable: true
  26230. });
  26231. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26232. get: function () {
  26233. return ActionManager._OnPickTrigger;
  26234. },
  26235. enumerable: true,
  26236. configurable: true
  26237. });
  26238. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26239. get: function () {
  26240. return ActionManager._OnLeftPickTrigger;
  26241. },
  26242. enumerable: true,
  26243. configurable: true
  26244. });
  26245. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26246. get: function () {
  26247. return ActionManager._OnRightPickTrigger;
  26248. },
  26249. enumerable: true,
  26250. configurable: true
  26251. });
  26252. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26253. get: function () {
  26254. return ActionManager._OnCenterPickTrigger;
  26255. },
  26256. enumerable: true,
  26257. configurable: true
  26258. });
  26259. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26260. get: function () {
  26261. return ActionManager._OnPickDownTrigger;
  26262. },
  26263. enumerable: true,
  26264. configurable: true
  26265. });
  26266. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26267. get: function () {
  26268. return ActionManager._OnPickUpTrigger;
  26269. },
  26270. enumerable: true,
  26271. configurable: true
  26272. });
  26273. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26274. /// This trigger will only be raised if you also declared a OnPickDown
  26275. get: function () {
  26276. return ActionManager._OnPickOutTrigger;
  26277. },
  26278. enumerable: true,
  26279. configurable: true
  26280. });
  26281. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26282. get: function () {
  26283. return ActionManager._OnLongPressTrigger;
  26284. },
  26285. enumerable: true,
  26286. configurable: true
  26287. });
  26288. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26289. get: function () {
  26290. return ActionManager._OnPointerOverTrigger;
  26291. },
  26292. enumerable: true,
  26293. configurable: true
  26294. });
  26295. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26296. get: function () {
  26297. return ActionManager._OnPointerOutTrigger;
  26298. },
  26299. enumerable: true,
  26300. configurable: true
  26301. });
  26302. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26303. get: function () {
  26304. return ActionManager._OnEveryFrameTrigger;
  26305. },
  26306. enumerable: true,
  26307. configurable: true
  26308. });
  26309. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26310. get: function () {
  26311. return ActionManager._OnIntersectionEnterTrigger;
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26317. get: function () {
  26318. return ActionManager._OnIntersectionExitTrigger;
  26319. },
  26320. enumerable: true,
  26321. configurable: true
  26322. });
  26323. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26324. get: function () {
  26325. return ActionManager._OnKeyDownTrigger;
  26326. },
  26327. enumerable: true,
  26328. configurable: true
  26329. });
  26330. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26331. get: function () {
  26332. return ActionManager._OnKeyUpTrigger;
  26333. },
  26334. enumerable: true,
  26335. configurable: true
  26336. });
  26337. // Methods
  26338. ActionManager.prototype.dispose = function () {
  26339. var index = this._scene._actionManagers.indexOf(this);
  26340. if (index > -1) {
  26341. this._scene._actionManagers.splice(index, 1);
  26342. }
  26343. };
  26344. ActionManager.prototype.getScene = function () {
  26345. return this._scene;
  26346. };
  26347. /**
  26348. * Does this action manager handles actions of any of the given triggers
  26349. * @param {number[]} triggers - the triggers to be tested
  26350. * @return {boolean} whether one (or more) of the triggers is handeled
  26351. */
  26352. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26353. for (var index = 0; index < this.actions.length; index++) {
  26354. var action = this.actions[index];
  26355. if (triggers.indexOf(action.trigger) > -1) {
  26356. return true;
  26357. }
  26358. }
  26359. return false;
  26360. };
  26361. /**
  26362. * Does this action manager handles actions of a given trigger
  26363. * @param {number} trigger - the trigger to be tested
  26364. * @return {boolean} whether the trigger is handeled
  26365. */
  26366. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26367. for (var index = 0; index < this.actions.length; index++) {
  26368. var action = this.actions[index];
  26369. if (action.trigger === trigger) {
  26370. return true;
  26371. }
  26372. }
  26373. return false;
  26374. };
  26375. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26376. /**
  26377. * Does this action manager has pointer triggers
  26378. * @return {boolean} whether or not it has pointer triggers
  26379. */
  26380. get: function () {
  26381. for (var index = 0; index < this.actions.length; index++) {
  26382. var action = this.actions[index];
  26383. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26384. return true;
  26385. }
  26386. }
  26387. return false;
  26388. },
  26389. enumerable: true,
  26390. configurable: true
  26391. });
  26392. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26393. /**
  26394. * Does this action manager has pick triggers
  26395. * @return {boolean} whether or not it has pick triggers
  26396. */
  26397. get: function () {
  26398. for (var index = 0; index < this.actions.length; index++) {
  26399. var action = this.actions[index];
  26400. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26401. return true;
  26402. }
  26403. }
  26404. return false;
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. /**
  26410. * Registers an action to this action manager
  26411. * @param {BABYLON.Action} action - the action to be registered
  26412. * @return {BABYLON.Action} the action amended (prepared) after registration
  26413. */
  26414. ActionManager.prototype.registerAction = function (action) {
  26415. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26416. if (this.getScene().actionManager !== this) {
  26417. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26418. return null;
  26419. }
  26420. }
  26421. this.actions.push(action);
  26422. action._actionManager = this;
  26423. action._prepare();
  26424. return action;
  26425. };
  26426. /**
  26427. * Process a specific trigger
  26428. * @param {number} trigger - the trigger to process
  26429. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26430. */
  26431. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26432. for (var index = 0; index < this.actions.length; index++) {
  26433. var action = this.actions[index];
  26434. if (action.trigger === trigger) {
  26435. if (trigger === ActionManager.OnKeyUpTrigger
  26436. || trigger === ActionManager.OnKeyDownTrigger) {
  26437. var parameter = action.getTriggerParameter();
  26438. if (parameter) {
  26439. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26440. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26441. if (actualkey !== parameter.toLowerCase()) {
  26442. continue;
  26443. }
  26444. }
  26445. }
  26446. action._executeCurrent(evt);
  26447. }
  26448. }
  26449. };
  26450. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26451. var properties = propertyPath.split(".");
  26452. for (var index = 0; index < properties.length - 1; index++) {
  26453. target = target[properties[index]];
  26454. }
  26455. return target;
  26456. };
  26457. ActionManager.prototype._getProperty = function (propertyPath) {
  26458. var properties = propertyPath.split(".");
  26459. return properties[properties.length - 1];
  26460. };
  26461. ActionManager.Parse = function (parsedActions, object, scene) {
  26462. var actionManager = new BABYLON.ActionManager(scene);
  26463. if (object === null)
  26464. scene.actionManager = actionManager;
  26465. else
  26466. object.actionManager = actionManager;
  26467. // instanciate a new object
  26468. var instanciate = function (name, params) {
  26469. var newInstance = Object.create(BABYLON[name].prototype);
  26470. newInstance.constructor.apply(newInstance, params);
  26471. return newInstance;
  26472. };
  26473. var parseParameter = function (name, value, target, propertyPath) {
  26474. if (propertyPath === null) {
  26475. // String, boolean or float
  26476. var floatValue = parseFloat(value);
  26477. if (value === "true" || value === "false")
  26478. return value === "true";
  26479. else
  26480. return isNaN(floatValue) ? value : floatValue;
  26481. }
  26482. var effectiveTarget = propertyPath.split(".");
  26483. var values = value.split(",");
  26484. // Get effective Target
  26485. for (var i = 0; i < effectiveTarget.length; i++) {
  26486. target = target[effectiveTarget[i]];
  26487. }
  26488. // Return appropriate value with its type
  26489. if (typeof (target) === "boolean")
  26490. return values[0] === "true";
  26491. if (typeof (target) === "string")
  26492. return values[0];
  26493. // Parameters with multiple values such as Vector3 etc.
  26494. var split = new Array();
  26495. for (var i = 0; i < values.length; i++)
  26496. split.push(parseFloat(values[i]));
  26497. if (target instanceof BABYLON.Vector3)
  26498. return BABYLON.Vector3.FromArray(split);
  26499. if (target instanceof BABYLON.Vector4)
  26500. return BABYLON.Vector4.FromArray(split);
  26501. if (target instanceof BABYLON.Color3)
  26502. return BABYLON.Color3.FromArray(split);
  26503. if (target instanceof BABYLON.Color4)
  26504. return BABYLON.Color4.FromArray(split);
  26505. return parseFloat(values[0]);
  26506. };
  26507. // traverse graph per trigger
  26508. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26509. if (combineArray === void 0) { combineArray = null; }
  26510. if (parsedAction.detached)
  26511. return;
  26512. var parameters = new Array();
  26513. var target = null;
  26514. var propertyPath = null;
  26515. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26516. // Parameters
  26517. if (parsedAction.type === 2)
  26518. parameters.push(actionManager);
  26519. else
  26520. parameters.push(trigger);
  26521. if (combine) {
  26522. var actions = new Array();
  26523. for (var j = 0; j < parsedAction.combine.length; j++) {
  26524. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26525. }
  26526. parameters.push(actions);
  26527. }
  26528. else {
  26529. for (var i = 0; i < parsedAction.properties.length; i++) {
  26530. var value = parsedAction.properties[i].value;
  26531. var name = parsedAction.properties[i].name;
  26532. var targetType = parsedAction.properties[i].targetType;
  26533. if (name === "target")
  26534. if (targetType !== null && targetType === "SceneProperties")
  26535. value = target = scene;
  26536. else
  26537. value = target = scene.getNodeByName(value);
  26538. else if (name === "parent")
  26539. value = scene.getNodeByName(value);
  26540. else if (name === "sound")
  26541. value = scene.getSoundByName(value);
  26542. else if (name !== "propertyPath") {
  26543. if (parsedAction.type === 2 && name === "operator")
  26544. value = BABYLON.ValueCondition[value];
  26545. else
  26546. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26547. }
  26548. else {
  26549. propertyPath = value;
  26550. }
  26551. parameters.push(value);
  26552. }
  26553. }
  26554. if (combineArray === null) {
  26555. parameters.push(condition);
  26556. }
  26557. else {
  26558. parameters.push(null);
  26559. }
  26560. // If interpolate value action
  26561. if (parsedAction.name === "InterpolateValueAction") {
  26562. var param = parameters[parameters.length - 2];
  26563. parameters[parameters.length - 1] = param;
  26564. parameters[parameters.length - 2] = condition;
  26565. }
  26566. // Action or condition(s) and not CombineAction
  26567. var newAction = instanciate(parsedAction.name, parameters);
  26568. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26569. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26570. if (action)
  26571. action.then(nothing);
  26572. else
  26573. actionManager.registerAction(nothing);
  26574. action = nothing;
  26575. }
  26576. if (combineArray === null) {
  26577. if (newAction instanceof BABYLON.Condition) {
  26578. condition = newAction;
  26579. newAction = action;
  26580. }
  26581. else {
  26582. condition = null;
  26583. if (action)
  26584. action.then(newAction);
  26585. else
  26586. actionManager.registerAction(newAction);
  26587. }
  26588. }
  26589. else {
  26590. combineArray.push(newAction);
  26591. }
  26592. for (var i = 0; i < parsedAction.children.length; i++)
  26593. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26594. };
  26595. // triggers
  26596. for (var i = 0; i < parsedActions.children.length; i++) {
  26597. var triggerParams;
  26598. var trigger = parsedActions.children[i];
  26599. if (trigger.properties.length > 0) {
  26600. var param = trigger.properties[0].value;
  26601. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26602. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26603. }
  26604. else
  26605. triggerParams = BABYLON.ActionManager[trigger.name];
  26606. for (var j = 0; j < trigger.children.length; j++) {
  26607. if (!trigger.detached)
  26608. traverse(trigger.children[j], triggerParams, null, null);
  26609. }
  26610. }
  26611. };
  26612. // Statics
  26613. ActionManager._NothingTrigger = 0;
  26614. ActionManager._OnPickTrigger = 1;
  26615. ActionManager._OnLeftPickTrigger = 2;
  26616. ActionManager._OnRightPickTrigger = 3;
  26617. ActionManager._OnCenterPickTrigger = 4;
  26618. ActionManager._OnPickDownTrigger = 5;
  26619. ActionManager._OnPickUpTrigger = 6;
  26620. ActionManager._OnLongPressTrigger = 7;
  26621. ActionManager._OnPointerOverTrigger = 8;
  26622. ActionManager._OnPointerOutTrigger = 9;
  26623. ActionManager._OnEveryFrameTrigger = 10;
  26624. ActionManager._OnIntersectionEnterTrigger = 11;
  26625. ActionManager._OnIntersectionExitTrigger = 12;
  26626. ActionManager._OnKeyDownTrigger = 13;
  26627. ActionManager._OnKeyUpTrigger = 14;
  26628. ActionManager._OnPickOutTrigger = 15;
  26629. ActionManager.DragMovementThreshold = 10; // in pixels
  26630. ActionManager.LongPressDelay = 500; // in milliseconds
  26631. return ActionManager;
  26632. })();
  26633. BABYLON.ActionManager = ActionManager;
  26634. })(BABYLON || (BABYLON = {}));
  26635. var BABYLON;
  26636. (function (BABYLON) {
  26637. var InterpolateValueAction = (function (_super) {
  26638. __extends(InterpolateValueAction, _super);
  26639. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26640. if (duration === void 0) { duration = 1000; }
  26641. _super.call(this, triggerOptions, condition);
  26642. this.propertyPath = propertyPath;
  26643. this.value = value;
  26644. this.duration = duration;
  26645. this.stopOtherAnimations = stopOtherAnimations;
  26646. this.onInterpolationDone = onInterpolationDone;
  26647. this._target = target;
  26648. }
  26649. InterpolateValueAction.prototype._prepare = function () {
  26650. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26651. this._property = this._getProperty(this.propertyPath);
  26652. };
  26653. InterpolateValueAction.prototype.execute = function () {
  26654. var scene = this._actionManager.getScene();
  26655. var keys = [
  26656. {
  26657. frame: 0,
  26658. value: this._target[this._property]
  26659. }, {
  26660. frame: 100,
  26661. value: this.value
  26662. }
  26663. ];
  26664. var dataType;
  26665. if (typeof this.value === "number") {
  26666. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26667. }
  26668. else if (this.value instanceof BABYLON.Color3) {
  26669. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26670. }
  26671. else if (this.value instanceof BABYLON.Vector3) {
  26672. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26673. }
  26674. else if (this.value instanceof BABYLON.Matrix) {
  26675. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26676. }
  26677. else if (this.value instanceof BABYLON.Quaternion) {
  26678. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26679. }
  26680. else {
  26681. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26682. return;
  26683. }
  26684. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26685. animation.setKeys(keys);
  26686. if (this.stopOtherAnimations) {
  26687. scene.stopAnimation(this._target);
  26688. }
  26689. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26690. };
  26691. return InterpolateValueAction;
  26692. })(BABYLON.Action);
  26693. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26694. })(BABYLON || (BABYLON = {}));
  26695. var BABYLON;
  26696. (function (BABYLON) {
  26697. var SwitchBooleanAction = (function (_super) {
  26698. __extends(SwitchBooleanAction, _super);
  26699. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26700. _super.call(this, triggerOptions, condition);
  26701. this.propertyPath = propertyPath;
  26702. this._target = target;
  26703. }
  26704. SwitchBooleanAction.prototype._prepare = function () {
  26705. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26706. this._property = this._getProperty(this.propertyPath);
  26707. };
  26708. SwitchBooleanAction.prototype.execute = function () {
  26709. this._target[this._property] = !this._target[this._property];
  26710. };
  26711. return SwitchBooleanAction;
  26712. })(BABYLON.Action);
  26713. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26714. var SetStateAction = (function (_super) {
  26715. __extends(SetStateAction, _super);
  26716. function SetStateAction(triggerOptions, target, value, condition) {
  26717. _super.call(this, triggerOptions, condition);
  26718. this.value = value;
  26719. this._target = target;
  26720. }
  26721. SetStateAction.prototype.execute = function () {
  26722. this._target.state = this.value;
  26723. };
  26724. return SetStateAction;
  26725. })(BABYLON.Action);
  26726. BABYLON.SetStateAction = SetStateAction;
  26727. var SetValueAction = (function (_super) {
  26728. __extends(SetValueAction, _super);
  26729. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26730. _super.call(this, triggerOptions, condition);
  26731. this.propertyPath = propertyPath;
  26732. this.value = value;
  26733. this._target = target;
  26734. }
  26735. SetValueAction.prototype._prepare = function () {
  26736. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26737. this._property = this._getProperty(this.propertyPath);
  26738. };
  26739. SetValueAction.prototype.execute = function () {
  26740. this._target[this._property] = this.value;
  26741. };
  26742. return SetValueAction;
  26743. })(BABYLON.Action);
  26744. BABYLON.SetValueAction = SetValueAction;
  26745. var IncrementValueAction = (function (_super) {
  26746. __extends(IncrementValueAction, _super);
  26747. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26748. _super.call(this, triggerOptions, condition);
  26749. this.propertyPath = propertyPath;
  26750. this.value = value;
  26751. this._target = target;
  26752. }
  26753. IncrementValueAction.prototype._prepare = function () {
  26754. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26755. this._property = this._getProperty(this.propertyPath);
  26756. if (typeof this._target[this._property] !== "number") {
  26757. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26758. }
  26759. };
  26760. IncrementValueAction.prototype.execute = function () {
  26761. this._target[this._property] += this.value;
  26762. };
  26763. return IncrementValueAction;
  26764. })(BABYLON.Action);
  26765. BABYLON.IncrementValueAction = IncrementValueAction;
  26766. var PlayAnimationAction = (function (_super) {
  26767. __extends(PlayAnimationAction, _super);
  26768. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26769. _super.call(this, triggerOptions, condition);
  26770. this.from = from;
  26771. this.to = to;
  26772. this.loop = loop;
  26773. this._target = target;
  26774. }
  26775. PlayAnimationAction.prototype._prepare = function () {
  26776. };
  26777. PlayAnimationAction.prototype.execute = function () {
  26778. var scene = this._actionManager.getScene();
  26779. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26780. };
  26781. return PlayAnimationAction;
  26782. })(BABYLON.Action);
  26783. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26784. var StopAnimationAction = (function (_super) {
  26785. __extends(StopAnimationAction, _super);
  26786. function StopAnimationAction(triggerOptions, target, condition) {
  26787. _super.call(this, triggerOptions, condition);
  26788. this._target = target;
  26789. }
  26790. StopAnimationAction.prototype._prepare = function () {
  26791. };
  26792. StopAnimationAction.prototype.execute = function () {
  26793. var scene = this._actionManager.getScene();
  26794. scene.stopAnimation(this._target);
  26795. };
  26796. return StopAnimationAction;
  26797. })(BABYLON.Action);
  26798. BABYLON.StopAnimationAction = StopAnimationAction;
  26799. var DoNothingAction = (function (_super) {
  26800. __extends(DoNothingAction, _super);
  26801. function DoNothingAction(triggerOptions, condition) {
  26802. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26803. _super.call(this, triggerOptions, condition);
  26804. }
  26805. DoNothingAction.prototype.execute = function () {
  26806. };
  26807. return DoNothingAction;
  26808. })(BABYLON.Action);
  26809. BABYLON.DoNothingAction = DoNothingAction;
  26810. var CombineAction = (function (_super) {
  26811. __extends(CombineAction, _super);
  26812. function CombineAction(triggerOptions, children, condition) {
  26813. _super.call(this, triggerOptions, condition);
  26814. this.children = children;
  26815. }
  26816. CombineAction.prototype._prepare = function () {
  26817. for (var index = 0; index < this.children.length; index++) {
  26818. this.children[index]._actionManager = this._actionManager;
  26819. this.children[index]._prepare();
  26820. }
  26821. };
  26822. CombineAction.prototype.execute = function (evt) {
  26823. for (var index = 0; index < this.children.length; index++) {
  26824. this.children[index].execute(evt);
  26825. }
  26826. };
  26827. return CombineAction;
  26828. })(BABYLON.Action);
  26829. BABYLON.CombineAction = CombineAction;
  26830. var ExecuteCodeAction = (function (_super) {
  26831. __extends(ExecuteCodeAction, _super);
  26832. function ExecuteCodeAction(triggerOptions, func, condition) {
  26833. _super.call(this, triggerOptions, condition);
  26834. this.func = func;
  26835. }
  26836. ExecuteCodeAction.prototype.execute = function (evt) {
  26837. this.func(evt);
  26838. };
  26839. return ExecuteCodeAction;
  26840. })(BABYLON.Action);
  26841. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26842. var SetParentAction = (function (_super) {
  26843. __extends(SetParentAction, _super);
  26844. function SetParentAction(triggerOptions, target, parent, condition) {
  26845. _super.call(this, triggerOptions, condition);
  26846. this._target = target;
  26847. this._parent = parent;
  26848. }
  26849. SetParentAction.prototype._prepare = function () {
  26850. };
  26851. SetParentAction.prototype.execute = function () {
  26852. if (this._target.parent === this._parent) {
  26853. return;
  26854. }
  26855. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26856. invertParentWorldMatrix.invert();
  26857. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26858. this._target.parent = this._parent;
  26859. };
  26860. return SetParentAction;
  26861. })(BABYLON.Action);
  26862. BABYLON.SetParentAction = SetParentAction;
  26863. var PlaySoundAction = (function (_super) {
  26864. __extends(PlaySoundAction, _super);
  26865. function PlaySoundAction(triggerOptions, sound, condition) {
  26866. _super.call(this, triggerOptions, condition);
  26867. this._sound = sound;
  26868. }
  26869. PlaySoundAction.prototype._prepare = function () {
  26870. };
  26871. PlaySoundAction.prototype.execute = function () {
  26872. if (this._sound !== undefined)
  26873. this._sound.play();
  26874. };
  26875. return PlaySoundAction;
  26876. })(BABYLON.Action);
  26877. BABYLON.PlaySoundAction = PlaySoundAction;
  26878. var StopSoundAction = (function (_super) {
  26879. __extends(StopSoundAction, _super);
  26880. function StopSoundAction(triggerOptions, sound, condition) {
  26881. _super.call(this, triggerOptions, condition);
  26882. this._sound = sound;
  26883. }
  26884. StopSoundAction.prototype._prepare = function () {
  26885. };
  26886. StopSoundAction.prototype.execute = function () {
  26887. if (this._sound !== undefined)
  26888. this._sound.stop();
  26889. };
  26890. return StopSoundAction;
  26891. })(BABYLON.Action);
  26892. BABYLON.StopSoundAction = StopSoundAction;
  26893. })(BABYLON || (BABYLON = {}));
  26894. var BABYLON;
  26895. (function (BABYLON) {
  26896. var Geometry = (function () {
  26897. function Geometry(id, scene, vertexData, updatable, mesh) {
  26898. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26899. this._totalVertices = 0;
  26900. this._isDisposed = false;
  26901. this.id = id;
  26902. this._engine = scene.getEngine();
  26903. this._meshes = [];
  26904. this._scene = scene;
  26905. //Init vertex buffer cache
  26906. this._vertexBuffers = {};
  26907. this._indices = [];
  26908. // vertexData
  26909. if (vertexData) {
  26910. this.setAllVerticesData(vertexData, updatable);
  26911. }
  26912. else {
  26913. this._totalVertices = 0;
  26914. this._indices = [];
  26915. }
  26916. // applyToMesh
  26917. if (mesh) {
  26918. this.applyToMesh(mesh);
  26919. mesh.computeWorldMatrix(true);
  26920. }
  26921. }
  26922. Object.defineProperty(Geometry.prototype, "extend", {
  26923. get: function () {
  26924. return this._extend;
  26925. },
  26926. enumerable: true,
  26927. configurable: true
  26928. });
  26929. Geometry.prototype.getScene = function () {
  26930. return this._scene;
  26931. };
  26932. Geometry.prototype.getEngine = function () {
  26933. return this._engine;
  26934. };
  26935. Geometry.prototype.isReady = function () {
  26936. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26937. };
  26938. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26939. vertexData.applyToGeometry(this, updatable);
  26940. this.notifyUpdate();
  26941. };
  26942. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26943. if (this._vertexBuffers[kind]) {
  26944. this._vertexBuffers[kind].dispose();
  26945. }
  26946. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26947. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26948. stride = this._vertexBuffers[kind].getStrideSize();
  26949. this._totalVertices = data.length / stride;
  26950. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26951. var meshes = this._meshes;
  26952. var numOfMeshes = meshes.length;
  26953. for (var index = 0; index < numOfMeshes; index++) {
  26954. var mesh = meshes[index];
  26955. mesh._resetPointsArrayCache();
  26956. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26957. mesh._createGlobalSubMesh();
  26958. mesh.computeWorldMatrix(true);
  26959. }
  26960. }
  26961. this.notifyUpdate(kind);
  26962. };
  26963. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26964. var vertexBuffer = this.getVertexBuffer(kind);
  26965. if (!vertexBuffer) {
  26966. return;
  26967. }
  26968. vertexBuffer.updateDirectly(data, offset);
  26969. this.notifyUpdate(kind);
  26970. };
  26971. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26972. var vertexBuffer = this.getVertexBuffer(kind);
  26973. if (!vertexBuffer) {
  26974. return;
  26975. }
  26976. vertexBuffer.update(data);
  26977. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26978. var stride = vertexBuffer.getStrideSize();
  26979. this._totalVertices = data.length / stride;
  26980. if (updateExtends) {
  26981. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26982. }
  26983. var meshes = this._meshes;
  26984. var numOfMeshes = meshes.length;
  26985. for (var index = 0; index < numOfMeshes; index++) {
  26986. var mesh = meshes[index];
  26987. mesh._resetPointsArrayCache();
  26988. if (updateExtends) {
  26989. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26990. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26991. var subMesh = mesh.subMeshes[subIndex];
  26992. subMesh.refreshBoundingInfo();
  26993. }
  26994. }
  26995. }
  26996. }
  26997. this.notifyUpdate(kind);
  26998. };
  26999. Geometry.prototype.getTotalVertices = function () {
  27000. if (!this.isReady()) {
  27001. return 0;
  27002. }
  27003. return this._totalVertices;
  27004. };
  27005. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27006. var vertexBuffer = this.getVertexBuffer(kind);
  27007. if (!vertexBuffer) {
  27008. return null;
  27009. }
  27010. var orig = vertexBuffer.getData();
  27011. if (!copyWhenShared || this._meshes.length === 1) {
  27012. return orig;
  27013. }
  27014. else {
  27015. var len = orig.length;
  27016. var copy = [];
  27017. for (var i = 0; i < len; i++) {
  27018. copy.push(orig[i]);
  27019. }
  27020. return copy;
  27021. }
  27022. };
  27023. Geometry.prototype.getVertexBuffer = function (kind) {
  27024. if (!this.isReady()) {
  27025. return null;
  27026. }
  27027. return this._vertexBuffers[kind];
  27028. };
  27029. Geometry.prototype.getVertexBuffers = function () {
  27030. if (!this.isReady()) {
  27031. return null;
  27032. }
  27033. return this._vertexBuffers;
  27034. };
  27035. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27036. if (!this._vertexBuffers) {
  27037. if (this._delayInfo) {
  27038. return this._delayInfo.indexOf(kind) !== -1;
  27039. }
  27040. return false;
  27041. }
  27042. return this._vertexBuffers[kind] !== undefined;
  27043. };
  27044. Geometry.prototype.getVerticesDataKinds = function () {
  27045. var result = [];
  27046. var kind;
  27047. if (!this._vertexBuffers && this._delayInfo) {
  27048. for (kind in this._delayInfo) {
  27049. result.push(kind);
  27050. }
  27051. }
  27052. else {
  27053. for (kind in this._vertexBuffers) {
  27054. result.push(kind);
  27055. }
  27056. }
  27057. return result;
  27058. };
  27059. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27060. if (this._indexBuffer) {
  27061. this._engine._releaseBuffer(this._indexBuffer);
  27062. }
  27063. this._indices = indices;
  27064. if (this._meshes.length !== 0 && this._indices) {
  27065. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27066. }
  27067. if (totalVertices !== undefined) {
  27068. this._totalVertices = totalVertices;
  27069. }
  27070. var meshes = this._meshes;
  27071. var numOfMeshes = meshes.length;
  27072. for (var index = 0; index < numOfMeshes; index++) {
  27073. meshes[index]._createGlobalSubMesh();
  27074. }
  27075. this.notifyUpdate();
  27076. };
  27077. Geometry.prototype.getTotalIndices = function () {
  27078. if (!this.isReady()) {
  27079. return 0;
  27080. }
  27081. return this._indices.length;
  27082. };
  27083. Geometry.prototype.getIndices = function (copyWhenShared) {
  27084. if (!this.isReady()) {
  27085. return null;
  27086. }
  27087. var orig = this._indices;
  27088. if (!copyWhenShared || this._meshes.length === 1) {
  27089. return orig;
  27090. }
  27091. else {
  27092. var len = orig.length;
  27093. var copy = [];
  27094. for (var i = 0; i < len; i++) {
  27095. copy.push(orig[i]);
  27096. }
  27097. return copy;
  27098. }
  27099. };
  27100. Geometry.prototype.getIndexBuffer = function () {
  27101. if (!this.isReady()) {
  27102. return null;
  27103. }
  27104. return this._indexBuffer;
  27105. };
  27106. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27107. var meshes = this._meshes;
  27108. var index = meshes.indexOf(mesh);
  27109. if (index === -1) {
  27110. return;
  27111. }
  27112. for (var kind in this._vertexBuffers) {
  27113. this._vertexBuffers[kind].dispose();
  27114. }
  27115. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27116. this._indexBuffer = null;
  27117. }
  27118. meshes.splice(index, 1);
  27119. mesh._geometry = null;
  27120. if (meshes.length === 0 && shouldDispose) {
  27121. this.dispose();
  27122. }
  27123. };
  27124. Geometry.prototype.applyToMesh = function (mesh) {
  27125. if (mesh._geometry === this) {
  27126. return;
  27127. }
  27128. var previousGeometry = mesh._geometry;
  27129. if (previousGeometry) {
  27130. previousGeometry.releaseForMesh(mesh);
  27131. }
  27132. var meshes = this._meshes;
  27133. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27134. mesh._geometry = this;
  27135. this._scene.pushGeometry(this);
  27136. meshes.push(mesh);
  27137. if (this.isReady()) {
  27138. this._applyToMesh(mesh);
  27139. }
  27140. else {
  27141. mesh._boundingInfo = this._boundingInfo;
  27142. }
  27143. };
  27144. Geometry.prototype._applyToMesh = function (mesh) {
  27145. var numOfMeshes = this._meshes.length;
  27146. // vertexBuffers
  27147. for (var kind in this._vertexBuffers) {
  27148. if (numOfMeshes === 1) {
  27149. this._vertexBuffers[kind].create();
  27150. }
  27151. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27152. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27153. mesh._resetPointsArrayCache();
  27154. if (!this._extend) {
  27155. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27156. }
  27157. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27158. mesh._createGlobalSubMesh();
  27159. //bounding info was just created again, world matrix should be applied again.
  27160. mesh._updateBoundingInfo();
  27161. }
  27162. }
  27163. // indexBuffer
  27164. if (numOfMeshes === 1 && this._indices) {
  27165. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27166. }
  27167. if (this._indexBuffer) {
  27168. this._indexBuffer.references = numOfMeshes;
  27169. }
  27170. };
  27171. Geometry.prototype.notifyUpdate = function (kind) {
  27172. if (this.onGeometryUpdated) {
  27173. this.onGeometryUpdated(this, kind);
  27174. }
  27175. };
  27176. Geometry.prototype.load = function (scene, onLoaded) {
  27177. var _this = this;
  27178. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27179. return;
  27180. }
  27181. if (this.isReady()) {
  27182. if (onLoaded) {
  27183. onLoaded();
  27184. }
  27185. return;
  27186. }
  27187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27188. scene._addPendingData(this);
  27189. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27190. _this._delayLoadingFunction(JSON.parse(data), _this);
  27191. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27192. _this._delayInfo = [];
  27193. scene._removePendingData(_this);
  27194. var meshes = _this._meshes;
  27195. var numOfMeshes = meshes.length;
  27196. for (var index = 0; index < numOfMeshes; index++) {
  27197. _this._applyToMesh(meshes[index]);
  27198. }
  27199. if (onLoaded) {
  27200. onLoaded();
  27201. }
  27202. }, function () { }, scene.database);
  27203. };
  27204. Geometry.prototype.isDisposed = function () {
  27205. return this._isDisposed;
  27206. };
  27207. Geometry.prototype.dispose = function () {
  27208. var meshes = this._meshes;
  27209. var numOfMeshes = meshes.length;
  27210. var index;
  27211. for (index = 0; index < numOfMeshes; index++) {
  27212. this.releaseForMesh(meshes[index]);
  27213. }
  27214. this._meshes = [];
  27215. for (var kind in this._vertexBuffers) {
  27216. this._vertexBuffers[kind].dispose();
  27217. }
  27218. this._vertexBuffers = [];
  27219. this._totalVertices = 0;
  27220. if (this._indexBuffer) {
  27221. this._engine._releaseBuffer(this._indexBuffer);
  27222. }
  27223. this._indexBuffer = null;
  27224. this._indices = [];
  27225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27226. this.delayLoadingFile = null;
  27227. this._delayLoadingFunction = null;
  27228. this._delayInfo = [];
  27229. this._boundingInfo = null;
  27230. this._scene.removeGeometry(this);
  27231. this._isDisposed = true;
  27232. };
  27233. Geometry.prototype.copy = function (id) {
  27234. var vertexData = new BABYLON.VertexData();
  27235. vertexData.indices = [];
  27236. var indices = this.getIndices();
  27237. for (var index = 0; index < indices.length; index++) {
  27238. vertexData.indices.push(indices[index]);
  27239. }
  27240. var updatable = false;
  27241. var stopChecking = false;
  27242. var kind;
  27243. for (kind in this._vertexBuffers) {
  27244. // using slice() to make a copy of the array and not just reference it
  27245. var data = this.getVerticesData(kind);
  27246. if (data instanceof Float32Array) {
  27247. vertexData.set(new Float32Array(data), kind);
  27248. }
  27249. else {
  27250. vertexData.set(data.slice(0), kind);
  27251. }
  27252. if (!stopChecking) {
  27253. updatable = this.getVertexBuffer(kind).isUpdatable();
  27254. stopChecking = !updatable;
  27255. }
  27256. }
  27257. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27258. geometry.delayLoadState = this.delayLoadState;
  27259. geometry.delayLoadingFile = this.delayLoadingFile;
  27260. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27261. for (kind in this._delayInfo) {
  27262. geometry._delayInfo = geometry._delayInfo || [];
  27263. geometry._delayInfo.push(kind);
  27264. }
  27265. // Bounding info
  27266. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27267. return geometry;
  27268. };
  27269. Geometry.prototype.serialize = function () {
  27270. var serializationObject = {};
  27271. serializationObject.id = this.id;
  27272. if (BABYLON.Tags.HasTags(this)) {
  27273. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27274. }
  27275. return serializationObject;
  27276. };
  27277. Geometry.prototype.serializeVerticeData = function () {
  27278. var serializationObject = this.serialize();
  27279. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27280. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27281. }
  27282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27283. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27284. }
  27285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27286. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27287. }
  27288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27289. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27290. }
  27291. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27292. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27293. }
  27294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27295. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27296. }
  27297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27298. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27299. }
  27300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27301. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27302. }
  27303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27304. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27305. }
  27306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27307. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27308. serializationObject.matricesIndices._isExpanded = true;
  27309. }
  27310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27311. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27312. }
  27313. serializationObject.indices = this.getIndices();
  27314. return serializationObject;
  27315. };
  27316. // Statics
  27317. Geometry.ExtractFromMesh = function (mesh, id) {
  27318. var geometry = mesh._geometry;
  27319. if (!geometry) {
  27320. return null;
  27321. }
  27322. return geometry.copy(id);
  27323. };
  27324. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27325. // be aware Math.random() could cause collisions
  27326. Geometry.RandomId = function () {
  27327. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27328. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27329. return v.toString(16);
  27330. });
  27331. };
  27332. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27333. var scene = mesh.getScene();
  27334. // Geometry
  27335. var geometryId = parsedGeometry.geometryId;
  27336. if (geometryId) {
  27337. var geometry = scene.getGeometryByID(geometryId);
  27338. if (geometry) {
  27339. geometry.applyToMesh(mesh);
  27340. }
  27341. }
  27342. else if (parsedGeometry instanceof ArrayBuffer) {
  27343. var binaryInfo = mesh._binaryInfo;
  27344. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27345. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27346. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27347. }
  27348. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27349. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27350. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27351. }
  27352. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27353. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27354. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27355. }
  27356. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27357. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27358. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27359. }
  27360. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27361. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27362. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27363. }
  27364. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27365. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27366. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27367. }
  27368. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27369. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27370. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27371. }
  27372. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27373. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27374. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27375. }
  27376. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27377. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27378. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27379. }
  27380. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27381. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27382. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27383. }
  27384. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27385. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27386. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27387. }
  27388. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27389. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27390. mesh.setIndices(indicesData);
  27391. }
  27392. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27393. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27394. mesh.subMeshes = [];
  27395. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27396. var materialIndex = subMeshesData[(i * 5) + 0];
  27397. var verticesStart = subMeshesData[(i * 5) + 1];
  27398. var verticesCount = subMeshesData[(i * 5) + 2];
  27399. var indexStart = subMeshesData[(i * 5) + 3];
  27400. var indexCount = subMeshesData[(i * 5) + 4];
  27401. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27402. }
  27403. }
  27404. }
  27405. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27406. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27407. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27408. if (parsedGeometry.uvs) {
  27409. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27410. }
  27411. if (parsedGeometry.uvs2) {
  27412. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27413. }
  27414. if (parsedGeometry.uvs3) {
  27415. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27416. }
  27417. if (parsedGeometry.uvs4) {
  27418. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27419. }
  27420. if (parsedGeometry.uvs5) {
  27421. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27422. }
  27423. if (parsedGeometry.uvs6) {
  27424. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27425. }
  27426. if (parsedGeometry.colors) {
  27427. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27428. }
  27429. if (parsedGeometry.matricesIndices) {
  27430. if (!parsedGeometry.matricesIndices._isExpanded) {
  27431. var floatIndices = [];
  27432. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27433. var matricesIndex = parsedGeometry.matricesIndices[i];
  27434. floatIndices.push(matricesIndex & 0x000000FF);
  27435. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27436. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27437. floatIndices.push(matricesIndex >> 24);
  27438. }
  27439. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27440. }
  27441. else {
  27442. delete parsedGeometry.matricesIndices._isExpanded;
  27443. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27444. }
  27445. }
  27446. if (parsedGeometry.matricesIndicesExtra) {
  27447. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27448. var floatIndices = [];
  27449. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27450. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27451. floatIndices.push(matricesIndex & 0x000000FF);
  27452. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27453. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27454. floatIndices.push(matricesIndex >> 24);
  27455. }
  27456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27457. }
  27458. else {
  27459. delete parsedGeometry.matricesIndices._isExpanded;
  27460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27461. }
  27462. }
  27463. if (parsedGeometry.matricesWeights) {
  27464. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27465. }
  27466. if (parsedGeometry.matricesWeightsExtra) {
  27467. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27468. }
  27469. mesh.setIndices(parsedGeometry.indices);
  27470. }
  27471. // SubMeshes
  27472. if (parsedGeometry.subMeshes) {
  27473. mesh.subMeshes = [];
  27474. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27475. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27476. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27477. }
  27478. }
  27479. // Flat shading
  27480. if (mesh._shouldGenerateFlatShading) {
  27481. mesh.convertToFlatShadedMesh();
  27482. delete mesh._shouldGenerateFlatShading;
  27483. }
  27484. // Update
  27485. mesh.computeWorldMatrix(true);
  27486. // Octree
  27487. if (scene['_selectionOctree']) {
  27488. scene['_selectionOctree'].addMesh(mesh);
  27489. }
  27490. };
  27491. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27492. if (scene.getGeometryByID(parsedVertexData.id)) {
  27493. return null; // null since geometry could be something else than a box...
  27494. }
  27495. var geometry = new Geometry(parsedVertexData.id, scene);
  27496. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27497. if (parsedVertexData.delayLoadingFile) {
  27498. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27499. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27500. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27501. geometry._delayInfo = [];
  27502. if (parsedVertexData.hasUVs) {
  27503. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27504. }
  27505. if (parsedVertexData.hasUVs2) {
  27506. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27507. }
  27508. if (parsedVertexData.hasUVs3) {
  27509. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27510. }
  27511. if (parsedVertexData.hasUVs4) {
  27512. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27513. }
  27514. if (parsedVertexData.hasUVs5) {
  27515. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27516. }
  27517. if (parsedVertexData.hasUVs6) {
  27518. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27519. }
  27520. if (parsedVertexData.hasColors) {
  27521. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27522. }
  27523. if (parsedVertexData.hasMatricesIndices) {
  27524. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27525. }
  27526. if (parsedVertexData.hasMatricesWeights) {
  27527. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27528. }
  27529. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27530. }
  27531. else {
  27532. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27533. }
  27534. scene.pushGeometry(geometry, true);
  27535. return geometry;
  27536. };
  27537. return Geometry;
  27538. })();
  27539. BABYLON.Geometry = Geometry;
  27540. /////// Primitives //////////////////////////////////////////////
  27541. var Geometry;
  27542. (function (Geometry) {
  27543. var Primitives;
  27544. (function (Primitives) {
  27545. /// Abstract class
  27546. var _Primitive = (function (_super) {
  27547. __extends(_Primitive, _super);
  27548. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27549. this._beingRegenerated = true;
  27550. this._canBeRegenerated = canBeRegenerated;
  27551. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27552. this._beingRegenerated = false;
  27553. }
  27554. _Primitive.prototype.canBeRegenerated = function () {
  27555. return this._canBeRegenerated;
  27556. };
  27557. _Primitive.prototype.regenerate = function () {
  27558. if (!this._canBeRegenerated) {
  27559. return;
  27560. }
  27561. this._beingRegenerated = true;
  27562. this.setAllVerticesData(this._regenerateVertexData(), false);
  27563. this._beingRegenerated = false;
  27564. };
  27565. _Primitive.prototype.asNewGeometry = function (id) {
  27566. return _super.prototype.copy.call(this, id);
  27567. };
  27568. // overrides
  27569. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27570. if (!this._beingRegenerated) {
  27571. return;
  27572. }
  27573. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27574. };
  27575. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27576. if (!this._beingRegenerated) {
  27577. return;
  27578. }
  27579. _super.prototype.setVerticesData.call(this, kind, data, false);
  27580. };
  27581. // to override
  27582. // protected
  27583. _Primitive.prototype._regenerateVertexData = function () {
  27584. throw new Error("Abstract method");
  27585. };
  27586. _Primitive.prototype.copy = function (id) {
  27587. throw new Error("Must be overriden in sub-classes.");
  27588. };
  27589. _Primitive.prototype.serialize = function () {
  27590. var serializationObject = _super.prototype.serialize.call(this);
  27591. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27592. return serializationObject;
  27593. };
  27594. return _Primitive;
  27595. })(Geometry);
  27596. Primitives._Primitive = _Primitive;
  27597. var Ribbon = (function (_super) {
  27598. __extends(Ribbon, _super);
  27599. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27600. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27601. this.pathArray = pathArray;
  27602. this.closeArray = closeArray;
  27603. this.closePath = closePath;
  27604. this.offset = offset;
  27605. this.side = side;
  27606. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27607. }
  27608. Ribbon.prototype._regenerateVertexData = function () {
  27609. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27610. };
  27611. Ribbon.prototype.copy = function (id) {
  27612. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27613. };
  27614. return Ribbon;
  27615. })(_Primitive);
  27616. Primitives.Ribbon = Ribbon;
  27617. var Box = (function (_super) {
  27618. __extends(Box, _super);
  27619. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27620. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27621. this.size = size;
  27622. this.side = side;
  27623. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27624. }
  27625. Box.prototype._regenerateVertexData = function () {
  27626. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27627. };
  27628. Box.prototype.copy = function (id) {
  27629. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27630. };
  27631. Box.prototype.serialize = function () {
  27632. var serializationObject = _super.prototype.serialize.call(this);
  27633. serializationObject.size = this.size;
  27634. return serializationObject;
  27635. };
  27636. Box.Parse = function (parsedBox, scene) {
  27637. if (scene.getGeometryByID(parsedBox.id)) {
  27638. return null; // null since geometry could be something else than a box...
  27639. }
  27640. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27641. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27642. scene.pushGeometry(box, true);
  27643. return box;
  27644. };
  27645. return Box;
  27646. })(_Primitive);
  27647. Primitives.Box = Box;
  27648. var Sphere = (function (_super) {
  27649. __extends(Sphere, _super);
  27650. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27651. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27652. this.segments = segments;
  27653. this.diameter = diameter;
  27654. this.side = side;
  27655. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27656. }
  27657. Sphere.prototype._regenerateVertexData = function () {
  27658. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27659. };
  27660. Sphere.prototype.copy = function (id) {
  27661. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27662. };
  27663. Sphere.prototype.serialize = function () {
  27664. var serializationObject = _super.prototype.serialize.call(this);
  27665. serializationObject.segments = this.segments;
  27666. serializationObject.diameter = this.diameter;
  27667. return serializationObject;
  27668. };
  27669. Sphere.Parse = function (parsedSphere, scene) {
  27670. if (scene.getGeometryByID(parsedSphere.id)) {
  27671. return null; // null since geometry could be something else than a sphere...
  27672. }
  27673. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27674. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27675. scene.pushGeometry(sphere, true);
  27676. return sphere;
  27677. };
  27678. return Sphere;
  27679. })(_Primitive);
  27680. Primitives.Sphere = Sphere;
  27681. var Disc = (function (_super) {
  27682. __extends(Disc, _super);
  27683. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27684. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27685. this.radius = radius;
  27686. this.tessellation = tessellation;
  27687. this.side = side;
  27688. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27689. }
  27690. Disc.prototype._regenerateVertexData = function () {
  27691. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27692. };
  27693. Disc.prototype.copy = function (id) {
  27694. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27695. };
  27696. return Disc;
  27697. })(_Primitive);
  27698. Primitives.Disc = Disc;
  27699. var Cylinder = (function (_super) {
  27700. __extends(Cylinder, _super);
  27701. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27702. if (subdivisions === void 0) { subdivisions = 1; }
  27703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27704. this.height = height;
  27705. this.diameterTop = diameterTop;
  27706. this.diameterBottom = diameterBottom;
  27707. this.tessellation = tessellation;
  27708. this.subdivisions = subdivisions;
  27709. this.side = side;
  27710. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27711. }
  27712. Cylinder.prototype._regenerateVertexData = function () {
  27713. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27714. };
  27715. Cylinder.prototype.copy = function (id) {
  27716. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27717. };
  27718. Cylinder.prototype.serialize = function () {
  27719. var serializationObject = _super.prototype.serialize.call(this);
  27720. serializationObject.height = this.height;
  27721. serializationObject.diameterTop = this.diameterTop;
  27722. serializationObject.diameterBottom = this.diameterBottom;
  27723. serializationObject.tessellation = this.tessellation;
  27724. return serializationObject;
  27725. };
  27726. Cylinder.Parse = function (parsedCylinder, scene) {
  27727. if (scene.getGeometryByID(parsedCylinder.id)) {
  27728. return null; // null since geometry could be something else than a cylinder...
  27729. }
  27730. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27731. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27732. scene.pushGeometry(cylinder, true);
  27733. return cylinder;
  27734. };
  27735. return Cylinder;
  27736. })(_Primitive);
  27737. Primitives.Cylinder = Cylinder;
  27738. var Torus = (function (_super) {
  27739. __extends(Torus, _super);
  27740. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27741. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27742. this.diameter = diameter;
  27743. this.thickness = thickness;
  27744. this.tessellation = tessellation;
  27745. this.side = side;
  27746. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27747. }
  27748. Torus.prototype._regenerateVertexData = function () {
  27749. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27750. };
  27751. Torus.prototype.copy = function (id) {
  27752. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27753. };
  27754. Torus.prototype.serialize = function () {
  27755. var serializationObject = _super.prototype.serialize.call(this);
  27756. serializationObject.diameter = this.diameter;
  27757. serializationObject.thickness = this.thickness;
  27758. serializationObject.tessellation = this.tessellation;
  27759. return serializationObject;
  27760. };
  27761. Torus.Parse = function (parsedTorus, scene) {
  27762. if (scene.getGeometryByID(parsedTorus.id)) {
  27763. return null; // null since geometry could be something else than a torus...
  27764. }
  27765. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27766. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27767. scene.pushGeometry(torus, true);
  27768. return torus;
  27769. };
  27770. return Torus;
  27771. })(_Primitive);
  27772. Primitives.Torus = Torus;
  27773. var Ground = (function (_super) {
  27774. __extends(Ground, _super);
  27775. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27776. this.width = width;
  27777. this.height = height;
  27778. this.subdivisions = subdivisions;
  27779. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27780. }
  27781. Ground.prototype._regenerateVertexData = function () {
  27782. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27783. };
  27784. Ground.prototype.copy = function (id) {
  27785. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27786. };
  27787. Ground.prototype.serialize = function () {
  27788. var serializationObject = _super.prototype.serialize.call(this);
  27789. serializationObject.width = this.width;
  27790. serializationObject.height = this.height;
  27791. serializationObject.subdivisions = this.subdivisions;
  27792. return serializationObject;
  27793. };
  27794. Ground.Parse = function (parsedGround, scene) {
  27795. if (scene.getGeometryByID(parsedGround.id)) {
  27796. return null; // null since geometry could be something else than a ground...
  27797. }
  27798. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27799. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27800. scene.pushGeometry(ground, true);
  27801. return ground;
  27802. };
  27803. return Ground;
  27804. })(_Primitive);
  27805. Primitives.Ground = Ground;
  27806. var TiledGround = (function (_super) {
  27807. __extends(TiledGround, _super);
  27808. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27809. this.xmin = xmin;
  27810. this.zmin = zmin;
  27811. this.xmax = xmax;
  27812. this.zmax = zmax;
  27813. this.subdivisions = subdivisions;
  27814. this.precision = precision;
  27815. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27816. }
  27817. TiledGround.prototype._regenerateVertexData = function () {
  27818. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27819. };
  27820. TiledGround.prototype.copy = function (id) {
  27821. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27822. };
  27823. return TiledGround;
  27824. })(_Primitive);
  27825. Primitives.TiledGround = TiledGround;
  27826. var Plane = (function (_super) {
  27827. __extends(Plane, _super);
  27828. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27829. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27830. this.size = size;
  27831. this.side = side;
  27832. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27833. }
  27834. Plane.prototype._regenerateVertexData = function () {
  27835. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27836. };
  27837. Plane.prototype.copy = function (id) {
  27838. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27839. };
  27840. Plane.prototype.serialize = function () {
  27841. var serializationObject = _super.prototype.serialize.call(this);
  27842. serializationObject.size = this.size;
  27843. return serializationObject;
  27844. };
  27845. Plane.Parse = function (parsedPlane, scene) {
  27846. if (scene.getGeometryByID(parsedPlane.id)) {
  27847. return null; // null since geometry could be something else than a ground...
  27848. }
  27849. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27850. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27851. scene.pushGeometry(plane, true);
  27852. return plane;
  27853. };
  27854. return Plane;
  27855. })(_Primitive);
  27856. Primitives.Plane = Plane;
  27857. var TorusKnot = (function (_super) {
  27858. __extends(TorusKnot, _super);
  27859. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27860. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27861. this.radius = radius;
  27862. this.tube = tube;
  27863. this.radialSegments = radialSegments;
  27864. this.tubularSegments = tubularSegments;
  27865. this.p = p;
  27866. this.q = q;
  27867. this.side = side;
  27868. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27869. }
  27870. TorusKnot.prototype._regenerateVertexData = function () {
  27871. 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 });
  27872. };
  27873. TorusKnot.prototype.copy = function (id) {
  27874. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27875. };
  27876. TorusKnot.prototype.serialize = function () {
  27877. var serializationObject = _super.prototype.serialize.call(this);
  27878. serializationObject.radius = this.radius;
  27879. serializationObject.tube = this.tube;
  27880. serializationObject.radialSegments = this.radialSegments;
  27881. serializationObject.tubularSegments = this.tubularSegments;
  27882. serializationObject.p = this.p;
  27883. serializationObject.q = this.q;
  27884. return serializationObject;
  27885. };
  27886. ;
  27887. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27888. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27889. return null; // null since geometry could be something else than a ground...
  27890. }
  27891. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27892. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27893. scene.pushGeometry(torusKnot, true);
  27894. return torusKnot;
  27895. };
  27896. return TorusKnot;
  27897. })(_Primitive);
  27898. Primitives.TorusKnot = TorusKnot;
  27899. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27900. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27901. })(BABYLON || (BABYLON = {}));
  27902. var BABYLON;
  27903. (function (BABYLON) {
  27904. var GroundMesh = (function (_super) {
  27905. __extends(GroundMesh, _super);
  27906. function GroundMesh(name, scene) {
  27907. _super.call(this, name, scene);
  27908. this.generateOctree = false;
  27909. this._worldInverse = new BABYLON.Matrix();
  27910. }
  27911. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27912. get: function () {
  27913. return this._subdivisions;
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27919. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27920. this._subdivisions = chunksCount;
  27921. this.subdivide(this._subdivisions);
  27922. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27923. };
  27924. /**
  27925. * Returns a height (y) value in the Worl system :
  27926. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27927. * Returns the ground y position if (x, z) are outside the ground surface.
  27928. * Not pertinent if the ground is rotated.
  27929. */
  27930. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27931. // express x and y in the ground local system
  27932. x -= this.position.x;
  27933. z -= this.position.z;
  27934. x /= this.scaling.x;
  27935. z /= this.scaling.z;
  27936. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27937. return this.position.y;
  27938. }
  27939. if (!this._heightQuads || this._heightQuads.length == 0) {
  27940. this._computeHeightQuads();
  27941. }
  27942. var facet = this._getFacetAt(x, z);
  27943. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27944. // return y in the World system
  27945. return y * this.scaling.y + this.position.y;
  27946. };
  27947. /**
  27948. * Returns a normalized vector (Vector3) orthogonal to the ground
  27949. * at the ground coordinates (x, z) expressed in the World system.
  27950. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27951. * Not pertinent if the ground is rotated.
  27952. */
  27953. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27954. var normal = new BABYLON.Vector3(0, 1, 0);
  27955. this.getNormalAtCoordinatesToRef(x, z, normal);
  27956. return normal;
  27957. };
  27958. /**
  27959. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27960. * at the ground coordinates (x, z) expressed in the World system.
  27961. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27962. * Not pertinent if the ground is rotated.
  27963. */
  27964. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27965. // express x and y in the ground local system
  27966. x -= this.position.x;
  27967. z -= this.position.z;
  27968. x /= this.scaling.x;
  27969. z /= this.scaling.z;
  27970. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27971. return;
  27972. }
  27973. if (!this._heightQuads || this._heightQuads.length == 0) {
  27974. this._computeHeightQuads();
  27975. }
  27976. var facet = this._getFacetAt(x, z);
  27977. ref.x = facet.x;
  27978. ref.y = facet.y;
  27979. ref.z = facet.z;
  27980. };
  27981. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27982. GroundMesh.prototype._getFacetAt = function (x, z) {
  27983. // retrieve col and row from x, z coordinates in the ground local system
  27984. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27985. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27986. var quad = this._heightQuads[row * this._subdivisions + col];
  27987. var facet;
  27988. if (z < quad.slope.x * x + quad.slope.y) {
  27989. facet = quad.facet1;
  27990. }
  27991. else {
  27992. facet = quad.facet2;
  27993. }
  27994. return facet;
  27995. };
  27996. // Populates the heightMap array with "facet" elements :
  27997. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27998. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27999. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28000. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28001. GroundMesh.prototype._computeHeightQuads = function () {
  28002. this._heightQuads = new Array();
  28003. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28004. var v1 = BABYLON.Vector3.Zero();
  28005. var v2 = BABYLON.Vector3.Zero();
  28006. var v3 = BABYLON.Vector3.Zero();
  28007. var v4 = BABYLON.Vector3.Zero();
  28008. var v1v2 = BABYLON.Vector3.Zero();
  28009. var v1v3 = BABYLON.Vector3.Zero();
  28010. var v1v4 = BABYLON.Vector3.Zero();
  28011. var norm1 = BABYLON.Vector3.Zero();
  28012. var norm2 = BABYLON.Vector3.Zero();
  28013. var i = 0;
  28014. var j = 0;
  28015. var k = 0;
  28016. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28017. var h = 0;
  28018. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28019. var d2 = 0;
  28020. for (var row = 0; row < this._subdivisions; row++) {
  28021. for (var col = 0; col < this._subdivisions; col++) {
  28022. i = col * 3;
  28023. j = row * (this._subdivisions + 1) * 3;
  28024. k = (row + 1) * (this._subdivisions + 1) * 3;
  28025. v1.x = positions[j + i];
  28026. v1.y = positions[j + i + 1];
  28027. v1.z = positions[j + i + 2];
  28028. v2.x = positions[j + i + 3];
  28029. v2.y = positions[j + i + 4];
  28030. v2.z = positions[j + i + 5];
  28031. v3.x = positions[k + i];
  28032. v3.y = positions[k + i + 1];
  28033. v3.z = positions[k + i + 2];
  28034. v4.x = positions[k + i + 3];
  28035. v4.y = positions[k + i + 4];
  28036. v4.z = positions[k + i + 5];
  28037. // 2D slope V1V4
  28038. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28039. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28040. var slope = new BABYLON.Vector2(cd, h);
  28041. // facet equations :
  28042. // we compute each facet normal vector
  28043. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28044. // we compute the value d by applying the equation to v1 which belongs to the plane
  28045. // then we store the facet equation in a Vector4
  28046. v2.subtractToRef(v1, v1v2);
  28047. v3.subtractToRef(v1, v1v3);
  28048. v4.subtractToRef(v1, v1v4);
  28049. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28050. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28051. norm1.normalize();
  28052. norm2.normalize();
  28053. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28054. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28055. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  28056. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  28057. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  28058. this._heightQuads.push(quad);
  28059. }
  28060. }
  28061. };
  28062. return GroundMesh;
  28063. })(BABYLON.Mesh);
  28064. BABYLON.GroundMesh = GroundMesh;
  28065. })(BABYLON || (BABYLON = {}));
  28066. var BABYLON;
  28067. (function (BABYLON) {
  28068. var LinesMesh = (function (_super) {
  28069. __extends(LinesMesh, _super);
  28070. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28071. if (parent === void 0) { parent = null; }
  28072. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28073. this.color = new BABYLON.Color3(1, 1, 1);
  28074. this.alpha = 1;
  28075. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28076. attributes: ["position"],
  28077. uniforms: ["worldViewProjection", "color"],
  28078. needAlphaBlending: true
  28079. });
  28080. }
  28081. Object.defineProperty(LinesMesh.prototype, "material", {
  28082. get: function () {
  28083. return this._colorShader;
  28084. },
  28085. enumerable: true,
  28086. configurable: true
  28087. });
  28088. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28089. get: function () {
  28090. return false;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28096. get: function () {
  28097. return false;
  28098. },
  28099. enumerable: true,
  28100. configurable: true
  28101. });
  28102. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28103. var engine = this.getScene().getEngine();
  28104. var indexToBind = this._geometry.getIndexBuffer();
  28105. // VBOs
  28106. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28107. // Color
  28108. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28109. };
  28110. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28111. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28112. return;
  28113. }
  28114. var engine = this.getScene().getEngine();
  28115. // Draw order
  28116. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28117. };
  28118. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28119. return null;
  28120. };
  28121. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28122. this._colorShader.dispose();
  28123. _super.prototype.dispose.call(this, doNotRecurse);
  28124. };
  28125. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28126. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28127. };
  28128. return LinesMesh;
  28129. })(BABYLON.Mesh);
  28130. BABYLON.LinesMesh = LinesMesh;
  28131. })(BABYLON || (BABYLON = {}));
  28132. var BABYLON;
  28133. (function (BABYLON) {
  28134. var DebugLayer = (function () {
  28135. function DebugLayer(scene) {
  28136. var _this = this;
  28137. this._transformationMatrix = BABYLON.Matrix.Identity();
  28138. this._enabled = false;
  28139. this._labelsEnabled = false;
  28140. this._displayStatistics = true;
  28141. this._displayTree = false;
  28142. this._displayLogs = false;
  28143. this._identityMatrix = BABYLON.Matrix.Identity();
  28144. this.axisRatio = 0.02;
  28145. this.accentColor = "orange";
  28146. this._scene = scene;
  28147. this._syncPositions = function () {
  28148. var engine = _this._scene.getEngine();
  28149. var canvasRect = engine.getRenderingCanvasClientRect();
  28150. if (_this._showUI) {
  28151. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28152. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28153. _this._statsDiv.style.width = "400px";
  28154. _this._statsDiv.style.height = "auto";
  28155. _this._statsSubsetDiv.style.maxHeight = "240px";
  28156. _this._optionsDiv.style.left = "0px";
  28157. _this._optionsDiv.style.top = "10px";
  28158. _this._optionsDiv.style.width = "200px";
  28159. _this._optionsDiv.style.height = "auto";
  28160. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28161. _this._logDiv.style.left = "0px";
  28162. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28163. _this._logDiv.style.width = "600px";
  28164. _this._logDiv.style.height = "160px";
  28165. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28166. _this._treeDiv.style.top = "10px";
  28167. _this._treeDiv.style.width = "300px";
  28168. _this._treeDiv.style.height = "auto";
  28169. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28170. }
  28171. _this._globalDiv.style.left = canvasRect.left + "px";
  28172. _this._globalDiv.style.top = canvasRect.top + "px";
  28173. _this._drawingCanvas.style.left = "0px";
  28174. _this._drawingCanvas.style.top = "0px";
  28175. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28176. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28177. var devicePixelRatio = window.devicePixelRatio || 1;
  28178. var context = _this._drawingContext;
  28179. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28180. context.mozBackingStorePixelRatio ||
  28181. context.msBackingStorePixelRatio ||
  28182. context.oBackingStorePixelRatio ||
  28183. context.backingStorePixelRatio || 1;
  28184. _this._ratio = devicePixelRatio / backingStoreRatio;
  28185. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28186. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28187. };
  28188. this._onCanvasClick = function (evt) {
  28189. _this._clickPosition = {
  28190. x: evt.clientX * _this._ratio,
  28191. y: evt.clientY * _this._ratio
  28192. };
  28193. };
  28194. this._syncUI = function () {
  28195. if (_this._showUI) {
  28196. if (_this._displayStatistics) {
  28197. _this._displayStats();
  28198. _this._statsDiv.style.display = "";
  28199. }
  28200. else {
  28201. _this._statsDiv.style.display = "none";
  28202. }
  28203. if (_this._displayLogs) {
  28204. _this._logDiv.style.display = "";
  28205. }
  28206. else {
  28207. _this._logDiv.style.display = "none";
  28208. }
  28209. if (_this._displayTree) {
  28210. _this._treeDiv.style.display = "";
  28211. if (_this._needToRefreshMeshesTree) {
  28212. _this._needToRefreshMeshesTree = false;
  28213. _this._refreshMeshesTreeContent();
  28214. }
  28215. }
  28216. else {
  28217. _this._treeDiv.style.display = "none";
  28218. }
  28219. }
  28220. };
  28221. this._syncData = function () {
  28222. if (_this._labelsEnabled || !_this._showUI) {
  28223. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28224. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28225. var engine = _this._scene.getEngine();
  28226. var viewport = _this._camera.viewport;
  28227. var globalViewport = viewport.toGlobal(engine);
  28228. // Meshes
  28229. var meshes = _this._camera.getActiveMeshes();
  28230. var index;
  28231. var projectedPosition;
  28232. for (index = 0; index < meshes.length; index++) {
  28233. var mesh = meshes.data[index];
  28234. var position = mesh.getBoundingInfo().boundingSphere.center;
  28235. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28236. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28237. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28238. }
  28239. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28240. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28241. }
  28242. }
  28243. // Cameras
  28244. var cameras = _this._scene.cameras;
  28245. for (index = 0; index < cameras.length; index++) {
  28246. var camera = cameras[index];
  28247. if (camera === _this._camera) {
  28248. continue;
  28249. }
  28250. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28251. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28252. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28253. _this._camera.detachControl(engine.getRenderingCanvas());
  28254. _this._camera = camera;
  28255. _this._camera.attachControl(engine.getRenderingCanvas());
  28256. }, function () { return "purple"; });
  28257. }
  28258. }
  28259. // Lights
  28260. var lights = _this._scene.lights;
  28261. for (index = 0; index < lights.length; index++) {
  28262. var light = lights[index];
  28263. if (light.position) {
  28264. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28265. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28266. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28267. light.setEnabled(!light.isEnabled());
  28268. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28269. }
  28270. }
  28271. }
  28272. }
  28273. _this._clickPosition = undefined;
  28274. };
  28275. }
  28276. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28277. while (this._treeSubsetDiv.hasChildNodes()) {
  28278. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28279. }
  28280. // Add meshes
  28281. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28282. sortedArray.sort(function (a, b) {
  28283. if (a.name === b.name) {
  28284. return 0;
  28285. }
  28286. return (a.name > b.name) ? 1 : -1;
  28287. });
  28288. for (var index = 0; index < sortedArray.length; index++) {
  28289. var mesh = sortedArray[index];
  28290. if (!mesh.isEnabled()) {
  28291. continue;
  28292. }
  28293. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28294. m.isVisible = element.checked;
  28295. }, mesh);
  28296. }
  28297. };
  28298. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28299. this._drawingContext.beginPath();
  28300. this._drawingContext.moveTo(zero.x, zero.y);
  28301. this._drawingContext.lineTo(unit.x, unit.y);
  28302. this._drawingContext.strokeStyle = color;
  28303. this._drawingContext.lineWidth = 4;
  28304. this._drawingContext.stroke();
  28305. this._drawingContext.font = "normal 14px Segoe UI";
  28306. this._drawingContext.fillStyle = color;
  28307. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28308. };
  28309. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28310. var position = mesh.getBoundingInfo().boundingSphere.center;
  28311. var worldMatrix = mesh.getWorldMatrix();
  28312. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28313. var unit = (unprojectedVector.subtract(position)).length();
  28314. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28315. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28316. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28317. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28318. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28319. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28320. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28321. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28322. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28323. };
  28324. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28325. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28326. this._drawingContext.font = "normal 12px Segoe UI";
  28327. var textMetrics = this._drawingContext.measureText(text);
  28328. var centerX = projectedPosition.x - textMetrics.width / 2;
  28329. var centerY = projectedPosition.y;
  28330. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28331. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28332. onClick();
  28333. }
  28334. this._drawingContext.beginPath();
  28335. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28336. this._drawingContext.fillStyle = getFillStyle();
  28337. this._drawingContext.globalAlpha = 0.5;
  28338. this._drawingContext.fill();
  28339. this._drawingContext.globalAlpha = 1.0;
  28340. this._drawingContext.strokeStyle = '#FFFFFF';
  28341. this._drawingContext.lineWidth = 1;
  28342. this._drawingContext.stroke();
  28343. this._drawingContext.fillStyle = "#FFFFFF";
  28344. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28345. this._drawingContext.beginPath();
  28346. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28347. this._drawingContext.fill();
  28348. }
  28349. };
  28350. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28351. if (!this._clickPosition) {
  28352. return false;
  28353. }
  28354. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28355. return false;
  28356. }
  28357. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28358. return false;
  28359. }
  28360. return true;
  28361. };
  28362. DebugLayer.prototype.isVisible = function () {
  28363. return this._enabled;
  28364. };
  28365. DebugLayer.prototype.hide = function () {
  28366. if (!this._enabled) {
  28367. return;
  28368. }
  28369. this._enabled = false;
  28370. var engine = this._scene.getEngine();
  28371. this._scene.unregisterBeforeRender(this._syncData);
  28372. this._scene.unregisterAfterRender(this._syncUI);
  28373. this._rootElement.removeChild(this._globalDiv);
  28374. this._scene.forceShowBoundingBoxes = false;
  28375. this._scene.forceWireframe = false;
  28376. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28377. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28378. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28379. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28380. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28381. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28382. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28383. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28384. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28385. this._scene.shadowsEnabled = true;
  28386. this._scene.particlesEnabled = true;
  28387. this._scene.postProcessesEnabled = true;
  28388. this._scene.collisionsEnabled = true;
  28389. this._scene.lightsEnabled = true;
  28390. this._scene.texturesEnabled = true;
  28391. this._scene.lensFlaresEnabled = true;
  28392. this._scene.proceduralTexturesEnabled = true;
  28393. this._scene.renderTargetsEnabled = true;
  28394. this._scene.probesEnabled = true;
  28395. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28396. };
  28397. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28398. if (showUI === void 0) { showUI = true; }
  28399. if (camera === void 0) { camera = null; }
  28400. if (rootElement === void 0) { rootElement = null; }
  28401. if (this._enabled) {
  28402. return;
  28403. }
  28404. this._enabled = true;
  28405. if (camera) {
  28406. this._camera = camera;
  28407. }
  28408. else {
  28409. this._camera = this._scene.activeCamera;
  28410. }
  28411. this._showUI = showUI;
  28412. var engine = this._scene.getEngine();
  28413. this._globalDiv = document.createElement("div");
  28414. this._rootElement = rootElement || document.body;
  28415. this._rootElement.appendChild(this._globalDiv);
  28416. this._generateDOMelements();
  28417. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28418. this._syncPositions();
  28419. this._scene.registerBeforeRender(this._syncData);
  28420. this._scene.registerAfterRender(this._syncUI);
  28421. };
  28422. DebugLayer.prototype._clearLabels = function () {
  28423. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28424. for (var index = 0; index < this._scene.meshes.length; index++) {
  28425. var mesh = this._scene.meshes[index];
  28426. mesh.renderOverlay = false;
  28427. }
  28428. };
  28429. DebugLayer.prototype._generateheader = function (root, text) {
  28430. var header = document.createElement("div");
  28431. header.innerHTML = text + "&nbsp;";
  28432. header.style.textAlign = "right";
  28433. header.style.width = "100%";
  28434. header.style.color = "white";
  28435. header.style.backgroundColor = "Black";
  28436. header.style.padding = "5px 5px 4px 0px";
  28437. header.style.marginLeft = "-5px";
  28438. header.style.fontWeight = "bold";
  28439. root.appendChild(header);
  28440. };
  28441. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28442. var label = document.createElement("label");
  28443. label.innerHTML = title;
  28444. label.style.color = color;
  28445. root.appendChild(label);
  28446. root.appendChild(document.createElement("br"));
  28447. };
  28448. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28449. if (tag === void 0) { tag = null; }
  28450. var label = document.createElement("label");
  28451. var boundingBoxesCheckbox = document.createElement("input");
  28452. boundingBoxesCheckbox.type = "checkbox";
  28453. boundingBoxesCheckbox.checked = initialState;
  28454. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28455. task(evt.target, tag);
  28456. });
  28457. label.appendChild(boundingBoxesCheckbox);
  28458. var container = document.createElement("span");
  28459. var leftPart = document.createElement("span");
  28460. var rightPart = document.createElement("span");
  28461. rightPart.style.cssFloat = "right";
  28462. leftPart.innerHTML = leftTitle;
  28463. rightPart.innerHTML = rightTitle;
  28464. rightPart.style.fontSize = "12px";
  28465. rightPart.style.maxWidth = "200px";
  28466. container.appendChild(leftPart);
  28467. container.appendChild(rightPart);
  28468. label.appendChild(container);
  28469. root.appendChild(label);
  28470. root.appendChild(document.createElement("br"));
  28471. };
  28472. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28473. if (tag === void 0) { tag = null; }
  28474. var label = document.createElement("label");
  28475. var checkBox = document.createElement("input");
  28476. checkBox.type = "checkbox";
  28477. checkBox.checked = initialState;
  28478. checkBox.addEventListener("change", function (evt) {
  28479. task(evt.target, tag);
  28480. });
  28481. label.appendChild(checkBox);
  28482. label.appendChild(document.createTextNode(title));
  28483. root.appendChild(label);
  28484. root.appendChild(document.createElement("br"));
  28485. };
  28486. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28487. if (tag === void 0) { tag = null; }
  28488. var button = document.createElement("button");
  28489. button.innerHTML = title;
  28490. button.style.height = "24px";
  28491. button.style.width = "150px";
  28492. button.style.marginBottom = "5px";
  28493. button.style.color = "#444444";
  28494. button.style.border = "1px solid white";
  28495. button.className = "debugLayerButton";
  28496. button.addEventListener("click", function (evt) {
  28497. task(evt.target, tag);
  28498. });
  28499. root.appendChild(button);
  28500. root.appendChild(document.createElement("br"));
  28501. };
  28502. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28503. if (tag === void 0) { tag = null; }
  28504. var label = document.createElement("label");
  28505. var boundingBoxesRadio = document.createElement("input");
  28506. boundingBoxesRadio.type = "radio";
  28507. boundingBoxesRadio.name = name;
  28508. boundingBoxesRadio.checked = initialState;
  28509. boundingBoxesRadio.addEventListener("change", function (evt) {
  28510. task(evt.target, tag);
  28511. });
  28512. label.appendChild(boundingBoxesRadio);
  28513. label.appendChild(document.createTextNode(title));
  28514. root.appendChild(label);
  28515. root.appendChild(document.createElement("br"));
  28516. };
  28517. DebugLayer.prototype._generateDOMelements = function () {
  28518. var _this = this;
  28519. this._globalDiv.id = "DebugLayer";
  28520. this._globalDiv.style.position = "absolute";
  28521. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28522. this._globalDiv.style.fontSize = "14px";
  28523. this._globalDiv.style.color = "white";
  28524. // Drawing canvas
  28525. this._drawingCanvas = document.createElement("canvas");
  28526. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28527. this._drawingCanvas.style.position = "absolute";
  28528. this._drawingCanvas.style.pointerEvents = "none";
  28529. this._drawingCanvas.style.backgroundColor = "transparent";
  28530. this._drawingContext = this._drawingCanvas.getContext("2d");
  28531. this._globalDiv.appendChild(this._drawingCanvas);
  28532. if (this._showUI) {
  28533. var background = "rgba(128, 128, 128, 0.4)";
  28534. var border = "rgb(180, 180, 180) solid 1px";
  28535. // Stats
  28536. this._statsDiv = document.createElement("div");
  28537. this._statsDiv.id = "DebugLayerStats";
  28538. this._statsDiv.style.border = border;
  28539. this._statsDiv.style.position = "absolute";
  28540. this._statsDiv.style.background = background;
  28541. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28542. this._generateheader(this._statsDiv, "STATISTICS");
  28543. this._statsSubsetDiv = document.createElement("div");
  28544. this._statsSubsetDiv.style.paddingTop = "5px";
  28545. this._statsSubsetDiv.style.paddingBottom = "5px";
  28546. this._statsSubsetDiv.style.overflowY = "auto";
  28547. this._statsDiv.appendChild(this._statsSubsetDiv);
  28548. // Tree
  28549. this._treeDiv = document.createElement("div");
  28550. this._treeDiv.id = "DebugLayerTree";
  28551. this._treeDiv.style.border = border;
  28552. this._treeDiv.style.position = "absolute";
  28553. this._treeDiv.style.background = background;
  28554. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28555. this._treeDiv.style.display = "none";
  28556. this._generateheader(this._treeDiv, "MESHES TREE");
  28557. this._treeSubsetDiv = document.createElement("div");
  28558. this._treeSubsetDiv.style.paddingTop = "5px";
  28559. this._treeSubsetDiv.style.paddingRight = "5px";
  28560. this._treeSubsetDiv.style.overflowY = "auto";
  28561. this._treeSubsetDiv.style.maxHeight = "300px";
  28562. this._treeDiv.appendChild(this._treeSubsetDiv);
  28563. this._needToRefreshMeshesTree = true;
  28564. // Logs
  28565. this._logDiv = document.createElement("div");
  28566. this._logDiv.style.border = border;
  28567. this._logDiv.id = "DebugLayerLogs";
  28568. this._logDiv.style.position = "absolute";
  28569. this._logDiv.style.background = background;
  28570. this._logDiv.style.padding = "0px 0px 0px 5px";
  28571. this._logDiv.style.display = "none";
  28572. this._generateheader(this._logDiv, "LOGS");
  28573. this._logSubsetDiv = document.createElement("div");
  28574. this._logSubsetDiv.style.height = "127px";
  28575. this._logSubsetDiv.style.paddingTop = "5px";
  28576. this._logSubsetDiv.style.overflowY = "auto";
  28577. this._logSubsetDiv.style.fontSize = "12px";
  28578. this._logSubsetDiv.style.fontFamily = "consolas";
  28579. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28580. this._logDiv.appendChild(this._logSubsetDiv);
  28581. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28582. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28583. };
  28584. // Options
  28585. this._optionsDiv = document.createElement("div");
  28586. this._optionsDiv.id = "DebugLayerOptions";
  28587. this._optionsDiv.style.border = border;
  28588. this._optionsDiv.style.position = "absolute";
  28589. this._optionsDiv.style.background = background;
  28590. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28591. this._optionsDiv.style.overflowY = "auto";
  28592. this._generateheader(this._optionsDiv, "OPTIONS");
  28593. this._optionsSubsetDiv = document.createElement("div");
  28594. this._optionsSubsetDiv.style.paddingTop = "5px";
  28595. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28596. this._optionsSubsetDiv.style.overflowY = "auto";
  28597. this._optionsSubsetDiv.style.maxHeight = "200px";
  28598. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28599. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28600. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28601. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28602. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28603. _this._displayTree = element.checked;
  28604. _this._needToRefreshMeshesTree = true;
  28605. });
  28606. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28607. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28608. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28609. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28610. _this._labelsEnabled = element.checked;
  28611. if (!_this._labelsEnabled) {
  28612. _this._clearLabels();
  28613. }
  28614. });
  28615. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28616. if (element.checked) {
  28617. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28618. }
  28619. else {
  28620. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28621. }
  28622. });
  28623. ;
  28624. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28625. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28626. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28627. if (element.checked) {
  28628. _this._scene.forceWireframe = false;
  28629. _this._scene.forcePointsCloud = false;
  28630. }
  28631. });
  28632. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28633. if (element.checked) {
  28634. _this._scene.forceWireframe = true;
  28635. _this._scene.forcePointsCloud = false;
  28636. }
  28637. });
  28638. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28639. if (element.checked) {
  28640. _this._scene.forceWireframe = false;
  28641. _this._scene.forcePointsCloud = true;
  28642. }
  28643. });
  28644. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28645. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28646. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28647. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28648. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28649. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28650. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28651. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28652. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28653. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  28654. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  28655. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28656. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28657. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28658. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28659. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28660. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28661. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28662. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28663. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28664. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28665. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28666. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28667. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28668. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28669. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28670. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28671. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28672. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28673. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28674. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28675. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28676. if (element.checked) {
  28677. _this._scene.headphone = true;
  28678. }
  28679. });
  28680. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28681. if (element.checked) {
  28682. _this._scene.headphone = false;
  28683. }
  28684. });
  28685. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28686. _this._scene.audioEnabled = !element.checked;
  28687. });
  28688. }
  28689. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28690. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28691. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28692. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28693. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28694. if (_this._camera) {
  28695. console.log(_this._camera);
  28696. }
  28697. else {
  28698. console.warn("No camera defined, or debug layer created before camera creation!");
  28699. }
  28700. });
  28701. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28702. this._globalDiv.appendChild(this._statsDiv);
  28703. this._globalDiv.appendChild(this._logDiv);
  28704. this._globalDiv.appendChild(this._optionsDiv);
  28705. this._globalDiv.appendChild(this._treeDiv);
  28706. }
  28707. };
  28708. DebugLayer.prototype._displayStats = function () {
  28709. var scene = this._scene;
  28710. var engine = scene.getEngine();
  28711. var glInfo = engine.getGlInfo();
  28712. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28713. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28714. + "<b>Count</b><br>"
  28715. + "Total meshes: " + scene.meshes.length + "<br>"
  28716. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28717. + "Total materials: " + scene.materials.length + "<br>"
  28718. + "Total textures: " + scene.textures.length + "<br>"
  28719. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28720. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28721. + "Active bones: " + scene.getActiveBones() + "<br>"
  28722. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28723. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  28724. + "<b>Duration</b><br>"
  28725. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28726. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28727. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28728. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28729. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28730. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28731. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  28732. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  28733. + "</div>"
  28734. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28735. + "<b>Extensions</b><br>"
  28736. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28737. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28738. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28739. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  28740. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28741. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28742. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  28743. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  28744. + "</div><br>"
  28745. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28746. + "<b>Caps.</b><br>"
  28747. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28748. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28749. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  28750. + "<b>Info</b><br>"
  28751. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  28752. + glInfo.version + "<br>"
  28753. + "</div><br>"
  28754. + glInfo.renderer + "<br>";
  28755. if (this.customStatsFunction) {
  28756. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28757. }
  28758. };
  28759. return DebugLayer;
  28760. })();
  28761. BABYLON.DebugLayer = DebugLayer;
  28762. })(BABYLON || (BABYLON = {}));
  28763. var BABYLON;
  28764. (function (BABYLON) {
  28765. var DefaultLoadingScreen = (function () {
  28766. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28767. var _this = this;
  28768. if (_loadingText === void 0) { _loadingText = ""; }
  28769. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28770. this._renderingCanvas = _renderingCanvas;
  28771. this._loadingText = _loadingText;
  28772. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28773. // Resize
  28774. this._resizeLoadingUI = function () {
  28775. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28776. _this._loadingDiv.style.position = "absolute";
  28777. _this._loadingDiv.style.left = canvasRect.left + "px";
  28778. _this._loadingDiv.style.top = canvasRect.top + "px";
  28779. _this._loadingDiv.style.width = canvasRect.width + "px";
  28780. _this._loadingDiv.style.height = canvasRect.height + "px";
  28781. };
  28782. }
  28783. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28784. var _this = this;
  28785. if (this._loadingDiv) {
  28786. // Do not add a loading screen if there is already one
  28787. return;
  28788. }
  28789. this._loadingDiv = document.createElement("div");
  28790. this._loadingDiv.id = "babylonjsLoadingDiv";
  28791. this._loadingDiv.style.opacity = "0";
  28792. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28793. // Loading text
  28794. this._loadingTextDiv = document.createElement("div");
  28795. this._loadingTextDiv.style.position = "absolute";
  28796. this._loadingTextDiv.style.left = "0";
  28797. this._loadingTextDiv.style.top = "50%";
  28798. this._loadingTextDiv.style.marginTop = "80px";
  28799. this._loadingTextDiv.style.width = "100%";
  28800. this._loadingTextDiv.style.height = "20px";
  28801. this._loadingTextDiv.style.fontFamily = "Arial";
  28802. this._loadingTextDiv.style.fontSize = "14px";
  28803. this._loadingTextDiv.style.color = "white";
  28804. this._loadingTextDiv.style.textAlign = "center";
  28805. this._loadingTextDiv.innerHTML = "Loading";
  28806. this._loadingDiv.appendChild(this._loadingTextDiv);
  28807. //set the predefined text
  28808. this._loadingTextDiv.innerHTML = this._loadingText;
  28809. // Loading img
  28810. var imgBack = new Image();
  28811. 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==";
  28812. imgBack.style.position = "absolute";
  28813. imgBack.style.left = "50%";
  28814. imgBack.style.top = "50%";
  28815. imgBack.style.marginLeft = "-50px";
  28816. imgBack.style.marginTop = "-50px";
  28817. imgBack.style.transition = "transform 1.0s ease";
  28818. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28819. var deg = 360;
  28820. var onTransitionEnd = function () {
  28821. deg += 360;
  28822. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28823. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28824. };
  28825. imgBack.addEventListener("transitionend", onTransitionEnd);
  28826. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28827. this._loadingDiv.appendChild(imgBack);
  28828. // front image
  28829. var imgFront = new Image();
  28830. 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=";
  28831. imgFront.style.position = "absolute";
  28832. imgFront.style.left = "50%";
  28833. imgFront.style.top = "50%";
  28834. imgFront.style.marginLeft = "-50px";
  28835. imgFront.style.marginTop = "-50px";
  28836. this._loadingDiv.appendChild(imgFront);
  28837. this._resizeLoadingUI();
  28838. window.addEventListener("resize", this._resizeLoadingUI);
  28839. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28840. document.body.appendChild(this._loadingDiv);
  28841. setTimeout(function () {
  28842. _this._loadingDiv.style.opacity = "1";
  28843. imgBack.style.transform = "rotateZ(360deg)";
  28844. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28845. }, 0);
  28846. };
  28847. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28848. var _this = this;
  28849. if (!this._loadingDiv) {
  28850. return;
  28851. }
  28852. var onTransitionEnd = function () {
  28853. if (!_this._loadingDiv) {
  28854. return;
  28855. }
  28856. document.body.removeChild(_this._loadingDiv);
  28857. window.removeEventListener("resize", _this._resizeLoadingUI);
  28858. _this._loadingDiv = null;
  28859. };
  28860. this._loadingDiv.style.opacity = "0";
  28861. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28862. };
  28863. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28864. set: function (text) {
  28865. this._loadingText = text;
  28866. if (this._loadingTextDiv) {
  28867. this._loadingTextDiv.innerHTML = this._loadingText;
  28868. }
  28869. },
  28870. enumerable: true,
  28871. configurable: true
  28872. });
  28873. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28874. get: function () {
  28875. return this._loadingDivBackgroundColor;
  28876. },
  28877. set: function (color) {
  28878. this._loadingDivBackgroundColor = color;
  28879. if (!this._loadingDiv) {
  28880. return;
  28881. }
  28882. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28883. },
  28884. enumerable: true,
  28885. configurable: true
  28886. });
  28887. return DefaultLoadingScreen;
  28888. })();
  28889. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28890. })(BABYLON || (BABYLON = {}));
  28891. var BABYLON;
  28892. (function (BABYLON) {
  28893. var SIMDVector3 = (function () {
  28894. function SIMDVector3() {
  28895. }
  28896. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28897. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28898. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28899. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28900. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28901. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28902. 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));
  28903. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28904. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28905. };
  28906. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28907. var v0 = SIMD.float32x4.splat(x);
  28908. var v1 = SIMD.float32x4.splat(y);
  28909. var v2 = SIMD.float32x4.splat(z);
  28910. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28911. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28912. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28913. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28914. 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));
  28915. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28916. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28917. };
  28918. return SIMDVector3;
  28919. })();
  28920. BABYLON.SIMDVector3 = SIMDVector3;
  28921. var SIMDMatrix = (function () {
  28922. function SIMDMatrix() {
  28923. }
  28924. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28925. if (offset === void 0) { offset = 0; }
  28926. var tm = this.m;
  28927. var om = other.m;
  28928. var om0 = SIMD.float32x4.load(om, 0);
  28929. var om1 = SIMD.float32x4.load(om, 4);
  28930. var om2 = SIMD.float32x4.load(om, 8);
  28931. var om3 = SIMD.float32x4.load(om, 12);
  28932. var tm0 = SIMD.float32x4.load(tm, 0);
  28933. 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)))));
  28934. var tm1 = SIMD.float32x4.load(tm, 4);
  28935. 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)))));
  28936. var tm2 = SIMD.float32x4.load(tm, 8);
  28937. 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)))));
  28938. var tm3 = SIMD.float32x4.load(tm, 12);
  28939. 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)))));
  28940. };
  28941. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28942. var src = this.m;
  28943. var dest = other.m;
  28944. var row0, row1, row2, row3;
  28945. var tmp1;
  28946. var minor0, minor1, minor2, minor3;
  28947. var det;
  28948. // Load the 4 rows
  28949. var src0 = SIMD.float32x4.load(src, 0);
  28950. var src1 = SIMD.float32x4.load(src, 4);
  28951. var src2 = SIMD.float32x4.load(src, 8);
  28952. var src3 = SIMD.float32x4.load(src, 12);
  28953. // Transpose the source matrix. Sort of. Not a true transpose operation
  28954. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28955. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28956. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28957. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28958. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28959. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28960. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28961. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28962. // This is a true transposition, but it will lead to an incorrect result
  28963. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28964. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28965. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28966. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28967. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28968. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28969. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28970. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28971. // ----
  28972. tmp1 = SIMD.float32x4.mul(row2, row3);
  28973. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28974. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28975. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28976. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28977. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28978. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28979. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28980. // ----
  28981. tmp1 = SIMD.float32x4.mul(row1, row2);
  28982. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28983. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28984. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28985. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28986. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28987. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28988. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28989. // ----
  28990. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28991. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28992. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28993. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28994. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28995. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28996. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28997. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28998. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28999. // ----
  29000. tmp1 = SIMD.float32x4.mul(row0, row1);
  29001. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29002. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29003. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29004. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29005. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29006. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29007. // ----
  29008. tmp1 = SIMD.float32x4.mul(row0, row3);
  29009. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29010. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29011. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29012. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29013. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29014. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29015. // ----
  29016. tmp1 = SIMD.float32x4.mul(row0, row2);
  29017. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29018. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29019. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29020. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29021. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29022. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29023. // Compute determinant
  29024. det = SIMD.float32x4.mul(row0, minor0);
  29025. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29026. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29027. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29028. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29029. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29030. // These shuffles aren't necessary if the faulty transposition is done
  29031. // up at the top of this function.
  29032. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29033. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29034. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29035. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29036. // Compute final values by multiplying with 1/det
  29037. minor0 = SIMD.float32x4.mul(det, minor0);
  29038. minor1 = SIMD.float32x4.mul(det, minor1);
  29039. minor2 = SIMD.float32x4.mul(det, minor2);
  29040. minor3 = SIMD.float32x4.mul(det, minor3);
  29041. SIMD.float32x4.store(dest, 0, minor0);
  29042. SIMD.float32x4.store(dest, 4, minor1);
  29043. SIMD.float32x4.store(dest, 8, minor2);
  29044. SIMD.float32x4.store(dest, 12, minor3);
  29045. return this;
  29046. };
  29047. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29048. var out = result.m;
  29049. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29050. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29051. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29052. // cc.kmVec3Subtract(f, pCenter, pEye);
  29053. var f = SIMD.float32x4.sub(center, eye);
  29054. // cc.kmVec3Normalize(f, f);
  29055. var tmp = SIMD.float32x4.mul(f, f);
  29056. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29057. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29058. // cc.kmVec3Assign(up, pUp);
  29059. // cc.kmVec3Normalize(up, up);
  29060. tmp = SIMD.float32x4.mul(up, up);
  29061. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29062. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29063. // cc.kmVec3Cross(s, f, up);
  29064. 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)));
  29065. // cc.kmVec3Normalize(s, s);
  29066. tmp = SIMD.float32x4.mul(s, s);
  29067. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29068. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29069. // cc.kmVec3Cross(u, s, f);
  29070. 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)));
  29071. // cc.kmVec3Normalize(s, s);
  29072. tmp = SIMD.float32x4.mul(s, s);
  29073. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29074. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29075. var zero = SIMD.float32x4.splat(0.0);
  29076. s = SIMD.float32x4.neg(s);
  29077. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29078. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29079. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29080. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29081. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29082. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29083. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29084. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29085. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29086. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29087. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29088. var b3 = SIMD.float32x4.neg(eye);
  29089. b3 = SIMD.float32x4.withW(b3, 1.0);
  29090. 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)))));
  29091. 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)))));
  29092. 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)))));
  29093. 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)))));
  29094. };
  29095. return SIMDMatrix;
  29096. })();
  29097. BABYLON.SIMDMatrix = SIMDMatrix;
  29098. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29099. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29100. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29101. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29102. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29103. var SIMDHelper = (function () {
  29104. function SIMDHelper() {
  29105. }
  29106. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29107. get: function () {
  29108. return SIMDHelper._isEnabled;
  29109. },
  29110. enumerable: true,
  29111. configurable: true
  29112. });
  29113. SIMDHelper.DisableSIMD = function () {
  29114. // Replace functions
  29115. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29116. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29117. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29118. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29120. SIMDHelper._isEnabled = false;
  29121. };
  29122. SIMDHelper.EnableSIMD = function () {
  29123. if (window.SIMD === undefined) {
  29124. return;
  29125. }
  29126. // Replace functions
  29127. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29128. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29129. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29130. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29132. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29133. get: function () { return this._data[0]; },
  29134. set: function (value) {
  29135. if (!this._data) {
  29136. this._data = new Float32Array(3);
  29137. }
  29138. this._data[0] = value;
  29139. }
  29140. });
  29141. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29142. get: function () { return this._data[1]; },
  29143. set: function (value) {
  29144. this._data[1] = value;
  29145. }
  29146. });
  29147. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29148. get: function () { return this._data[2]; },
  29149. set: function (value) {
  29150. this._data[2] = value;
  29151. }
  29152. });
  29153. SIMDHelper._isEnabled = true;
  29154. };
  29155. SIMDHelper._isEnabled = false;
  29156. return SIMDHelper;
  29157. })();
  29158. BABYLON.SIMDHelper = SIMDHelper;
  29159. })(BABYLON || (BABYLON = {}));
  29160. var BABYLON;
  29161. (function (BABYLON) {
  29162. var ShaderMaterial = (function (_super) {
  29163. __extends(ShaderMaterial, _super);
  29164. function ShaderMaterial(name, scene, shaderPath, options) {
  29165. _super.call(this, name, scene);
  29166. this._textures = {};
  29167. this._floats = {};
  29168. this._floatsArrays = {};
  29169. this._colors3 = {};
  29170. this._colors4 = {};
  29171. this._vectors2 = {};
  29172. this._vectors3 = {};
  29173. this._vectors4 = {};
  29174. this._matrices = {};
  29175. this._matrices3x3 = {};
  29176. this._matrices2x2 = {};
  29177. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29178. this._shaderPath = shaderPath;
  29179. options.needAlphaBlending = options.needAlphaBlending || false;
  29180. options.needAlphaTesting = options.needAlphaTesting || false;
  29181. options.attributes = options.attributes || ["position", "normal", "uv"];
  29182. options.uniforms = options.uniforms || ["worldViewProjection"];
  29183. options.samplers = options.samplers || [];
  29184. options.defines = options.defines || [];
  29185. this._options = options;
  29186. }
  29187. ShaderMaterial.prototype.needAlphaBlending = function () {
  29188. return this._options.needAlphaBlending;
  29189. };
  29190. ShaderMaterial.prototype.needAlphaTesting = function () {
  29191. return this._options.needAlphaTesting;
  29192. };
  29193. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29194. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29195. this._options.uniforms.push(uniformName);
  29196. }
  29197. };
  29198. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29199. if (this._options.samplers.indexOf(name) === -1) {
  29200. this._options.samplers.push(name);
  29201. }
  29202. this._textures[name] = texture;
  29203. return this;
  29204. };
  29205. ShaderMaterial.prototype.setFloat = function (name, value) {
  29206. this._checkUniform(name);
  29207. this._floats[name] = value;
  29208. return this;
  29209. };
  29210. ShaderMaterial.prototype.setFloats = function (name, value) {
  29211. this._checkUniform(name);
  29212. this._floatsArrays[name] = value;
  29213. return this;
  29214. };
  29215. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29216. this._checkUniform(name);
  29217. this._colors3[name] = value;
  29218. return this;
  29219. };
  29220. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29221. this._checkUniform(name);
  29222. this._colors4[name] = value;
  29223. return this;
  29224. };
  29225. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29226. this._checkUniform(name);
  29227. this._vectors2[name] = value;
  29228. return this;
  29229. };
  29230. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29231. this._checkUniform(name);
  29232. this._vectors3[name] = value;
  29233. return this;
  29234. };
  29235. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29236. this._checkUniform(name);
  29237. this._vectors4[name] = value;
  29238. return this;
  29239. };
  29240. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29241. this._checkUniform(name);
  29242. this._matrices[name] = value;
  29243. return this;
  29244. };
  29245. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29246. this._checkUniform(name);
  29247. this._matrices3x3[name] = value;
  29248. return this;
  29249. };
  29250. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29251. this._checkUniform(name);
  29252. this._matrices2x2[name] = value;
  29253. return this;
  29254. };
  29255. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  29256. var scene = this.getScene();
  29257. var engine = scene.getEngine();
  29258. if (!this.checkReadyOnEveryCall) {
  29259. if (this._renderId === scene.getRenderId()) {
  29260. return true;
  29261. }
  29262. }
  29263. // Instances
  29264. var defines = [];
  29265. var fallbacks = new BABYLON.EffectFallbacks();
  29266. if (useInstances) {
  29267. defines.push("#define INSTANCES");
  29268. }
  29269. for (var index = 0; index < this._options.defines.length; index++) {
  29270. defines.push(this._options.defines[index]);
  29271. }
  29272. // Bones
  29273. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  29275. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29276. fallbacks.addCPUSkinningFallback(0, mesh);
  29277. }
  29278. // Alpha test
  29279. if (engine.getAlphaTesting()) {
  29280. defines.push("#define ALPHATEST");
  29281. }
  29282. var previousEffect = this._effect;
  29283. var join = defines.join("\n");
  29284. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  29285. if (!this._effect.isReady()) {
  29286. return false;
  29287. }
  29288. if (previousEffect !== this._effect) {
  29289. scene.resetCachedMaterial();
  29290. }
  29291. this._renderId = scene.getRenderId();
  29292. return true;
  29293. };
  29294. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29295. var scene = this.getScene();
  29296. if (this._options.uniforms.indexOf("world") !== -1) {
  29297. this._effect.setMatrix("world", world);
  29298. }
  29299. if (this._options.uniforms.indexOf("worldView") !== -1) {
  29300. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  29301. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  29302. }
  29303. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  29304. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  29305. }
  29306. };
  29307. ShaderMaterial.prototype.bind = function (world, mesh) {
  29308. // Std values
  29309. this.bindOnlyWorldMatrix(world);
  29310. if (this.getScene().getCachedMaterial() !== this) {
  29311. if (this._options.uniforms.indexOf("view") !== -1) {
  29312. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  29313. }
  29314. if (this._options.uniforms.indexOf("projection") !== -1) {
  29315. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  29316. }
  29317. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  29318. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29319. }
  29320. // Bones
  29321. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29322. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  29323. }
  29324. // Texture
  29325. for (var name in this._textures) {
  29326. this._effect.setTexture(name, this._textures[name]);
  29327. }
  29328. // Float
  29329. for (name in this._floats) {
  29330. this._effect.setFloat(name, this._floats[name]);
  29331. }
  29332. // Float s
  29333. for (name in this._floatsArrays) {
  29334. this._effect.setArray(name, this._floatsArrays[name]);
  29335. }
  29336. // Color3
  29337. for (name in this._colors3) {
  29338. this._effect.setColor3(name, this._colors3[name]);
  29339. }
  29340. // Color4
  29341. for (name in this._colors4) {
  29342. var color = this._colors4[name];
  29343. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29344. }
  29345. // Vector2
  29346. for (name in this._vectors2) {
  29347. this._effect.setVector2(name, this._vectors2[name]);
  29348. }
  29349. // Vector3
  29350. for (name in this._vectors3) {
  29351. this._effect.setVector3(name, this._vectors3[name]);
  29352. }
  29353. // Vector4
  29354. for (name in this._vectors4) {
  29355. this._effect.setVector4(name, this._vectors4[name]);
  29356. }
  29357. // Matrix
  29358. for (name in this._matrices) {
  29359. this._effect.setMatrix(name, this._matrices[name]);
  29360. }
  29361. // Matrix 3x3
  29362. for (name in this._matrices3x3) {
  29363. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  29364. }
  29365. // Matrix 2x2
  29366. for (name in this._matrices2x2) {
  29367. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  29368. }
  29369. }
  29370. _super.prototype.bind.call(this, world, mesh);
  29371. };
  29372. ShaderMaterial.prototype.clone = function (name) {
  29373. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  29374. return newShaderMaterial;
  29375. };
  29376. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  29377. for (var name in this._textures) {
  29378. this._textures[name].dispose();
  29379. }
  29380. this._textures = {};
  29381. _super.prototype.dispose.call(this, forceDisposeEffect);
  29382. };
  29383. ShaderMaterial.prototype.serialize = function () {
  29384. var serializationObject = _super.prototype.serialize.call(this);
  29385. serializationObject.options = this._options;
  29386. serializationObject.shaderPath = this._shaderPath;
  29387. serializationObject.customType = "BABYLON.ShaderMaterial";
  29388. // Texture
  29389. serializationObject.textures = {};
  29390. for (var name in this._textures) {
  29391. serializationObject.textures[name] = this._textures[name].serialize();
  29392. }
  29393. // Float
  29394. serializationObject.floats = {};
  29395. for (name in this._floats) {
  29396. serializationObject.floats[name] = this._floats[name];
  29397. }
  29398. // Float s
  29399. serializationObject.floatArrays = {};
  29400. for (name in this._floatsArrays) {
  29401. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29402. }
  29403. // Color3
  29404. serializationObject.colors3 = {};
  29405. for (name in this._colors3) {
  29406. serializationObject.colors3[name] = this._colors3[name].asArray();
  29407. }
  29408. // Color4
  29409. serializationObject.colors4 = {};
  29410. for (name in this._colors4) {
  29411. serializationObject.colors4[name] = this._colors4[name].asArray();
  29412. }
  29413. // Vector2
  29414. serializationObject.vectors2 = {};
  29415. for (name in this._vectors2) {
  29416. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29417. }
  29418. // Vector3
  29419. serializationObject.vectors3 = {};
  29420. for (name in this._vectors3) {
  29421. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29422. }
  29423. // Vector4
  29424. serializationObject.vectors4 = {};
  29425. for (name in this._vectors4) {
  29426. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29427. }
  29428. // Matrix
  29429. serializationObject.matrices = {};
  29430. for (name in this._matrices) {
  29431. serializationObject.matrices[name] = this._matrices[name].asArray();
  29432. }
  29433. // Matrix 3x3
  29434. serializationObject.matrices3x3 = {};
  29435. for (name in this._matrices3x3) {
  29436. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29437. }
  29438. // Matrix 2x2
  29439. serializationObject.matrices2x2 = {};
  29440. for (name in this._matrices2x2) {
  29441. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29442. }
  29443. return serializationObject;
  29444. };
  29445. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29446. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  29447. // Texture
  29448. for (var name in source.textures) {
  29449. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29450. }
  29451. // Float
  29452. for (name in source.floats) {
  29453. material.setFloat(name, source.floats[name]);
  29454. }
  29455. // Float s
  29456. for (name in source.floatsArrays) {
  29457. material.setFloats(name, source.floatsArrays[name]);
  29458. }
  29459. // Color3
  29460. for (name in source.colors3) {
  29461. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29462. }
  29463. // Color4
  29464. for (name in source.colors4) {
  29465. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29466. }
  29467. // Vector2
  29468. for (name in source.vectors2) {
  29469. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29470. }
  29471. // Vector3
  29472. for (name in source.vectors3) {
  29473. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29474. }
  29475. // Vector4
  29476. for (name in source.vectors4) {
  29477. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29478. }
  29479. // Matrix
  29480. for (name in source.matrices) {
  29481. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29482. }
  29483. // Matrix 3x3
  29484. for (name in source.matrices3x3) {
  29485. material.setMatrix3x3(name, source.matrices3x3[name]);
  29486. }
  29487. // Matrix 2x2
  29488. for (name in source.matrices2x2) {
  29489. material.setMatrix2x2(name, source.matrices2x2[name]);
  29490. }
  29491. return material;
  29492. };
  29493. return ShaderMaterial;
  29494. })(BABYLON.Material);
  29495. BABYLON.ShaderMaterial = ShaderMaterial;
  29496. })(BABYLON || (BABYLON = {}));
  29497. var BABYLON;
  29498. (function (BABYLON) {
  29499. var Internals;
  29500. (function (Internals) {
  29501. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29502. // All values and structures referenced from:
  29503. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29504. var DDS_MAGIC = 0x20534444;
  29505. 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;
  29506. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29507. 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;
  29508. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29509. function FourCCToInt32(value) {
  29510. return value.charCodeAt(0) +
  29511. (value.charCodeAt(1) << 8) +
  29512. (value.charCodeAt(2) << 16) +
  29513. (value.charCodeAt(3) << 24);
  29514. }
  29515. function Int32ToFourCC(value) {
  29516. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29517. }
  29518. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29519. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29520. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29521. var headerLengthInt = 31; // The header length in 32 bit ints
  29522. // Offsets into the header array
  29523. var off_magic = 0;
  29524. var off_size = 1;
  29525. var off_flags = 2;
  29526. var off_height = 3;
  29527. var off_width = 4;
  29528. var off_mipmapCount = 7;
  29529. var off_pfFlags = 20;
  29530. var off_pfFourCC = 21;
  29531. var off_RGBbpp = 22;
  29532. var off_RMask = 23;
  29533. var off_GMask = 24;
  29534. var off_BMask = 25;
  29535. var off_AMask = 26;
  29536. var off_caps1 = 27;
  29537. var off_caps2 = 28;
  29538. ;
  29539. var DDSTools = (function () {
  29540. function DDSTools() {
  29541. }
  29542. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29543. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29544. var mipmapCount = 1;
  29545. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29546. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29547. }
  29548. return {
  29549. width: header[off_width],
  29550. height: header[off_height],
  29551. mipmapCount: mipmapCount,
  29552. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29553. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29554. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29555. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29556. };
  29557. };
  29558. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29559. var byteArray = new Uint8Array(dataLength);
  29560. var srcData = new Uint8Array(arrayBuffer);
  29561. var index = 0;
  29562. for (var y = height - 1; y >= 0; y--) {
  29563. for (var x = 0; x < width; x++) {
  29564. var srcPos = dataOffset + (x + y * width) * 4;
  29565. byteArray[index + 2] = srcData[srcPos];
  29566. byteArray[index + 1] = srcData[srcPos + 1];
  29567. byteArray[index] = srcData[srcPos + 2];
  29568. byteArray[index + 3] = srcData[srcPos + 3];
  29569. index += 4;
  29570. }
  29571. }
  29572. return byteArray;
  29573. };
  29574. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29575. var byteArray = new Uint8Array(dataLength);
  29576. var srcData = new Uint8Array(arrayBuffer);
  29577. var index = 0;
  29578. for (var y = height - 1; y >= 0; y--) {
  29579. for (var x = 0; x < width; x++) {
  29580. var srcPos = dataOffset + (x + y * width) * 3;
  29581. byteArray[index + 2] = srcData[srcPos];
  29582. byteArray[index + 1] = srcData[srcPos + 1];
  29583. byteArray[index] = srcData[srcPos + 2];
  29584. index += 3;
  29585. }
  29586. }
  29587. return byteArray;
  29588. };
  29589. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29590. var byteArray = new Uint8Array(dataLength);
  29591. var srcData = new Uint8Array(arrayBuffer);
  29592. var index = 0;
  29593. for (var y = height - 1; y >= 0; y--) {
  29594. for (var x = 0; x < width; x++) {
  29595. var srcPos = dataOffset + (x + y * width);
  29596. byteArray[index] = srcData[srcPos];
  29597. index++;
  29598. }
  29599. }
  29600. return byteArray;
  29601. };
  29602. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29603. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29604. if (header[off_magic] != DDS_MAGIC) {
  29605. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29606. return;
  29607. }
  29608. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29609. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29610. return;
  29611. }
  29612. if (info.isFourCC) {
  29613. fourCC = header[off_pfFourCC];
  29614. switch (fourCC) {
  29615. case FOURCC_DXT1:
  29616. blockBytes = 8;
  29617. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29618. break;
  29619. case FOURCC_DXT3:
  29620. blockBytes = 16;
  29621. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29622. break;
  29623. case FOURCC_DXT5:
  29624. blockBytes = 16;
  29625. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29626. break;
  29627. default:
  29628. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29629. return;
  29630. }
  29631. }
  29632. mipmapCount = 1;
  29633. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29634. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29635. }
  29636. var bpp = header[off_RGBbpp];
  29637. for (var face = 0; face < faces; face++) {
  29638. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29639. width = header[off_width];
  29640. height = header[off_height];
  29641. dataOffset = header[off_size] + 4;
  29642. for (i = 0; i < mipmapCount; ++i) {
  29643. if (info.isRGB) {
  29644. if (bpp === 24) {
  29645. dataLength = width * height * 3;
  29646. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29647. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29648. }
  29649. else {
  29650. dataLength = width * height * 4;
  29651. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29652. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29653. }
  29654. }
  29655. else if (info.isLuminance) {
  29656. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29657. var unpaddedRowSize = width;
  29658. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29659. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29660. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29661. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29662. }
  29663. else {
  29664. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29665. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29666. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29667. }
  29668. dataOffset += dataLength;
  29669. width *= 0.5;
  29670. height *= 0.5;
  29671. width = Math.max(1.0, width);
  29672. height = Math.max(1.0, height);
  29673. }
  29674. }
  29675. };
  29676. return DDSTools;
  29677. })();
  29678. Internals.DDSTools = DDSTools;
  29679. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29680. })(BABYLON || (BABYLON = {}));
  29681. var BABYLON;
  29682. (function (BABYLON) {
  29683. var CannonJSPlugin = (function () {
  29684. function CannonJSPlugin(_useDeltaForWorldStep) {
  29685. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  29686. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  29687. this._registeredMeshes = [];
  29688. this._physicsMaterials = [];
  29689. this._fixedTimeStep = 1 / 60;
  29690. //private _maxSubSteps : number = 15;
  29691. this.name = "CannonJS";
  29692. this.updateBodyPosition = function (mesh) {
  29693. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29694. var registeredMesh = this._registeredMeshes[index];
  29695. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29696. var body = registeredMesh.body;
  29697. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29698. body.quaternion.copy(mesh.rotationQuaternion);
  29699. if (registeredMesh.deltaRotation) {
  29700. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29701. body.quaternion = body.quaternion.mult(tmpQ);
  29702. }
  29703. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29704. //calculate the correct body position:
  29705. var rotationQuaternion = mesh.rotationQuaternion;
  29706. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29707. mesh.computeWorldMatrix(true);
  29708. //get original center with no rotation
  29709. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29710. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29711. //rotation is back
  29712. mesh.rotationQuaternion = rotationQuaternion;
  29713. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29714. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29715. mesh.setPivotMatrix(p);
  29716. mesh.computeWorldMatrix(true);
  29717. //calculate the translation
  29718. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29719. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29720. //add it inverted to the delta
  29721. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29722. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29723. mesh.setPivotMatrix(oldPivot);
  29724. mesh.computeWorldMatrix(true);
  29725. }
  29726. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29727. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29728. }
  29729. body.position.set(center.x, center.y, center.z);
  29730. return;
  29731. }
  29732. }
  29733. };
  29734. }
  29735. CannonJSPlugin.prototype.initialize = function (iterations) {
  29736. if (iterations === void 0) { iterations = 10; }
  29737. this._world = new CANNON.World();
  29738. this._world.broadphase = new CANNON.NaiveBroadphase();
  29739. this._world.solver.iterations = iterations;
  29740. };
  29741. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29742. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29743. };
  29744. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29745. var _this = this;
  29746. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  29747. this._registeredMeshes.forEach(function (registeredMesh) {
  29748. // Body position
  29749. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29750. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29751. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29752. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29753. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29754. if (registeredMesh.deltaRotation) {
  29755. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29756. }
  29757. //is the physics collision callback is set?
  29758. if (registeredMesh.mesh.onPhysicsCollide) {
  29759. if (!registeredMesh.collisionFunction) {
  29760. registeredMesh.collisionFunction = function (e) {
  29761. //find the mesh that collided with the registered mesh
  29762. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29763. if (_this._registeredMeshes[idx].body == e.body) {
  29764. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29765. }
  29766. }
  29767. };
  29768. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29769. }
  29770. }
  29771. else {
  29772. //unregister, in case the function was removed for some reason
  29773. if (registeredMesh.collisionFunction) {
  29774. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29775. }
  29776. }
  29777. });
  29778. };
  29779. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29780. this._gravity = gravity;
  29781. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29782. };
  29783. CannonJSPlugin.prototype.getGravity = function () {
  29784. return this._gravity;
  29785. };
  29786. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29787. this.unregisterMesh(mesh);
  29788. if (!mesh.rotationQuaternion) {
  29789. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29790. }
  29791. mesh.computeWorldMatrix(true);
  29792. var shape = this._createShape(mesh, impostor);
  29793. return this._createRigidBodyFromShape(shape, mesh, options);
  29794. };
  29795. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29796. //get the correct bounding box
  29797. var oldQuaternion = mesh.rotationQuaternion;
  29798. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29799. mesh.computeWorldMatrix(true);
  29800. var returnValue;
  29801. switch (impostor) {
  29802. case BABYLON.PhysicsEngine.SphereImpostor:
  29803. var bbox = mesh.getBoundingInfo().boundingBox;
  29804. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29805. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29806. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29807. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29808. break;
  29809. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29810. case BABYLON.PhysicsEngine.CylinderImpostor:
  29811. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29812. case BABYLON.PhysicsEngine.BoxImpostor:
  29813. bbox = mesh.getBoundingInfo().boundingBox;
  29814. var min = bbox.minimumWorld;
  29815. var max = bbox.maximumWorld;
  29816. var box = max.subtract(min).scale(0.5);
  29817. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29818. break;
  29819. case BABYLON.PhysicsEngine.PlaneImpostor:
  29820. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29821. returnValue = new CANNON.Plane();
  29822. break;
  29823. case BABYLON.PhysicsEngine.MeshImpostor:
  29824. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29825. var rawFaces = mesh.getIndices();
  29826. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29827. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29828. break;
  29829. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29830. returnValue = this._createHeightmap(mesh);
  29831. break;
  29832. }
  29833. mesh.rotationQuaternion = oldQuaternion;
  29834. return returnValue;
  29835. };
  29836. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29837. var verts = [], faces = [];
  29838. mesh.computeWorldMatrix(true);
  29839. //reuse this variable
  29840. var transformed = BABYLON.Vector3.Zero();
  29841. // Get vertices
  29842. for (var i = 0; i < rawVerts.length; i += 3) {
  29843. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29844. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29845. }
  29846. // Get faces
  29847. for (var j = 0; j < rawFaces.length; j += 3) {
  29848. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29849. }
  29850. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29851. return shape;
  29852. };
  29853. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29854. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29855. var matrix = [];
  29856. //For now pointDepth will not be used and will be automatically calculated.
  29857. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29858. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29859. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29860. var elementSize = dim * 2 / arraySize;
  29861. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29862. for (var i = 0; i < pos.length; i = i + 3) {
  29863. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29864. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29865. var y = pos[i + 1] + minY;
  29866. if (!matrix[x]) {
  29867. matrix[x] = [];
  29868. }
  29869. if (!matrix[x][z]) {
  29870. matrix[x][z] = y;
  29871. }
  29872. matrix[x][z] = Math.max(y, matrix[x][z]);
  29873. }
  29874. for (var x = 0; x <= arraySize; ++x) {
  29875. if (!matrix[x]) {
  29876. var loc = 1;
  29877. while (!matrix[(x + loc) % arraySize]) {
  29878. loc++;
  29879. }
  29880. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29881. }
  29882. for (var z = 0; z <= arraySize; ++z) {
  29883. if (!matrix[x][z]) {
  29884. var loc = 1;
  29885. var newValue;
  29886. while (newValue === undefined) {
  29887. newValue = matrix[x][(z + loc++) % arraySize];
  29888. }
  29889. matrix[x][z] = newValue;
  29890. }
  29891. }
  29892. }
  29893. var shape = new CANNON.Heightfield(matrix, {
  29894. elementSize: elementSize
  29895. });
  29896. //For future reference, needed for body transformation
  29897. shape.minY = minY;
  29898. return shape;
  29899. };
  29900. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29901. var index;
  29902. var mat;
  29903. for (index = 0; index < this._physicsMaterials.length; index++) {
  29904. mat = this._physicsMaterials[index];
  29905. if (mat.friction === friction && mat.restitution === restitution) {
  29906. return mat;
  29907. }
  29908. }
  29909. var currentMat = new CANNON.Material("mat");
  29910. this._physicsMaterials.push(currentMat);
  29911. for (index = 0; index < this._physicsMaterials.length; index++) {
  29912. mat = this._physicsMaterials[index];
  29913. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29914. this._world.addContactMaterial(contactMaterial);
  29915. }
  29916. return currentMat;
  29917. };
  29918. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29919. if (!mesh.rotationQuaternion) {
  29920. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29921. }
  29922. // The delta between the mesh position and the mesh bounding box center
  29923. var bbox = mesh.getBoundingInfo().boundingBox;
  29924. var deltaPosition = mesh.position.subtract(bbox.center);
  29925. var deltaRotation;
  29926. var material = this._addMaterial(options.friction, options.restitution);
  29927. var body = new CANNON.Body({
  29928. mass: options.mass,
  29929. material: material,
  29930. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29931. });
  29932. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29933. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29934. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29935. //-90 DEG in X, precalculated
  29936. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29937. body.quaternion = body.quaternion.mult(tmpQ);
  29938. //Invert! (Precalculated, 90 deg in X)
  29939. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29940. }
  29941. //If it is a heightfield, if should be centered.
  29942. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29943. //calculate the correct body position:
  29944. var rotationQuaternion = mesh.rotationQuaternion;
  29945. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29946. mesh.computeWorldMatrix(true);
  29947. //get original center with no rotation
  29948. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29949. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29950. //rotation is back
  29951. mesh.rotationQuaternion = rotationQuaternion;
  29952. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29953. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29954. mesh.setPivotMatrix(p);
  29955. mesh.computeWorldMatrix(true);
  29956. //calculate the translation
  29957. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29958. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29959. //add it inverted to the delta
  29960. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29961. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29962. mesh.setPivotMatrix(oldPivot);
  29963. mesh.computeWorldMatrix(true);
  29964. }
  29965. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29966. deltaPosition = BABYLON.Vector3.Zero();
  29967. }
  29968. //add the shape
  29969. body.addShape(shape);
  29970. this._world.add(body);
  29971. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29972. return body;
  29973. };
  29974. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29975. var initialMesh = parts[0].mesh;
  29976. this.unregisterMesh(initialMesh);
  29977. initialMesh.computeWorldMatrix(true);
  29978. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29979. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29980. for (var index = 1; index < parts.length; index++) {
  29981. var mesh = parts[index].mesh;
  29982. mesh.computeWorldMatrix(true);
  29983. var shape = this._createShape(mesh, parts[index].impostor);
  29984. var localPosition = mesh.position;
  29985. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29986. }
  29987. return body;
  29988. };
  29989. CannonJSPlugin.prototype._unbindBody = function (body) {
  29990. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29991. var registeredMesh = this._registeredMeshes[index];
  29992. if (registeredMesh.body === body) {
  29993. this._world.remove(registeredMesh.body);
  29994. registeredMesh.body = null;
  29995. registeredMesh.delta = null;
  29996. registeredMesh.deltaRotation = null;
  29997. }
  29998. }
  29999. };
  30000. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30001. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30002. var registeredMesh = this._registeredMeshes[index];
  30003. if (registeredMesh.mesh === mesh) {
  30004. // Remove body
  30005. if (registeredMesh.body) {
  30006. this._unbindBody(registeredMesh.body);
  30007. }
  30008. this._registeredMeshes.splice(index, 1);
  30009. return;
  30010. }
  30011. }
  30012. };
  30013. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30014. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30015. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30016. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30017. var registeredMesh = this._registeredMeshes[index];
  30018. if (registeredMesh.mesh === mesh) {
  30019. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30020. return;
  30021. }
  30022. }
  30023. };
  30024. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30025. var body1 = null, body2 = null;
  30026. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30027. var registeredMesh = this._registeredMeshes[index];
  30028. if (registeredMesh.mesh === mesh1) {
  30029. body1 = registeredMesh.body;
  30030. if (body2)
  30031. break;
  30032. }
  30033. else if (registeredMesh.mesh === mesh2) {
  30034. body2 = registeredMesh.body;
  30035. if (body1)
  30036. break;
  30037. }
  30038. }
  30039. if (!body1 || !body2) {
  30040. return false;
  30041. }
  30042. 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));
  30043. this._world.addConstraint(constraint);
  30044. return true;
  30045. };
  30046. CannonJSPlugin.prototype.dispose = function () {
  30047. while (this._registeredMeshes.length) {
  30048. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30049. }
  30050. };
  30051. CannonJSPlugin.prototype.isSupported = function () {
  30052. return window.CANNON !== undefined;
  30053. };
  30054. CannonJSPlugin.prototype.getWorldObject = function () {
  30055. return this._world;
  30056. };
  30057. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30058. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30059. var registeredMesh = this._registeredMeshes[index];
  30060. if (registeredMesh.mesh === mesh) {
  30061. return registeredMesh.body;
  30062. }
  30063. }
  30064. return null;
  30065. };
  30066. return CannonJSPlugin;
  30067. })();
  30068. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30069. })(BABYLON || (BABYLON = {}));
  30070. var BABYLON;
  30071. (function (BABYLON) {
  30072. var OimoJSPlugin = (function () {
  30073. function OimoJSPlugin() {
  30074. this._registeredMeshes = [];
  30075. this.name = "oimo";
  30076. /**
  30077. * Update the body position according to the mesh position
  30078. * @param mesh
  30079. */
  30080. this.updateBodyPosition = function (mesh) {
  30081. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30082. var registeredMesh = this._registeredMeshes[index];
  30083. var body = registeredMesh.body.body;
  30084. var updated = false;
  30085. var newPosition;
  30086. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30087. mesh.computeWorldMatrix(true);
  30088. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30089. updated = true;
  30090. }
  30091. else if (registeredMesh.mesh.parent === mesh) {
  30092. mesh.computeWorldMatrix(true);
  30093. registeredMesh.mesh.computeWorldMatrix(true);
  30094. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30095. updated = true;
  30096. }
  30097. if (updated) {
  30098. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30099. body.setQuaternion(mesh.rotationQuaternion);
  30100. body.sleeping = false;
  30101. //force Oimo to update the body's position
  30102. body.updatePosition(1);
  30103. }
  30104. }
  30105. };
  30106. }
  30107. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30108. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30109. };
  30110. OimoJSPlugin.prototype.initialize = function (iterations) {
  30111. this._world = new OIMO.World(null, null, iterations);
  30112. this._world.clear();
  30113. };
  30114. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30115. this._gravity = this._world.gravity = gravity;
  30116. };
  30117. OimoJSPlugin.prototype.getGravity = function () {
  30118. return this._gravity;
  30119. };
  30120. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30121. this.unregisterMesh(mesh);
  30122. if (!mesh.rotationQuaternion) {
  30123. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30124. }
  30125. mesh.computeWorldMatrix(true);
  30126. var bbox = mesh.getBoundingInfo().boundingBox;
  30127. // The delta between the mesh position and the mesh bounding box center
  30128. var deltaPosition = mesh.position.subtract(bbox.center);
  30129. //calculate rotation to fit Oimo's needs (Euler...)
  30130. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30131. //get the correct bounding box
  30132. var oldQuaternion = mesh.rotationQuaternion;
  30133. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30134. mesh.computeWorldMatrix(true);
  30135. var bodyConfig = {
  30136. name: mesh.uniqueId,
  30137. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30138. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30139. move: options.mass != 0,
  30140. config: [options.mass, options.friction, options.restitution],
  30141. world: this._world
  30142. };
  30143. // register mesh
  30144. switch (impostor) {
  30145. case BABYLON.PhysicsEngine.SphereImpostor:
  30146. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30147. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30148. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30149. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30150. bodyConfig.type = 'sphere';
  30151. bodyConfig.size = [size];
  30152. break;
  30153. case BABYLON.PhysicsEngine.PlaneImpostor:
  30154. //Oimo "fakes" a cylinder as a box, so why don't we!
  30155. case BABYLON.PhysicsEngine.CylinderImpostor:
  30156. case BABYLON.PhysicsEngine.BoxImpostor:
  30157. var min = bbox.minimumWorld;
  30158. var max = bbox.maximumWorld;
  30159. var box = max.subtract(min);
  30160. var sizeX = this._checkWithEpsilon(box.x);
  30161. var sizeY = this._checkWithEpsilon(box.y);
  30162. var sizeZ = this._checkWithEpsilon(box.z);
  30163. bodyConfig.type = 'box';
  30164. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30165. break;
  30166. }
  30167. var body = new OIMO.Body(bodyConfig);
  30168. //We have to access the rigid body's properties to set the quaternion.
  30169. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30170. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30171. //TEST
  30172. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30173. //update the internal rotation matrix
  30174. //body.body.syncShapes();
  30175. this._registeredMeshes.push({
  30176. mesh: mesh,
  30177. body: body,
  30178. delta: deltaPosition
  30179. });
  30180. //for the sake of consistency.
  30181. mesh.rotationQuaternion = oldQuaternion;
  30182. return body;
  30183. };
  30184. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30185. var types = [], sizes = [], positions = [], rotations = [];
  30186. var initialMesh = parts[0].mesh;
  30187. for (var index = 0; index < parts.length; index++) {
  30188. var part = parts[index];
  30189. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30190. types.push(bodyParameters.type);
  30191. sizes.push.apply(sizes, bodyParameters.size);
  30192. positions.push.apply(positions, bodyParameters.pos);
  30193. rotations.push.apply(rotations, bodyParameters.rot);
  30194. }
  30195. var body = new OIMO.Body({
  30196. name: initialMesh.uniqueId,
  30197. type: types,
  30198. size: sizes,
  30199. pos: positions,
  30200. rot: rotations,
  30201. move: options.mass != 0,
  30202. config: [options.mass, options.friction, options.restitution],
  30203. world: this._world
  30204. });
  30205. //Reset the body's rotation to be of the initial mesh's.
  30206. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30207. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30208. this._registeredMeshes.push({
  30209. mesh: initialMesh,
  30210. body: body
  30211. });
  30212. return body;
  30213. };
  30214. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30215. var mesh = part.mesh;
  30216. if (!mesh.rotationQuaternion) {
  30217. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30218. }
  30219. // We need the bounding box/sphere info to compute the physics body
  30220. mesh.computeWorldMatrix(true);
  30221. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30222. var bodyParameters = {
  30223. name: mesh.uniqueId,
  30224. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30225. //A bug in Oimo (Body class) prevents us from using rot directly.
  30226. rot: [0, 0, 0],
  30227. //For future reference, if the bug will ever be fixed.
  30228. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30229. };
  30230. var oldQuaternion = mesh.rotationQuaternion;
  30231. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30232. mesh.computeWorldMatrix(true);
  30233. switch (part.impostor) {
  30234. case BABYLON.PhysicsEngine.SphereImpostor:
  30235. var bbox = mesh.getBoundingInfo().boundingBox;
  30236. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30237. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30238. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30239. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30240. bodyParameters.type = 'sphere';
  30241. bodyParameters.size = [size, size, size];
  30242. break;
  30243. case BABYLON.PhysicsEngine.PlaneImpostor:
  30244. case BABYLON.PhysicsEngine.CylinderImpostor:
  30245. case BABYLON.PhysicsEngine.BoxImpostor:
  30246. bbox = mesh.getBoundingInfo().boundingBox;
  30247. var min = bbox.minimumWorld;
  30248. var max = bbox.maximumWorld;
  30249. var box = max.subtract(min);
  30250. var sizeX = this._checkWithEpsilon(box.x);
  30251. var sizeY = this._checkWithEpsilon(box.y);
  30252. var sizeZ = this._checkWithEpsilon(box.z);
  30253. bodyParameters.type = 'box';
  30254. bodyParameters.size = [sizeX, sizeY, sizeZ];
  30255. break;
  30256. }
  30257. mesh.rotationQuaternion = oldQuaternion;
  30258. return bodyParameters;
  30259. };
  30260. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  30261. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30262. var registeredMesh = this._registeredMeshes[index];
  30263. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30264. if (registeredMesh.body) {
  30265. this._world.removeRigidBody(registeredMesh.body.body);
  30266. this._unbindBody(registeredMesh.body);
  30267. }
  30268. this._registeredMeshes.splice(index, 1);
  30269. return;
  30270. }
  30271. }
  30272. };
  30273. OimoJSPlugin.prototype._unbindBody = function (body) {
  30274. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30275. var registeredMesh = this._registeredMeshes[index];
  30276. if (registeredMesh.body === body) {
  30277. registeredMesh.body = null;
  30278. }
  30279. }
  30280. };
  30281. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30282. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30283. var registeredMesh = this._registeredMeshes[index];
  30284. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30285. // Get object mass to have a behaviour similar to cannon.js
  30286. var mass = registeredMesh.body.body.massInfo.mass;
  30287. // The force is scaled with the mass of object
  30288. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30289. return;
  30290. }
  30291. }
  30292. };
  30293. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  30294. var body1 = null, body2 = null;
  30295. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30296. var registeredMesh = this._registeredMeshes[index];
  30297. if (registeredMesh.mesh === mesh1) {
  30298. body1 = registeredMesh.body.body;
  30299. }
  30300. else if (registeredMesh.mesh === mesh2) {
  30301. body2 = registeredMesh.body.body;
  30302. }
  30303. }
  30304. if (!body1 || !body2) {
  30305. return false;
  30306. }
  30307. if (!options) {
  30308. options = {};
  30309. }
  30310. new OIMO.Link({
  30311. type: options.type,
  30312. body1: body1,
  30313. body2: body2,
  30314. min: options.min,
  30315. max: options.max,
  30316. axe1: options.axe1,
  30317. axe2: options.axe2,
  30318. pos1: [pivot1.x, pivot1.y, pivot1.z],
  30319. pos2: [pivot2.x, pivot2.y, pivot2.z],
  30320. collision: options.collision,
  30321. spring: options.spring,
  30322. world: this._world
  30323. });
  30324. return true;
  30325. };
  30326. OimoJSPlugin.prototype.dispose = function () {
  30327. this._world.clear();
  30328. while (this._registeredMeshes.length) {
  30329. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30330. }
  30331. };
  30332. OimoJSPlugin.prototype.isSupported = function () {
  30333. return OIMO !== undefined;
  30334. };
  30335. OimoJSPlugin.prototype.getWorldObject = function () {
  30336. return this._world;
  30337. };
  30338. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30339. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30340. var registeredMesh = this._registeredMeshes[index];
  30341. if (registeredMesh.mesh === mesh) {
  30342. return registeredMesh.body;
  30343. }
  30344. }
  30345. return null;
  30346. };
  30347. OimoJSPlugin.prototype._getLastShape = function (body) {
  30348. var lastShape = body.shapes;
  30349. while (lastShape.next) {
  30350. lastShape = lastShape.next;
  30351. }
  30352. return lastShape;
  30353. };
  30354. OimoJSPlugin.prototype.runOneStep = function (time) {
  30355. this._world.step();
  30356. // Update the position of all registered meshes
  30357. var i = this._registeredMeshes.length;
  30358. var m;
  30359. while (i--) {
  30360. var body = this._registeredMeshes[i].body.body;
  30361. var mesh = this._registeredMeshes[i].mesh;
  30362. if (!this._registeredMeshes[i].delta) {
  30363. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  30364. }
  30365. if (!body.sleeping) {
  30366. //TODO check that
  30367. if (body.shapes.next) {
  30368. var parentShape = this._getLastShape(body);
  30369. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  30370. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  30371. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  30372. }
  30373. else {
  30374. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  30375. }
  30376. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  30377. mesh.computeWorldMatrix();
  30378. }
  30379. //check if the collide callback is set.
  30380. if (mesh.onPhysicsCollide) {
  30381. var meshUniqueName = mesh.uniqueId;
  30382. var contact = this._world.contacts;
  30383. while (contact !== null) {
  30384. //is this body colliding with any other?
  30385. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30386. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  30387. //get the mesh and execute the callback
  30388. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  30389. if (otherMesh)
  30390. mesh.onPhysicsCollide(otherMesh, contact);
  30391. }
  30392. contact = contact.next;
  30393. }
  30394. }
  30395. }
  30396. };
  30397. return OimoJSPlugin;
  30398. })();
  30399. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30400. })(BABYLON || (BABYLON = {}));
  30401. var BABYLON;
  30402. (function (BABYLON) {
  30403. var DisplayPassPostProcess = (function (_super) {
  30404. __extends(DisplayPassPostProcess, _super);
  30405. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30406. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30407. }
  30408. return DisplayPassPostProcess;
  30409. })(BABYLON.PostProcess);
  30410. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30411. })(BABYLON || (BABYLON = {}));
  30412. var BABYLON;
  30413. (function (BABYLON) {
  30414. var SimplificationSettings = (function () {
  30415. function SimplificationSettings(quality, distance, optimizeMesh) {
  30416. this.quality = quality;
  30417. this.distance = distance;
  30418. this.optimizeMesh = optimizeMesh;
  30419. }
  30420. return SimplificationSettings;
  30421. })();
  30422. BABYLON.SimplificationSettings = SimplificationSettings;
  30423. var SimplificationQueue = (function () {
  30424. function SimplificationQueue() {
  30425. this.running = false;
  30426. this._simplificationArray = [];
  30427. }
  30428. SimplificationQueue.prototype.addTask = function (task) {
  30429. this._simplificationArray.push(task);
  30430. };
  30431. SimplificationQueue.prototype.executeNext = function () {
  30432. var task = this._simplificationArray.pop();
  30433. if (task) {
  30434. this.running = true;
  30435. this.runSimplification(task);
  30436. }
  30437. else {
  30438. this.running = false;
  30439. }
  30440. };
  30441. SimplificationQueue.prototype.runSimplification = function (task) {
  30442. var _this = this;
  30443. if (task.parallelProcessing) {
  30444. //parallel simplifier
  30445. task.settings.forEach(function (setting) {
  30446. var simplifier = _this.getSimplifier(task);
  30447. simplifier.simplify(setting, function (newMesh) {
  30448. task.mesh.addLODLevel(setting.distance, newMesh);
  30449. newMesh.isVisible = true;
  30450. //check if it is the last
  30451. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30452. //all done, run the success callback.
  30453. task.successCallback();
  30454. }
  30455. _this.executeNext();
  30456. });
  30457. });
  30458. }
  30459. else {
  30460. //single simplifier.
  30461. var simplifier = this.getSimplifier(task);
  30462. var runDecimation = function (setting, callback) {
  30463. simplifier.simplify(setting, function (newMesh) {
  30464. task.mesh.addLODLevel(setting.distance, newMesh);
  30465. newMesh.isVisible = true;
  30466. //run the next quality level
  30467. callback();
  30468. });
  30469. };
  30470. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30471. runDecimation(task.settings[loop.index], function () {
  30472. loop.executeNext();
  30473. });
  30474. }, function () {
  30475. //execution ended, run the success callback.
  30476. if (task.successCallback) {
  30477. task.successCallback();
  30478. }
  30479. _this.executeNext();
  30480. });
  30481. }
  30482. };
  30483. SimplificationQueue.prototype.getSimplifier = function (task) {
  30484. switch (task.simplificationType) {
  30485. case SimplificationType.QUADRATIC:
  30486. default:
  30487. return new QuadraticErrorSimplification(task.mesh);
  30488. }
  30489. };
  30490. return SimplificationQueue;
  30491. })();
  30492. BABYLON.SimplificationQueue = SimplificationQueue;
  30493. /**
  30494. * The implemented types of simplification.
  30495. * At the moment only Quadratic Error Decimation is implemented.
  30496. */
  30497. (function (SimplificationType) {
  30498. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30499. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30500. var SimplificationType = BABYLON.SimplificationType;
  30501. var DecimationTriangle = (function () {
  30502. function DecimationTriangle(vertices) {
  30503. this.vertices = vertices;
  30504. this.error = new Array(4);
  30505. this.deleted = false;
  30506. this.isDirty = false;
  30507. this.deletePending = false;
  30508. this.borderFactor = 0;
  30509. }
  30510. return DecimationTriangle;
  30511. })();
  30512. BABYLON.DecimationTriangle = DecimationTriangle;
  30513. var DecimationVertex = (function () {
  30514. function DecimationVertex(position, id) {
  30515. this.position = position;
  30516. this.id = id;
  30517. this.isBorder = true;
  30518. this.q = new QuadraticMatrix();
  30519. this.triangleCount = 0;
  30520. this.triangleStart = 0;
  30521. this.originalOffsets = [];
  30522. }
  30523. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30524. this.position.copyFrom(newPosition);
  30525. };
  30526. return DecimationVertex;
  30527. })();
  30528. BABYLON.DecimationVertex = DecimationVertex;
  30529. var QuadraticMatrix = (function () {
  30530. function QuadraticMatrix(data) {
  30531. this.data = new Array(10);
  30532. for (var i = 0; i < 10; ++i) {
  30533. if (data && data[i]) {
  30534. this.data[i] = data[i];
  30535. }
  30536. else {
  30537. this.data[i] = 0;
  30538. }
  30539. }
  30540. }
  30541. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30542. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30543. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30544. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30545. return det;
  30546. };
  30547. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30548. for (var i = 0; i < 10; ++i) {
  30549. this.data[i] += matrix.data[i];
  30550. }
  30551. };
  30552. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30553. for (var i = 0; i < 10; ++i) {
  30554. this.data[i] += data[i];
  30555. }
  30556. };
  30557. QuadraticMatrix.prototype.add = function (matrix) {
  30558. var m = new QuadraticMatrix();
  30559. for (var i = 0; i < 10; ++i) {
  30560. m.data[i] = this.data[i] + matrix.data[i];
  30561. }
  30562. return m;
  30563. };
  30564. QuadraticMatrix.FromData = function (a, b, c, d) {
  30565. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30566. };
  30567. //returning an array to avoid garbage collection
  30568. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30569. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30570. };
  30571. return QuadraticMatrix;
  30572. })();
  30573. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30574. var Reference = (function () {
  30575. function Reference(vertexId, triangleId) {
  30576. this.vertexId = vertexId;
  30577. this.triangleId = triangleId;
  30578. }
  30579. return Reference;
  30580. })();
  30581. BABYLON.Reference = Reference;
  30582. /**
  30583. * An implementation of the Quadratic Error simplification algorithm.
  30584. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30585. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30586. * @author RaananW
  30587. */
  30588. var QuadraticErrorSimplification = (function () {
  30589. function QuadraticErrorSimplification(_mesh) {
  30590. this._mesh = _mesh;
  30591. this.initialized = false;
  30592. this.syncIterations = 5000;
  30593. this.aggressiveness = 7;
  30594. this.decimationIterations = 100;
  30595. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30596. }
  30597. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30598. var _this = this;
  30599. this.initDecimatedMesh();
  30600. //iterating through the submeshes array, one after the other.
  30601. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30602. _this.initWithMesh(loop.index, function () {
  30603. _this.runDecimation(settings, loop.index, function () {
  30604. loop.executeNext();
  30605. });
  30606. }, settings.optimizeMesh);
  30607. }, function () {
  30608. setTimeout(function () {
  30609. successCallback(_this._reconstructedMesh);
  30610. }, 0);
  30611. });
  30612. };
  30613. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30614. var _this = this;
  30615. var gCount = 0;
  30616. triangle.vertices.forEach(function (vertex) {
  30617. var count = 0;
  30618. var vPos = vertex.position;
  30619. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30620. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30621. ++count;
  30622. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30623. ++count;
  30624. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30625. ++count;
  30626. if (count > 1) {
  30627. ++gCount;
  30628. }
  30629. ;
  30630. });
  30631. if (gCount > 1) {
  30632. console.log(triangle, gCount);
  30633. }
  30634. return gCount > 1;
  30635. };
  30636. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30637. var _this = this;
  30638. var targetCount = ~~(this.triangles.length * settings.quality);
  30639. var deletedTriangles = 0;
  30640. var triangleCount = this.triangles.length;
  30641. var iterationFunction = function (iteration, callback) {
  30642. setTimeout(function () {
  30643. if (iteration % 5 === 0) {
  30644. _this.updateMesh(iteration === 0);
  30645. }
  30646. for (var i = 0; i < _this.triangles.length; ++i) {
  30647. _this.triangles[i].isDirty = false;
  30648. }
  30649. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30650. var trianglesIterator = function (i) {
  30651. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30652. var t = _this.triangles[tIdx];
  30653. if (!t)
  30654. return;
  30655. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30656. return;
  30657. }
  30658. for (var j = 0; j < 3; ++j) {
  30659. if (t.error[j] < threshold) {
  30660. var deleted0 = [];
  30661. var deleted1 = [];
  30662. var v0 = t.vertices[j];
  30663. var v1 = t.vertices[(j + 1) % 3];
  30664. if (v0.isBorder !== v1.isBorder)
  30665. continue;
  30666. var p = BABYLON.Vector3.Zero();
  30667. var n = BABYLON.Vector3.Zero();
  30668. var uv = BABYLON.Vector2.Zero();
  30669. var color = new BABYLON.Color4(0, 0, 0, 1);
  30670. _this.calculateError(v0, v1, p, n, uv, color);
  30671. var delTr = [];
  30672. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30673. continue;
  30674. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30675. continue;
  30676. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30677. continue;
  30678. var uniqueArray = [];
  30679. delTr.forEach(function (deletedT) {
  30680. if (uniqueArray.indexOf(deletedT) === -1) {
  30681. deletedT.deletePending = true;
  30682. uniqueArray.push(deletedT);
  30683. }
  30684. });
  30685. if (uniqueArray.length % 2 !== 0) {
  30686. continue;
  30687. }
  30688. v0.q = v1.q.add(v0.q);
  30689. v0.updatePosition(p);
  30690. var tStart = _this.references.length;
  30691. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30692. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30693. var tCount = _this.references.length - tStart;
  30694. if (tCount <= v0.triangleCount) {
  30695. if (tCount) {
  30696. for (var c = 0; c < tCount; c++) {
  30697. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30698. }
  30699. }
  30700. }
  30701. else {
  30702. v0.triangleStart = tStart;
  30703. }
  30704. v0.triangleCount = tCount;
  30705. break;
  30706. }
  30707. }
  30708. };
  30709. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30710. }, 0);
  30711. };
  30712. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30713. if (triangleCount - deletedTriangles <= targetCount)
  30714. loop.breakLoop();
  30715. else {
  30716. iterationFunction(loop.index, function () {
  30717. loop.executeNext();
  30718. });
  30719. }
  30720. }, function () {
  30721. setTimeout(function () {
  30722. //reconstruct this part of the mesh
  30723. _this.reconstructMesh(submeshIndex);
  30724. successCallback();
  30725. }, 0);
  30726. });
  30727. };
  30728. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30729. var _this = this;
  30730. this.vertices = [];
  30731. this.triangles = [];
  30732. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30733. var indices = this._mesh.getIndices();
  30734. var submesh = this._mesh.subMeshes[submeshIndex];
  30735. var findInVertices = function (positionToSearch) {
  30736. if (optimizeMesh) {
  30737. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30738. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30739. return _this.vertices[ii];
  30740. }
  30741. }
  30742. }
  30743. return null;
  30744. };
  30745. var vertexReferences = [];
  30746. var vertexInit = function (i) {
  30747. var offset = i + submesh.verticesStart;
  30748. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30749. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30750. vertex.originalOffsets.push(offset);
  30751. if (vertex.id === _this.vertices.length) {
  30752. _this.vertices.push(vertex);
  30753. }
  30754. vertexReferences.push(vertex.id);
  30755. };
  30756. //var totalVertices = mesh.getTotalVertices();
  30757. var totalVertices = submesh.verticesCount;
  30758. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30759. var indicesInit = function (i) {
  30760. var offset = (submesh.indexStart / 3) + i;
  30761. var pos = (offset * 3);
  30762. var i0 = indices[pos + 0];
  30763. var i1 = indices[pos + 1];
  30764. var i2 = indices[pos + 2];
  30765. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30766. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30767. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30768. var triangle = new DecimationTriangle([v0, v1, v2]);
  30769. triangle.originalOffset = pos;
  30770. _this.triangles.push(triangle);
  30771. };
  30772. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30773. _this.init(callback);
  30774. });
  30775. });
  30776. };
  30777. QuadraticErrorSimplification.prototype.init = function (callback) {
  30778. var _this = this;
  30779. var triangleInit1 = function (i) {
  30780. var t = _this.triangles[i];
  30781. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30782. for (var j = 0; j < 3; j++) {
  30783. 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))));
  30784. }
  30785. };
  30786. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30787. var triangleInit2 = function (i) {
  30788. var t = _this.triangles[i];
  30789. for (var j = 0; j < 3; ++j) {
  30790. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30791. }
  30792. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30793. };
  30794. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30795. _this.initialized = true;
  30796. callback();
  30797. });
  30798. });
  30799. };
  30800. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30801. var newTriangles = [];
  30802. var i;
  30803. for (i = 0; i < this.vertices.length; ++i) {
  30804. this.vertices[i].triangleCount = 0;
  30805. }
  30806. var t;
  30807. var j;
  30808. for (i = 0; i < this.triangles.length; ++i) {
  30809. if (!this.triangles[i].deleted) {
  30810. t = this.triangles[i];
  30811. for (j = 0; j < 3; ++j) {
  30812. t.vertices[j].triangleCount = 1;
  30813. }
  30814. newTriangles.push(t);
  30815. }
  30816. }
  30817. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30818. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30819. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30820. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30821. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30822. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30823. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30824. var vertexCount = 0;
  30825. for (i = 0; i < this.vertices.length; ++i) {
  30826. var vertex = this.vertices[i];
  30827. vertex.id = vertexCount;
  30828. if (vertex.triangleCount) {
  30829. vertex.originalOffsets.forEach(function (originalOffset) {
  30830. newPositionData.push(vertex.position.x);
  30831. newPositionData.push(vertex.position.y);
  30832. newPositionData.push(vertex.position.z);
  30833. newNormalData.push(normalData[originalOffset * 3]);
  30834. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30835. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30836. if (uvs && uvs.length) {
  30837. newUVsData.push(uvs[(originalOffset * 2)]);
  30838. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30839. }
  30840. else if (colorsData && colorsData.length) {
  30841. newColorsData.push(colorsData[(originalOffset * 4)]);
  30842. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30843. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30844. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30845. }
  30846. ++vertexCount;
  30847. });
  30848. }
  30849. }
  30850. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30851. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30852. var submeshesArray = this._reconstructedMesh.subMeshes;
  30853. this._reconstructedMesh.subMeshes = [];
  30854. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30855. var originalIndices = this._mesh.getIndices();
  30856. for (i = 0; i < newTriangles.length; ++i) {
  30857. t = newTriangles[i]; //now get the new referencing point for each vertex
  30858. [0, 1, 2].forEach(function (idx) {
  30859. var id = originalIndices[t.originalOffset + idx];
  30860. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30861. if (offset < 0)
  30862. offset = 0;
  30863. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30864. });
  30865. }
  30866. //overwriting the old vertex buffers and indices.
  30867. this._reconstructedMesh.setIndices(newIndicesArray);
  30868. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30869. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30870. if (newUVsData.length > 0)
  30871. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30872. if (newColorsData.length > 0)
  30873. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30874. //create submesh
  30875. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30876. if (submeshIndex > 0) {
  30877. this._reconstructedMesh.subMeshes = [];
  30878. submeshesArray.forEach(function (submesh) {
  30879. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30880. });
  30881. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30882. }
  30883. };
  30884. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30885. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30886. this._reconstructedMesh.material = this._mesh.material;
  30887. this._reconstructedMesh.parent = this._mesh.parent;
  30888. this._reconstructedMesh.isVisible = false;
  30889. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30890. };
  30891. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30892. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30893. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30894. if (t.deleted)
  30895. continue;
  30896. var s = this.references[vertex1.triangleStart + i].vertexId;
  30897. var v1 = t.vertices[(s + 1) % 3];
  30898. var v2 = t.vertices[(s + 2) % 3];
  30899. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30900. deletedArray[i] = true;
  30901. delTr.push(t);
  30902. continue;
  30903. }
  30904. var d1 = v1.position.subtract(point);
  30905. d1 = d1.normalize();
  30906. var d2 = v2.position.subtract(point);
  30907. d2 = d2.normalize();
  30908. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30909. return true;
  30910. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30911. deletedArray[i] = false;
  30912. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30913. return true;
  30914. }
  30915. return false;
  30916. };
  30917. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30918. var newDeleted = deletedTriangles;
  30919. for (var i = 0; i < vertex.triangleCount; ++i) {
  30920. var ref = this.references[vertex.triangleStart + i];
  30921. var t = this.triangles[ref.triangleId];
  30922. if (t.deleted)
  30923. continue;
  30924. if (deletedArray[i] && t.deletePending) {
  30925. t.deleted = true;
  30926. newDeleted++;
  30927. continue;
  30928. }
  30929. t.vertices[ref.vertexId] = origVertex;
  30930. t.isDirty = true;
  30931. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30932. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30933. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30934. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30935. this.references.push(ref);
  30936. }
  30937. return newDeleted;
  30938. };
  30939. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30940. for (var i = 0; i < this.vertices.length; ++i) {
  30941. var vCount = [];
  30942. var vId = [];
  30943. var v = this.vertices[i];
  30944. var j;
  30945. for (j = 0; j < v.triangleCount; ++j) {
  30946. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30947. for (var ii = 0; ii < 3; ii++) {
  30948. var ofs = 0;
  30949. var vv = triangle.vertices[ii];
  30950. while (ofs < vCount.length) {
  30951. if (vId[ofs] === vv.id)
  30952. break;
  30953. ++ofs;
  30954. }
  30955. if (ofs === vCount.length) {
  30956. vCount.push(1);
  30957. vId.push(vv.id);
  30958. }
  30959. else {
  30960. vCount[ofs]++;
  30961. }
  30962. }
  30963. }
  30964. for (j = 0; j < vCount.length; ++j) {
  30965. if (vCount[j] === 1) {
  30966. this.vertices[vId[j]].isBorder = true;
  30967. }
  30968. else {
  30969. this.vertices[vId[j]].isBorder = false;
  30970. }
  30971. }
  30972. }
  30973. };
  30974. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30975. if (identifyBorders === void 0) { identifyBorders = false; }
  30976. var i;
  30977. if (!identifyBorders) {
  30978. var newTrianglesVector = [];
  30979. for (i = 0; i < this.triangles.length; ++i) {
  30980. if (!this.triangles[i].deleted) {
  30981. newTrianglesVector.push(this.triangles[i]);
  30982. }
  30983. }
  30984. this.triangles = newTrianglesVector;
  30985. }
  30986. for (i = 0; i < this.vertices.length; ++i) {
  30987. this.vertices[i].triangleCount = 0;
  30988. this.vertices[i].triangleStart = 0;
  30989. }
  30990. var t;
  30991. var j;
  30992. var v;
  30993. for (i = 0; i < this.triangles.length; ++i) {
  30994. t = this.triangles[i];
  30995. for (j = 0; j < 3; ++j) {
  30996. v = t.vertices[j];
  30997. v.triangleCount++;
  30998. }
  30999. }
  31000. var tStart = 0;
  31001. for (i = 0; i < this.vertices.length; ++i) {
  31002. this.vertices[i].triangleStart = tStart;
  31003. tStart += this.vertices[i].triangleCount;
  31004. this.vertices[i].triangleCount = 0;
  31005. }
  31006. var newReferences = new Array(this.triangles.length * 3);
  31007. for (i = 0; i < this.triangles.length; ++i) {
  31008. t = this.triangles[i];
  31009. for (j = 0; j < 3; ++j) {
  31010. v = t.vertices[j];
  31011. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31012. v.triangleCount++;
  31013. }
  31014. }
  31015. this.references = newReferences;
  31016. if (identifyBorders) {
  31017. this.identifyBorder();
  31018. }
  31019. };
  31020. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31021. var x = point.x;
  31022. var y = point.y;
  31023. var z = point.z;
  31024. 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
  31025. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31026. };
  31027. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31028. var q = vertex1.q.add(vertex2.q);
  31029. var border = vertex1.isBorder && vertex2.isBorder;
  31030. var error = 0;
  31031. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31032. if (qDet !== 0 && !border) {
  31033. if (!pointResult) {
  31034. pointResult = BABYLON.Vector3.Zero();
  31035. }
  31036. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31037. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31038. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31039. error = this.vertexError(q, pointResult);
  31040. }
  31041. else {
  31042. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31043. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31044. var error1 = this.vertexError(q, vertex1.position);
  31045. var error2 = this.vertexError(q, vertex2.position);
  31046. var error3 = this.vertexError(q, p3);
  31047. error = Math.min(error1, error2, error3);
  31048. if (error === error1) {
  31049. if (pointResult) {
  31050. pointResult.copyFrom(vertex1.position);
  31051. }
  31052. }
  31053. else if (error === error2) {
  31054. if (pointResult) {
  31055. pointResult.copyFrom(vertex2.position);
  31056. }
  31057. }
  31058. else {
  31059. if (pointResult) {
  31060. pointResult.copyFrom(p3);
  31061. }
  31062. }
  31063. }
  31064. return error;
  31065. };
  31066. return QuadraticErrorSimplification;
  31067. })();
  31068. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31069. })(BABYLON || (BABYLON = {}));
  31070. var BABYLON;
  31071. (function (BABYLON) {
  31072. var serializedGeometries = [];
  31073. var serializeGeometry = function (geometry, serializationGeometries) {
  31074. if (serializedGeometries[geometry.id]) {
  31075. return;
  31076. }
  31077. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31078. serializationGeometries.boxes.push(geometry.serialize());
  31079. }
  31080. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31081. serializationGeometries.spheres.push(geometry.serialize());
  31082. }
  31083. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31084. serializationGeometries.cylinders.push(geometry.serialize());
  31085. }
  31086. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31087. serializationGeometries.toruses.push(geometry.serialize());
  31088. }
  31089. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31090. serializationGeometries.grounds.push(geometry.serialize());
  31091. }
  31092. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31093. serializationGeometries.planes.push(geometry.serialize());
  31094. }
  31095. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31096. serializationGeometries.torusKnots.push(geometry.serialize());
  31097. }
  31098. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31099. throw new Error("Unknown primitive type");
  31100. }
  31101. else {
  31102. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31103. }
  31104. serializedGeometries[geometry.id] = true;
  31105. };
  31106. var serializeMesh = function (mesh, serializationScene) {
  31107. var serializationObject = {};
  31108. serializationObject.name = mesh.name;
  31109. serializationObject.id = mesh.id;
  31110. if (BABYLON.Tags.HasTags(mesh)) {
  31111. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31112. }
  31113. serializationObject.position = mesh.position.asArray();
  31114. if (mesh.rotationQuaternion) {
  31115. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31116. }
  31117. else if (mesh.rotation) {
  31118. serializationObject.rotation = mesh.rotation.asArray();
  31119. }
  31120. serializationObject.scaling = mesh.scaling.asArray();
  31121. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31122. serializationObject.isEnabled = mesh.isEnabled();
  31123. serializationObject.isVisible = mesh.isVisible;
  31124. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31125. serializationObject.pickable = mesh.isPickable;
  31126. serializationObject.receiveShadows = mesh.receiveShadows;
  31127. serializationObject.billboardMode = mesh.billboardMode;
  31128. serializationObject.visibility = mesh.visibility;
  31129. serializationObject.checkCollisions = mesh.checkCollisions;
  31130. // Parent
  31131. if (mesh.parent) {
  31132. serializationObject.parentId = mesh.parent.id;
  31133. }
  31134. // Geometry
  31135. var geometry = mesh._geometry;
  31136. if (geometry) {
  31137. var geometryId = geometry.id;
  31138. serializationObject.geometryId = geometryId;
  31139. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31140. // 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
  31141. serializeGeometry(geometry, serializationScene.geometries);
  31142. }
  31143. // SubMeshes
  31144. serializationObject.subMeshes = [];
  31145. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31146. var subMesh = mesh.subMeshes[subIndex];
  31147. serializationObject.subMeshes.push({
  31148. materialIndex: subMesh.materialIndex,
  31149. verticesStart: subMesh.verticesStart,
  31150. verticesCount: subMesh.verticesCount,
  31151. indexStart: subMesh.indexStart,
  31152. indexCount: subMesh.indexCount
  31153. });
  31154. }
  31155. }
  31156. // Material
  31157. if (mesh.material) {
  31158. serializationObject.materialId = mesh.material.id;
  31159. }
  31160. else {
  31161. mesh.material = null;
  31162. }
  31163. // Skeleton
  31164. if (mesh.skeleton) {
  31165. serializationObject.skeletonId = mesh.skeleton.id;
  31166. }
  31167. // Physics
  31168. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31169. serializationObject.physicsMass = mesh.getPhysicsMass();
  31170. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31171. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31172. switch (mesh.getPhysicsImpostor()) {
  31173. case BABYLON.PhysicsEngine.BoxImpostor:
  31174. serializationObject.physicsImpostor = 1;
  31175. break;
  31176. case BABYLON.PhysicsEngine.SphereImpostor:
  31177. serializationObject.physicsImpostor = 2;
  31178. break;
  31179. }
  31180. }
  31181. // Instances
  31182. serializationObject.instances = [];
  31183. for (var index = 0; index < mesh.instances.length; index++) {
  31184. var instance = mesh.instances[index];
  31185. var serializationInstance = {
  31186. name: instance.name,
  31187. position: instance.position.asArray(),
  31188. scaling: instance.scaling.asArray()
  31189. };
  31190. if (instance.rotationQuaternion) {
  31191. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31192. }
  31193. else if (instance.rotation) {
  31194. serializationInstance.rotation = instance.rotation.asArray();
  31195. }
  31196. serializationObject.instances.push(serializationInstance);
  31197. // Animations
  31198. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31199. serializationInstance.ranges = instance.serializeAnimationRanges();
  31200. }
  31201. // Animations
  31202. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31203. serializationObject.ranges = mesh.serializeAnimationRanges();
  31204. // Layer mask
  31205. serializationObject.layerMask = mesh.layerMask;
  31206. return serializationObject;
  31207. };
  31208. var finalizeSingleMesh = function (mesh, serializationObject) {
  31209. //only works if the mesh is already loaded
  31210. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31211. //serialize material
  31212. if (mesh.material) {
  31213. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31214. serializationObject.materials = serializationObject.materials || [];
  31215. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31216. serializationObject.materials.push(mesh.material.serialize());
  31217. }
  31218. }
  31219. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31220. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31221. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31222. serializationObject.multiMaterials.push(mesh.material.serialize());
  31223. }
  31224. }
  31225. }
  31226. //serialize geometry
  31227. var geometry = mesh._geometry;
  31228. if (geometry) {
  31229. if (!serializationObject.geometries) {
  31230. serializationObject.geometries = {};
  31231. serializationObject.geometries.boxes = [];
  31232. serializationObject.geometries.spheres = [];
  31233. serializationObject.geometries.cylinders = [];
  31234. serializationObject.geometries.toruses = [];
  31235. serializationObject.geometries.grounds = [];
  31236. serializationObject.geometries.planes = [];
  31237. serializationObject.geometries.torusKnots = [];
  31238. serializationObject.geometries.vertexData = [];
  31239. }
  31240. serializeGeometry(geometry, serializationObject.geometries);
  31241. }
  31242. // Skeletons
  31243. if (mesh.skeleton) {
  31244. serializationObject.skeletons = serializationObject.skeletons || [];
  31245. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31246. }
  31247. //serialize the actual mesh
  31248. serializationObject.meshes = serializationObject.meshes || [];
  31249. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31250. }
  31251. };
  31252. var SceneSerializer = (function () {
  31253. function SceneSerializer() {
  31254. }
  31255. SceneSerializer.Serialize = function (scene) {
  31256. var serializationObject = {};
  31257. // Scene
  31258. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  31259. serializationObject.autoClear = scene.autoClear;
  31260. serializationObject.clearColor = scene.clearColor.asArray();
  31261. serializationObject.ambientColor = scene.ambientColor.asArray();
  31262. serializationObject.gravity = scene.gravity.asArray();
  31263. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  31264. serializationObject.workerCollisions = scene.workerCollisions;
  31265. // Fog
  31266. if (scene.fogMode && scene.fogMode !== 0) {
  31267. serializationObject.fogMode = scene.fogMode;
  31268. serializationObject.fogColor = scene.fogColor.asArray();
  31269. serializationObject.fogStart = scene.fogStart;
  31270. serializationObject.fogEnd = scene.fogEnd;
  31271. serializationObject.fogDensity = scene.fogDensity;
  31272. }
  31273. //Physics
  31274. if (scene.isPhysicsEnabled()) {
  31275. serializationObject.physicsEnabled = true;
  31276. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  31277. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  31278. }
  31279. // Lights
  31280. serializationObject.lights = [];
  31281. var index;
  31282. var light;
  31283. for (index = 0; index < scene.lights.length; index++) {
  31284. light = scene.lights[index];
  31285. serializationObject.lights.push(light.serialize());
  31286. }
  31287. // Cameras
  31288. serializationObject.cameras = [];
  31289. for (index = 0; index < scene.cameras.length; index++) {
  31290. var camera = scene.cameras[index];
  31291. serializationObject.cameras.push(camera.serialize());
  31292. }
  31293. if (scene.activeCamera) {
  31294. serializationObject.activeCameraID = scene.activeCamera.id;
  31295. }
  31296. // Materials
  31297. serializationObject.materials = [];
  31298. serializationObject.multiMaterials = [];
  31299. var material;
  31300. for (index = 0; index < scene.materials.length; index++) {
  31301. material = scene.materials[index];
  31302. serializationObject.materials.push(material.serialize());
  31303. }
  31304. // MultiMaterials
  31305. serializationObject.multiMaterials = [];
  31306. for (index = 0; index < scene.multiMaterials.length; index++) {
  31307. var multiMaterial = scene.multiMaterials[index];
  31308. serializationObject.multiMaterials.push(multiMaterial.serialize());
  31309. }
  31310. // Skeletons
  31311. serializationObject.skeletons = [];
  31312. for (index = 0; index < scene.skeletons.length; index++) {
  31313. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  31314. }
  31315. // Geometries
  31316. serializationObject.geometries = {};
  31317. serializationObject.geometries.boxes = [];
  31318. serializationObject.geometries.spheres = [];
  31319. serializationObject.geometries.cylinders = [];
  31320. serializationObject.geometries.toruses = [];
  31321. serializationObject.geometries.grounds = [];
  31322. serializationObject.geometries.planes = [];
  31323. serializationObject.geometries.torusKnots = [];
  31324. serializationObject.geometries.vertexData = [];
  31325. serializedGeometries = [];
  31326. var geometries = scene.getGeometries();
  31327. for (index = 0; index < geometries.length; index++) {
  31328. var geometry = geometries[index];
  31329. if (geometry.isReady()) {
  31330. serializeGeometry(geometry, serializationObject.geometries);
  31331. }
  31332. }
  31333. // Meshes
  31334. serializationObject.meshes = [];
  31335. for (index = 0; index < scene.meshes.length; index++) {
  31336. var abstractMesh = scene.meshes[index];
  31337. if (abstractMesh instanceof BABYLON.Mesh) {
  31338. var mesh = abstractMesh;
  31339. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31340. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31341. }
  31342. }
  31343. }
  31344. // Particles Systems
  31345. serializationObject.particleSystems = [];
  31346. for (index = 0; index < scene.particleSystems.length; index++) {
  31347. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  31348. }
  31349. // Lens flares
  31350. serializationObject.lensFlareSystems = [];
  31351. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  31352. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  31353. }
  31354. // Shadows
  31355. serializationObject.shadowGenerators = [];
  31356. for (index = 0; index < scene.lights.length; index++) {
  31357. light = scene.lights[index];
  31358. if (light.getShadowGenerator()) {
  31359. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  31360. }
  31361. }
  31362. return serializationObject;
  31363. };
  31364. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  31365. if (withParents === void 0) { withParents = false; }
  31366. if (withChildren === void 0) { withChildren = false; }
  31367. var serializationObject = {};
  31368. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  31369. if (withParents || withChildren) {
  31370. //deliberate for loop! not for each, appended should be processed as well.
  31371. for (var i = 0; i < toSerialize.length; ++i) {
  31372. if (withChildren) {
  31373. toSerialize[i].getDescendants().forEach(function (node) {
  31374. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  31375. toSerialize.push(node);
  31376. }
  31377. });
  31378. }
  31379. //make sure the array doesn't contain the object already
  31380. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  31381. toSerialize.push(toSerialize[i].parent);
  31382. }
  31383. }
  31384. }
  31385. toSerialize.forEach(function (mesh) {
  31386. finalizeSingleMesh(mesh, serializationObject);
  31387. });
  31388. return serializationObject;
  31389. };
  31390. return SceneSerializer;
  31391. })();
  31392. BABYLON.SceneSerializer = SceneSerializer;
  31393. })(BABYLON || (BABYLON = {}));
  31394. var BABYLON;
  31395. (function (BABYLON) {
  31396. // Unique ID when we import meshes from Babylon to CSG
  31397. var currentCSGMeshId = 0;
  31398. // # class Vertex
  31399. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31400. // one to provide additional features like texture coordinates and vertex
  31401. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31402. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31403. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31404. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31405. // is not used anywhere else.
  31406. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31407. var Vertex = (function () {
  31408. function Vertex(pos, normal, uv) {
  31409. this.pos = pos;
  31410. this.normal = normal;
  31411. this.uv = uv;
  31412. }
  31413. Vertex.prototype.clone = function () {
  31414. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31415. };
  31416. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31417. // orientation of a polygon is flipped.
  31418. Vertex.prototype.flip = function () {
  31419. this.normal = this.normal.scale(-1);
  31420. };
  31421. // Create a new vertex between this vertex and `other` by linearly
  31422. // interpolating all properties using a parameter of `t`. Subclasses should
  31423. // override this to interpolate additional properties.
  31424. Vertex.prototype.interpolate = function (other, t) {
  31425. 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));
  31426. };
  31427. return Vertex;
  31428. })();
  31429. // # class Plane
  31430. // Represents a plane in 3D space.
  31431. var Plane = (function () {
  31432. function Plane(normal, w) {
  31433. this.normal = normal;
  31434. this.w = w;
  31435. }
  31436. Plane.FromPoints = function (a, b, c) {
  31437. var v0 = c.subtract(a);
  31438. var v1 = b.subtract(a);
  31439. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31440. return null;
  31441. }
  31442. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31443. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31444. };
  31445. Plane.prototype.clone = function () {
  31446. return new Plane(this.normal.clone(), this.w);
  31447. };
  31448. Plane.prototype.flip = function () {
  31449. this.normal.scaleInPlace(-1);
  31450. this.w = -this.w;
  31451. };
  31452. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31453. // fragments in the appropriate lists. Coplanar polygons go into either
  31454. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31455. // respect to this plane. Polygons in front or in back of this plane go into
  31456. // either `front` or `back`.
  31457. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31458. var COPLANAR = 0;
  31459. var FRONT = 1;
  31460. var BACK = 2;
  31461. var SPANNING = 3;
  31462. // Classify each point as well as the entire polygon into one of the above
  31463. // four classes.
  31464. var polygonType = 0;
  31465. var types = [];
  31466. var i;
  31467. var t;
  31468. for (i = 0; i < polygon.vertices.length; i++) {
  31469. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31470. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31471. polygonType |= type;
  31472. types.push(type);
  31473. }
  31474. // Put the polygon in the correct list, splitting it when necessary.
  31475. switch (polygonType) {
  31476. case COPLANAR:
  31477. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31478. break;
  31479. case FRONT:
  31480. front.push(polygon);
  31481. break;
  31482. case BACK:
  31483. back.push(polygon);
  31484. break;
  31485. case SPANNING:
  31486. var f = [], b = [];
  31487. for (i = 0; i < polygon.vertices.length; i++) {
  31488. var j = (i + 1) % polygon.vertices.length;
  31489. var ti = types[i], tj = types[j];
  31490. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31491. if (ti !== BACK)
  31492. f.push(vi);
  31493. if (ti !== FRONT)
  31494. b.push(ti !== BACK ? vi.clone() : vi);
  31495. if ((ti | tj) === SPANNING) {
  31496. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31497. var v = vi.interpolate(vj, t);
  31498. f.push(v);
  31499. b.push(v.clone());
  31500. }
  31501. }
  31502. var poly;
  31503. if (f.length >= 3) {
  31504. poly = new Polygon(f, polygon.shared);
  31505. if (poly.plane)
  31506. front.push(poly);
  31507. }
  31508. if (b.length >= 3) {
  31509. poly = new Polygon(b, polygon.shared);
  31510. if (poly.plane)
  31511. back.push(poly);
  31512. }
  31513. break;
  31514. }
  31515. };
  31516. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31517. // point is on the plane.
  31518. Plane.EPSILON = 1e-5;
  31519. return Plane;
  31520. })();
  31521. // # class Polygon
  31522. // Represents a convex polygon. The vertices used to initialize a polygon must
  31523. // be coplanar and form a convex loop.
  31524. //
  31525. // Each convex polygon has a `shared` property, which is shared between all
  31526. // polygons that are clones of each other or were split from the same polygon.
  31527. // This can be used to define per-polygon properties (such as surface color).
  31528. var Polygon = (function () {
  31529. function Polygon(vertices, shared) {
  31530. this.vertices = vertices;
  31531. this.shared = shared;
  31532. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31533. }
  31534. Polygon.prototype.clone = function () {
  31535. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31536. return new Polygon(vertices, this.shared);
  31537. };
  31538. Polygon.prototype.flip = function () {
  31539. this.vertices.reverse().map(function (v) { v.flip(); });
  31540. this.plane.flip();
  31541. };
  31542. return Polygon;
  31543. })();
  31544. // # class Node
  31545. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31546. // by picking a polygon to split along. That polygon (and all other coplanar
  31547. // polygons) are added directly to that node and the other polygons are added to
  31548. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31549. // no distinction between internal and leaf nodes.
  31550. var Node = (function () {
  31551. function Node(polygons) {
  31552. this.plane = null;
  31553. this.front = null;
  31554. this.back = null;
  31555. this.polygons = [];
  31556. if (polygons) {
  31557. this.build(polygons);
  31558. }
  31559. }
  31560. Node.prototype.clone = function () {
  31561. var node = new Node();
  31562. node.plane = this.plane && this.plane.clone();
  31563. node.front = this.front && this.front.clone();
  31564. node.back = this.back && this.back.clone();
  31565. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31566. return node;
  31567. };
  31568. // Convert solid space to empty space and empty space to solid space.
  31569. Node.prototype.invert = function () {
  31570. for (var i = 0; i < this.polygons.length; i++) {
  31571. this.polygons[i].flip();
  31572. }
  31573. if (this.plane) {
  31574. this.plane.flip();
  31575. }
  31576. if (this.front) {
  31577. this.front.invert();
  31578. }
  31579. if (this.back) {
  31580. this.back.invert();
  31581. }
  31582. var temp = this.front;
  31583. this.front = this.back;
  31584. this.back = temp;
  31585. };
  31586. // Recursively remove all polygons in `polygons` that are inside this BSP
  31587. // tree.
  31588. Node.prototype.clipPolygons = function (polygons) {
  31589. if (!this.plane)
  31590. return polygons.slice();
  31591. var front = [], back = [];
  31592. for (var i = 0; i < polygons.length; i++) {
  31593. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31594. }
  31595. if (this.front) {
  31596. front = this.front.clipPolygons(front);
  31597. }
  31598. if (this.back) {
  31599. back = this.back.clipPolygons(back);
  31600. }
  31601. else {
  31602. back = [];
  31603. }
  31604. return front.concat(back);
  31605. };
  31606. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31607. // `bsp`.
  31608. Node.prototype.clipTo = function (bsp) {
  31609. this.polygons = bsp.clipPolygons(this.polygons);
  31610. if (this.front)
  31611. this.front.clipTo(bsp);
  31612. if (this.back)
  31613. this.back.clipTo(bsp);
  31614. };
  31615. // Return a list of all polygons in this BSP tree.
  31616. Node.prototype.allPolygons = function () {
  31617. var polygons = this.polygons.slice();
  31618. if (this.front)
  31619. polygons = polygons.concat(this.front.allPolygons());
  31620. if (this.back)
  31621. polygons = polygons.concat(this.back.allPolygons());
  31622. return polygons;
  31623. };
  31624. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31625. // new polygons are filtered down to the bottom of the tree and become new
  31626. // nodes there. Each set of polygons is partitioned using the first polygon
  31627. // (no heuristic is used to pick a good split).
  31628. Node.prototype.build = function (polygons) {
  31629. if (!polygons.length)
  31630. return;
  31631. if (!this.plane)
  31632. this.plane = polygons[0].plane.clone();
  31633. var front = [], back = [];
  31634. for (var i = 0; i < polygons.length; i++) {
  31635. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31636. }
  31637. if (front.length) {
  31638. if (!this.front)
  31639. this.front = new Node();
  31640. this.front.build(front);
  31641. }
  31642. if (back.length) {
  31643. if (!this.back)
  31644. this.back = new Node();
  31645. this.back.build(back);
  31646. }
  31647. };
  31648. return Node;
  31649. })();
  31650. var CSG = (function () {
  31651. function CSG() {
  31652. this.polygons = new Array();
  31653. }
  31654. // Convert BABYLON.Mesh to BABYLON.CSG
  31655. CSG.FromMesh = function (mesh) {
  31656. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31657. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31658. if (mesh instanceof BABYLON.Mesh) {
  31659. mesh.computeWorldMatrix(true);
  31660. matrix = mesh.getWorldMatrix();
  31661. meshPosition = mesh.position.clone();
  31662. meshRotation = mesh.rotation.clone();
  31663. if (mesh.rotationQuaternion) {
  31664. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31665. }
  31666. meshScaling = mesh.scaling.clone();
  31667. }
  31668. else {
  31669. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31670. }
  31671. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31672. var subMeshes = mesh.subMeshes;
  31673. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31674. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31675. vertices = [];
  31676. for (var j = 0; j < 3; j++) {
  31677. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31678. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31679. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31680. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31681. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31682. vertex = new Vertex(position, normal, uv);
  31683. vertices.push(vertex);
  31684. }
  31685. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31686. // To handle the case of degenerated triangle
  31687. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31688. if (polygon.plane)
  31689. polygons.push(polygon);
  31690. }
  31691. }
  31692. var csg = CSG.FromPolygons(polygons);
  31693. csg.matrix = matrix;
  31694. csg.position = meshPosition;
  31695. csg.rotation = meshRotation;
  31696. csg.scaling = meshScaling;
  31697. csg.rotationQuaternion = meshRotationQuaternion;
  31698. currentCSGMeshId++;
  31699. return csg;
  31700. };
  31701. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31702. CSG.FromPolygons = function (polygons) {
  31703. var csg = new CSG();
  31704. csg.polygons = polygons;
  31705. return csg;
  31706. };
  31707. CSG.prototype.clone = function () {
  31708. var csg = new CSG();
  31709. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31710. csg.copyTransformAttributes(this);
  31711. return csg;
  31712. };
  31713. CSG.prototype.toPolygons = function () {
  31714. return this.polygons;
  31715. };
  31716. CSG.prototype.union = function (csg) {
  31717. var a = new Node(this.clone().polygons);
  31718. var b = new Node(csg.clone().polygons);
  31719. a.clipTo(b);
  31720. b.clipTo(a);
  31721. b.invert();
  31722. b.clipTo(a);
  31723. b.invert();
  31724. a.build(b.allPolygons());
  31725. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31726. };
  31727. CSG.prototype.unionInPlace = function (csg) {
  31728. var a = new Node(this.polygons);
  31729. var b = new Node(csg.polygons);
  31730. a.clipTo(b);
  31731. b.clipTo(a);
  31732. b.invert();
  31733. b.clipTo(a);
  31734. b.invert();
  31735. a.build(b.allPolygons());
  31736. this.polygons = a.allPolygons();
  31737. };
  31738. CSG.prototype.subtract = function (csg) {
  31739. var a = new Node(this.clone().polygons);
  31740. var b = new Node(csg.clone().polygons);
  31741. a.invert();
  31742. a.clipTo(b);
  31743. b.clipTo(a);
  31744. b.invert();
  31745. b.clipTo(a);
  31746. b.invert();
  31747. a.build(b.allPolygons());
  31748. a.invert();
  31749. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31750. };
  31751. CSG.prototype.subtractInPlace = function (csg) {
  31752. var a = new Node(this.polygons);
  31753. var b = new Node(csg.polygons);
  31754. a.invert();
  31755. a.clipTo(b);
  31756. b.clipTo(a);
  31757. b.invert();
  31758. b.clipTo(a);
  31759. b.invert();
  31760. a.build(b.allPolygons());
  31761. a.invert();
  31762. this.polygons = a.allPolygons();
  31763. };
  31764. CSG.prototype.intersect = function (csg) {
  31765. var a = new Node(this.clone().polygons);
  31766. var b = new Node(csg.clone().polygons);
  31767. a.invert();
  31768. b.clipTo(a);
  31769. b.invert();
  31770. a.clipTo(b);
  31771. b.clipTo(a);
  31772. a.build(b.allPolygons());
  31773. a.invert();
  31774. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31775. };
  31776. CSG.prototype.intersectInPlace = function (csg) {
  31777. var a = new Node(this.polygons);
  31778. var b = new Node(csg.polygons);
  31779. a.invert();
  31780. b.clipTo(a);
  31781. b.invert();
  31782. a.clipTo(b);
  31783. b.clipTo(a);
  31784. a.build(b.allPolygons());
  31785. a.invert();
  31786. this.polygons = a.allPolygons();
  31787. };
  31788. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31789. // not modified.
  31790. CSG.prototype.inverse = function () {
  31791. var csg = this.clone();
  31792. csg.inverseInPlace();
  31793. return csg;
  31794. };
  31795. CSG.prototype.inverseInPlace = function () {
  31796. this.polygons.map(function (p) { p.flip(); });
  31797. };
  31798. // This is used to keep meshes transformations so they can be restored
  31799. // when we build back a Babylon Mesh
  31800. // NB : All CSG operations are performed in world coordinates
  31801. CSG.prototype.copyTransformAttributes = function (csg) {
  31802. this.matrix = csg.matrix;
  31803. this.position = csg.position;
  31804. this.rotation = csg.rotation;
  31805. this.scaling = csg.scaling;
  31806. this.rotationQuaternion = csg.rotationQuaternion;
  31807. return this;
  31808. };
  31809. // Build Raw mesh from CSG
  31810. // Coordinates here are in world space
  31811. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31812. var matrix = this.matrix.clone();
  31813. matrix.invert();
  31814. 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;
  31815. if (keepSubMeshes) {
  31816. // Sort Polygons, since subMeshes are indices range
  31817. polygons.sort(function (a, b) {
  31818. if (a.shared.meshId === b.shared.meshId) {
  31819. return a.shared.subMeshId - b.shared.subMeshId;
  31820. }
  31821. else {
  31822. return a.shared.meshId - b.shared.meshId;
  31823. }
  31824. });
  31825. }
  31826. for (var i = 0, il = polygons.length; i < il; i++) {
  31827. polygon = polygons[i];
  31828. // Building SubMeshes
  31829. if (!subMesh_dict[polygon.shared.meshId]) {
  31830. subMesh_dict[polygon.shared.meshId] = {};
  31831. }
  31832. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31833. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31834. indexStart: +Infinity,
  31835. indexEnd: -Infinity,
  31836. materialIndex: polygon.shared.materialIndex
  31837. };
  31838. }
  31839. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31840. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31841. polygonIndices[0] = 0;
  31842. polygonIndices[1] = j - 1;
  31843. polygonIndices[2] = j;
  31844. for (var k = 0; k < 3; k++) {
  31845. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31846. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31847. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31848. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31849. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31850. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31851. // Check if 2 points can be merged
  31852. if (!(typeof vertex_idx !== 'undefined' &&
  31853. normals[vertex_idx * 3] === localNormal.x &&
  31854. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31855. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31856. uvs[vertex_idx * 2] === uv.x &&
  31857. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31858. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31859. uvs.push(uv.x, uv.y);
  31860. normals.push(normal.x, normal.y, normal.z);
  31861. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31862. }
  31863. indices.push(vertex_idx);
  31864. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31865. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31866. currentIndex++;
  31867. }
  31868. }
  31869. }
  31870. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31871. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31872. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31873. mesh.setIndices(indices);
  31874. if (keepSubMeshes) {
  31875. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31876. var materialIndexOffset = 0, materialMaxIndex;
  31877. mesh.subMeshes = new Array();
  31878. for (var m in subMesh_dict) {
  31879. materialMaxIndex = -1;
  31880. for (var sm in subMesh_dict[m]) {
  31881. subMesh_obj = subMesh_dict[m][sm];
  31882. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31883. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31884. }
  31885. materialIndexOffset += ++materialMaxIndex;
  31886. }
  31887. }
  31888. return mesh;
  31889. };
  31890. // Build Mesh from CSG taking material and transforms into account
  31891. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31892. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31893. mesh.material = material;
  31894. mesh.position.copyFrom(this.position);
  31895. mesh.rotation.copyFrom(this.rotation);
  31896. if (this.rotationQuaternion) {
  31897. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31898. }
  31899. mesh.scaling.copyFrom(this.scaling);
  31900. mesh.computeWorldMatrix(true);
  31901. return mesh;
  31902. };
  31903. return CSG;
  31904. })();
  31905. BABYLON.CSG = CSG;
  31906. })(BABYLON || (BABYLON = {}));
  31907. var BABYLON;
  31908. (function (BABYLON) {
  31909. var VRDistortionCorrectionPostProcess = (function (_super) {
  31910. __extends(VRDistortionCorrectionPostProcess, _super);
  31911. //ANY
  31912. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31913. var _this = this;
  31914. _super.call(this, name, "vrDistortionCorrection", [
  31915. 'LensCenter',
  31916. 'Scale',
  31917. 'ScaleIn',
  31918. 'HmdWarpParam'
  31919. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31920. this._isRightEye = isRightEye;
  31921. this._distortionFactors = vrMetrics.distortionK;
  31922. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31923. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31924. this.onSizeChanged = function () {
  31925. _this.aspectRatio = _this.width * .5 / _this.height;
  31926. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31927. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31928. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31929. };
  31930. this.onApply = function (effect) {
  31931. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31932. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31933. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31934. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31935. };
  31936. }
  31937. return VRDistortionCorrectionPostProcess;
  31938. })(BABYLON.PostProcess);
  31939. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31940. })(BABYLON || (BABYLON = {}));
  31941. // Mainly based on these 2 articles :
  31942. // 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
  31943. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31944. var BABYLON;
  31945. (function (BABYLON) {
  31946. (function (JoystickAxis) {
  31947. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31948. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31949. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31950. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31951. var JoystickAxis = BABYLON.JoystickAxis;
  31952. var VirtualJoystick = (function () {
  31953. function VirtualJoystick(leftJoystick) {
  31954. var _this = this;
  31955. if (leftJoystick) {
  31956. this._leftJoystick = true;
  31957. }
  31958. else {
  31959. this._leftJoystick = false;
  31960. }
  31961. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31962. VirtualJoystick._globalJoystickIndex++;
  31963. // By default left & right arrow keys are moving the X
  31964. // and up & down keys are moving the Y
  31965. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31966. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31967. this.reverseLeftRight = false;
  31968. this.reverseUpDown = false;
  31969. // collections of pointers
  31970. this._touches = new BABYLON.SmartCollection();
  31971. this.deltaPosition = BABYLON.Vector3.Zero();
  31972. this._joystickSensibility = 25;
  31973. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31974. this._rotationSpeed = 25;
  31975. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31976. this._rotateOnAxisRelativeToMesh = false;
  31977. this._onResize = function (evt) {
  31978. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31979. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31980. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31981. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31982. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31983. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31984. };
  31985. // injecting a canvas element on top of the canvas 3D game
  31986. if (!VirtualJoystick.vjCanvas) {
  31987. window.addEventListener("resize", this._onResize, false);
  31988. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31989. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31990. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31991. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31992. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31993. VirtualJoystick.vjCanvas.style.width = "100%";
  31994. VirtualJoystick.vjCanvas.style.height = "100%";
  31995. VirtualJoystick.vjCanvas.style.position = "absolute";
  31996. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31997. VirtualJoystick.vjCanvas.style.top = "0px";
  31998. VirtualJoystick.vjCanvas.style.left = "0px";
  31999. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32000. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32001. // Support for jQuery PEP polyfill
  32002. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32003. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32004. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32005. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32006. document.body.appendChild(VirtualJoystick.vjCanvas);
  32007. }
  32008. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32009. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32010. this.pressed = false;
  32011. // default joystick color
  32012. this._joystickColor = "cyan";
  32013. this._joystickPointerID = -1;
  32014. // current joystick position
  32015. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32016. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32017. // origin joystick position
  32018. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32019. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32020. this._onPointerDownHandlerRef = function (evt) {
  32021. _this._onPointerDown(evt);
  32022. };
  32023. this._onPointerMoveHandlerRef = function (evt) {
  32024. _this._onPointerMove(evt);
  32025. };
  32026. this._onPointerOutHandlerRef = function (evt) {
  32027. _this._onPointerUp(evt);
  32028. };
  32029. this._onPointerUpHandlerRef = function (evt) {
  32030. _this._onPointerUp(evt);
  32031. };
  32032. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32033. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32034. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32035. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32036. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32037. evt.preventDefault(); // Disables system menu
  32038. }, false);
  32039. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32040. }
  32041. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32042. this._joystickSensibility = newJoystickSensibility;
  32043. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32044. };
  32045. VirtualJoystick.prototype._onPointerDown = function (e) {
  32046. var positionOnScreenCondition;
  32047. e.preventDefault();
  32048. if (this._leftJoystick === true) {
  32049. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32050. }
  32051. else {
  32052. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32053. }
  32054. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32055. // First contact will be dedicated to the virtual joystick
  32056. this._joystickPointerID = e.pointerId;
  32057. this._joystickPointerStartPos.x = e.clientX;
  32058. this._joystickPointerStartPos.y = e.clientY;
  32059. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32060. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32061. this._deltaJoystickVector.x = 0;
  32062. this._deltaJoystickVector.y = 0;
  32063. this.pressed = true;
  32064. this._touches.add(e.pointerId.toString(), e);
  32065. }
  32066. else {
  32067. // You can only trigger the action buttons with a joystick declared
  32068. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32069. this._action();
  32070. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32071. }
  32072. }
  32073. };
  32074. VirtualJoystick.prototype._onPointerMove = function (e) {
  32075. // If the current pointer is the one associated to the joystick (first touch contact)
  32076. if (this._joystickPointerID == e.pointerId) {
  32077. this._joystickPointerPos.x = e.clientX;
  32078. this._joystickPointerPos.y = e.clientY;
  32079. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32080. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32081. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32082. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32083. switch (this._axisTargetedByLeftAndRight) {
  32084. case JoystickAxis.X:
  32085. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32086. break;
  32087. case JoystickAxis.Y:
  32088. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32089. break;
  32090. case JoystickAxis.Z:
  32091. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32092. break;
  32093. }
  32094. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32095. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32096. switch (this._axisTargetedByUpAndDown) {
  32097. case JoystickAxis.X:
  32098. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32099. break;
  32100. case JoystickAxis.Y:
  32101. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32102. break;
  32103. case JoystickAxis.Z:
  32104. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32105. break;
  32106. }
  32107. }
  32108. else {
  32109. if (this._touches.item(e.pointerId.toString())) {
  32110. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32111. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32112. }
  32113. }
  32114. };
  32115. VirtualJoystick.prototype._onPointerUp = function (e) {
  32116. if (this._joystickPointerID == e.pointerId) {
  32117. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32118. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32119. this._joystickPointerID = -1;
  32120. this.pressed = false;
  32121. }
  32122. else {
  32123. var touch = this._touches.item(e.pointerId.toString());
  32124. if (touch) {
  32125. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32126. }
  32127. }
  32128. this._deltaJoystickVector.x = 0;
  32129. this._deltaJoystickVector.y = 0;
  32130. this._touches.remove(e.pointerId.toString());
  32131. };
  32132. /**
  32133. * Change the color of the virtual joystick
  32134. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32135. */
  32136. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32137. this._joystickColor = newColor;
  32138. };
  32139. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32140. this._action = action;
  32141. };
  32142. // Define which axis you'd like to control for left & right
  32143. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32144. switch (axis) {
  32145. case JoystickAxis.X:
  32146. case JoystickAxis.Y:
  32147. case JoystickAxis.Z:
  32148. this._axisTargetedByLeftAndRight = axis;
  32149. break;
  32150. default:
  32151. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32152. break;
  32153. }
  32154. };
  32155. // Define which axis you'd like to control for up & down
  32156. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32157. switch (axis) {
  32158. case JoystickAxis.X:
  32159. case JoystickAxis.Y:
  32160. case JoystickAxis.Z:
  32161. this._axisTargetedByUpAndDown = axis;
  32162. break;
  32163. default:
  32164. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32165. break;
  32166. }
  32167. };
  32168. VirtualJoystick.prototype._clearCanvas = function () {
  32169. if (this._leftJoystick) {
  32170. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32171. }
  32172. else {
  32173. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32174. }
  32175. };
  32176. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32177. var _this = this;
  32178. if (this.pressed) {
  32179. this._touches.forEach(function (touch) {
  32180. if (touch.pointerId === _this._joystickPointerID) {
  32181. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32182. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32183. VirtualJoystick.vjCanvasContext.beginPath();
  32184. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32185. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32186. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32187. VirtualJoystick.vjCanvasContext.stroke();
  32188. VirtualJoystick.vjCanvasContext.closePath();
  32189. VirtualJoystick.vjCanvasContext.beginPath();
  32190. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32191. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32192. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32193. VirtualJoystick.vjCanvasContext.stroke();
  32194. VirtualJoystick.vjCanvasContext.closePath();
  32195. VirtualJoystick.vjCanvasContext.beginPath();
  32196. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32197. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32198. VirtualJoystick.vjCanvasContext.stroke();
  32199. VirtualJoystick.vjCanvasContext.closePath();
  32200. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32201. }
  32202. else {
  32203. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32204. VirtualJoystick.vjCanvasContext.beginPath();
  32205. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32206. VirtualJoystick.vjCanvasContext.beginPath();
  32207. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32208. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32209. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32210. VirtualJoystick.vjCanvasContext.stroke();
  32211. VirtualJoystick.vjCanvasContext.closePath();
  32212. touch.prevX = touch.x;
  32213. touch.prevY = touch.y;
  32214. }
  32215. ;
  32216. });
  32217. }
  32218. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32219. };
  32220. VirtualJoystick.prototype.releaseCanvas = function () {
  32221. if (VirtualJoystick.vjCanvas) {
  32222. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32223. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32224. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32225. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32226. window.removeEventListener("resize", this._onResize);
  32227. document.body.removeChild(VirtualJoystick.vjCanvas);
  32228. VirtualJoystick.vjCanvas = null;
  32229. }
  32230. };
  32231. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32232. VirtualJoystick._globalJoystickIndex = 0;
  32233. return VirtualJoystick;
  32234. })();
  32235. BABYLON.VirtualJoystick = VirtualJoystick;
  32236. })(BABYLON || (BABYLON = {}));
  32237. var BABYLON;
  32238. (function (BABYLON) {
  32239. // We're mainly based on the logic defined into the FreeCamera code
  32240. var VirtualJoysticksCamera = (function (_super) {
  32241. __extends(VirtualJoysticksCamera, _super);
  32242. function VirtualJoysticksCamera(name, position, scene) {
  32243. _super.call(this, name, position, scene);
  32244. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32245. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32246. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32247. this._leftjoystick.setJoystickSensibility(0.15);
  32248. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32249. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32250. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32251. this._rightjoystick.reverseUpDown = true;
  32252. this._rightjoystick.setJoystickSensibility(0.05);
  32253. this._rightjoystick.setJoystickColor("yellow");
  32254. }
  32255. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  32256. return this._leftjoystick;
  32257. };
  32258. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  32259. return this._rightjoystick;
  32260. };
  32261. VirtualJoysticksCamera.prototype._checkInputs = function () {
  32262. var speed = this._computeLocalCameraSpeed() * 50;
  32263. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32264. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  32265. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32266. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  32267. if (!this._leftjoystick.pressed) {
  32268. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  32269. }
  32270. if (!this._rightjoystick.pressed) {
  32271. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  32272. }
  32273. _super.prototype._checkInputs.call(this);
  32274. };
  32275. VirtualJoysticksCamera.prototype.dispose = function () {
  32276. this._leftjoystick.releaseCanvas();
  32277. _super.prototype.dispose.call(this);
  32278. };
  32279. return VirtualJoysticksCamera;
  32280. })(BABYLON.FreeCamera);
  32281. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  32282. })(BABYLON || (BABYLON = {}));
  32283. var BABYLON;
  32284. (function (BABYLON) {
  32285. var AnaglyphPostProcess = (function (_super) {
  32286. __extends(AnaglyphPostProcess, _super);
  32287. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32288. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  32289. }
  32290. return AnaglyphPostProcess;
  32291. })(BABYLON.PostProcess);
  32292. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  32293. })(BABYLON || (BABYLON = {}));
  32294. var BABYLON;
  32295. (function (BABYLON) {
  32296. var OutlineRenderer = (function () {
  32297. function OutlineRenderer(scene) {
  32298. this._scene = scene;
  32299. }
  32300. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  32301. var _this = this;
  32302. if (useOverlay === void 0) { useOverlay = false; }
  32303. var scene = this._scene;
  32304. var engine = this._scene.getEngine();
  32305. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32306. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  32307. return;
  32308. }
  32309. var mesh = subMesh.getRenderingMesh();
  32310. var material = subMesh.getMaterial();
  32311. engine.enableEffect(this._effect);
  32312. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  32313. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  32314. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32315. // Bones
  32316. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32317. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32318. }
  32319. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  32320. // Alpha test
  32321. if (material && material.needAlphaTesting()) {
  32322. var alphaTexture = material.getAlphaTestTexture();
  32323. this._effect.setTexture("diffuseSampler", alphaTexture);
  32324. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32325. }
  32326. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  32327. };
  32328. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  32329. var defines = [];
  32330. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  32331. var mesh = subMesh.getMesh();
  32332. var material = subMesh.getMaterial();
  32333. // Alpha test
  32334. if (material && material.needAlphaTesting()) {
  32335. defines.push("#define ALPHATEST");
  32336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32337. attribs.push(BABYLON.VertexBuffer.UVKind);
  32338. defines.push("#define UV1");
  32339. }
  32340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32341. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32342. defines.push("#define UV2");
  32343. }
  32344. }
  32345. // Bones
  32346. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32347. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32348. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32349. if (mesh.numBoneInfluencers > 4) {
  32350. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32351. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32352. }
  32353. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32354. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32355. }
  32356. else {
  32357. defines.push("#define NUM_BONE_INFLUENCERS 0");
  32358. }
  32359. // Instances
  32360. if (useInstances) {
  32361. defines.push("#define INSTANCES");
  32362. attribs.push("world0");
  32363. attribs.push("world1");
  32364. attribs.push("world2");
  32365. attribs.push("world3");
  32366. }
  32367. // Get correct effect
  32368. var join = defines.join("\n");
  32369. if (this._cachedDefines !== join) {
  32370. this._cachedDefines = join;
  32371. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  32372. }
  32373. return this._effect.isReady();
  32374. };
  32375. return OutlineRenderer;
  32376. })();
  32377. BABYLON.OutlineRenderer = OutlineRenderer;
  32378. })(BABYLON || (BABYLON = {}));
  32379. var BABYLON;
  32380. (function (BABYLON) {
  32381. var MeshAssetTask = (function () {
  32382. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  32383. this.name = name;
  32384. this.meshesNames = meshesNames;
  32385. this.rootUrl = rootUrl;
  32386. this.sceneFilename = sceneFilename;
  32387. this.isCompleted = false;
  32388. }
  32389. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32390. var _this = this;
  32391. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32392. _this.loadedMeshes = meshes;
  32393. _this.loadedParticleSystems = particleSystems;
  32394. _this.loadedSkeletons = skeletons;
  32395. _this.isCompleted = true;
  32396. if (_this.onSuccess) {
  32397. _this.onSuccess(_this);
  32398. }
  32399. onSuccess();
  32400. }, null, function () {
  32401. if (_this.onError) {
  32402. _this.onError(_this);
  32403. }
  32404. onError();
  32405. });
  32406. };
  32407. return MeshAssetTask;
  32408. })();
  32409. BABYLON.MeshAssetTask = MeshAssetTask;
  32410. var TextFileAssetTask = (function () {
  32411. function TextFileAssetTask(name, url) {
  32412. this.name = name;
  32413. this.url = url;
  32414. this.isCompleted = false;
  32415. }
  32416. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32417. var _this = this;
  32418. BABYLON.Tools.LoadFile(this.url, function (data) {
  32419. _this.text = data;
  32420. _this.isCompleted = true;
  32421. if (_this.onSuccess) {
  32422. _this.onSuccess(_this);
  32423. }
  32424. onSuccess();
  32425. }, null, scene.database, false, function () {
  32426. if (_this.onError) {
  32427. _this.onError(_this);
  32428. }
  32429. onError();
  32430. });
  32431. };
  32432. return TextFileAssetTask;
  32433. })();
  32434. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32435. var BinaryFileAssetTask = (function () {
  32436. function BinaryFileAssetTask(name, url) {
  32437. this.name = name;
  32438. this.url = url;
  32439. this.isCompleted = false;
  32440. }
  32441. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32442. var _this = this;
  32443. BABYLON.Tools.LoadFile(this.url, function (data) {
  32444. _this.data = data;
  32445. _this.isCompleted = true;
  32446. if (_this.onSuccess) {
  32447. _this.onSuccess(_this);
  32448. }
  32449. onSuccess();
  32450. }, null, scene.database, true, function () {
  32451. if (_this.onError) {
  32452. _this.onError(_this);
  32453. }
  32454. onError();
  32455. });
  32456. };
  32457. return BinaryFileAssetTask;
  32458. })();
  32459. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32460. var ImageAssetTask = (function () {
  32461. function ImageAssetTask(name, url) {
  32462. this.name = name;
  32463. this.url = url;
  32464. this.isCompleted = false;
  32465. }
  32466. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32467. var _this = this;
  32468. var img = new Image();
  32469. img.onload = function () {
  32470. _this.image = img;
  32471. _this.isCompleted = true;
  32472. if (_this.onSuccess) {
  32473. _this.onSuccess(_this);
  32474. }
  32475. onSuccess();
  32476. };
  32477. img.onerror = function () {
  32478. if (_this.onError) {
  32479. _this.onError(_this);
  32480. }
  32481. onError();
  32482. };
  32483. img.src = this.url;
  32484. };
  32485. return ImageAssetTask;
  32486. })();
  32487. BABYLON.ImageAssetTask = ImageAssetTask;
  32488. var TextureAssetTask = (function () {
  32489. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32491. this.name = name;
  32492. this.url = url;
  32493. this.noMipmap = noMipmap;
  32494. this.invertY = invertY;
  32495. this.samplingMode = samplingMode;
  32496. this.isCompleted = false;
  32497. }
  32498. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32499. var _this = this;
  32500. var onload = function () {
  32501. _this.isCompleted = true;
  32502. if (_this.onSuccess) {
  32503. _this.onSuccess(_this);
  32504. }
  32505. onSuccess();
  32506. };
  32507. var onerror = function () {
  32508. if (_this.onError) {
  32509. _this.onError(_this);
  32510. }
  32511. onError();
  32512. };
  32513. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32514. };
  32515. return TextureAssetTask;
  32516. })();
  32517. BABYLON.TextureAssetTask = TextureAssetTask;
  32518. var AssetsManager = (function () {
  32519. function AssetsManager(scene) {
  32520. this._tasks = new Array();
  32521. this._waitingTasksCount = 0;
  32522. this.useDefaultLoadingScreen = true;
  32523. this._scene = scene;
  32524. }
  32525. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32526. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32527. this._tasks.push(task);
  32528. return task;
  32529. };
  32530. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32531. var task = new TextFileAssetTask(taskName, url);
  32532. this._tasks.push(task);
  32533. return task;
  32534. };
  32535. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32536. var task = new BinaryFileAssetTask(taskName, url);
  32537. this._tasks.push(task);
  32538. return task;
  32539. };
  32540. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32541. var task = new ImageAssetTask(taskName, url);
  32542. this._tasks.push(task);
  32543. return task;
  32544. };
  32545. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32547. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32548. this._tasks.push(task);
  32549. return task;
  32550. };
  32551. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32552. this._waitingTasksCount--;
  32553. if (this._waitingTasksCount === 0) {
  32554. if (this.onFinish) {
  32555. this.onFinish(this._tasks);
  32556. }
  32557. this._scene.getEngine().hideLoadingUI();
  32558. }
  32559. };
  32560. AssetsManager.prototype._runTask = function (task) {
  32561. var _this = this;
  32562. task.run(this._scene, function () {
  32563. if (_this.onTaskSuccess) {
  32564. _this.onTaskSuccess(task);
  32565. }
  32566. _this._decreaseWaitingTasksCount();
  32567. }, function () {
  32568. if (_this.onTaskError) {
  32569. _this.onTaskError(task);
  32570. }
  32571. _this._decreaseWaitingTasksCount();
  32572. });
  32573. };
  32574. AssetsManager.prototype.reset = function () {
  32575. this._tasks = new Array();
  32576. return this;
  32577. };
  32578. AssetsManager.prototype.load = function () {
  32579. this._waitingTasksCount = this._tasks.length;
  32580. if (this._waitingTasksCount === 0) {
  32581. if (this.onFinish) {
  32582. this.onFinish(this._tasks);
  32583. }
  32584. return this;
  32585. }
  32586. if (this.useDefaultLoadingScreen) {
  32587. this._scene.getEngine().displayLoadingUI();
  32588. }
  32589. for (var index = 0; index < this._tasks.length; index++) {
  32590. var task = this._tasks[index];
  32591. this._runTask(task);
  32592. }
  32593. return this;
  32594. };
  32595. return AssetsManager;
  32596. })();
  32597. BABYLON.AssetsManager = AssetsManager;
  32598. })(BABYLON || (BABYLON = {}));
  32599. var BABYLON;
  32600. (function (BABYLON) {
  32601. var VRDeviceOrientationFreeCamera = (function (_super) {
  32602. __extends(VRDeviceOrientationFreeCamera, _super);
  32603. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32604. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32605. _super.call(this, name, position, scene);
  32606. this._alpha = 0;
  32607. this._beta = 0;
  32608. this._gamma = 0;
  32609. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32610. metrics.compensateDistortion = compensateDistortion;
  32611. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32612. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32613. }
  32614. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32615. this._alpha = +evt.alpha | 0;
  32616. this._beta = +evt.beta | 0;
  32617. this._gamma = +evt.gamma | 0;
  32618. if (this._gamma < 0) {
  32619. this._gamma = 90 + this._gamma;
  32620. }
  32621. else {
  32622. // Incline it in the correct angle.
  32623. this._gamma = 270 - this._gamma;
  32624. }
  32625. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32626. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32627. this.rotation.z = this._beta / 180.0 * Math.PI;
  32628. };
  32629. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32630. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32631. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32632. };
  32633. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32634. _super.prototype.detachControl.call(this, element);
  32635. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32636. };
  32637. return VRDeviceOrientationFreeCamera;
  32638. })(BABYLON.FreeCamera);
  32639. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32640. })(BABYLON || (BABYLON = {}));
  32641. var BABYLON;
  32642. (function (BABYLON) {
  32643. var WebVRFreeCamera = (function (_super) {
  32644. __extends(WebVRFreeCamera, _super);
  32645. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32646. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32647. _super.call(this, name, position, scene);
  32648. this._hmdDevice = null;
  32649. this._sensorDevice = null;
  32650. this._cacheState = null;
  32651. this._cacheQuaternion = new BABYLON.Quaternion();
  32652. this._cacheRotation = BABYLON.Vector3.Zero();
  32653. this._vrEnabled = false;
  32654. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32655. metrics.compensateDistortion = compensateDistortion;
  32656. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32657. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32658. }
  32659. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32660. var size = devices.length;
  32661. var i = 0;
  32662. // Reset devices.
  32663. this._sensorDevice = null;
  32664. this._hmdDevice = null;
  32665. // Search for a HmdDevice.
  32666. while (i < size && this._hmdDevice === null) {
  32667. if (devices[i] instanceof HMDVRDevice) {
  32668. this._hmdDevice = devices[i];
  32669. }
  32670. i++;
  32671. }
  32672. i = 0;
  32673. while (i < size && this._sensorDevice === null) {
  32674. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32675. this._sensorDevice = devices[i];
  32676. }
  32677. i++;
  32678. }
  32679. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32680. };
  32681. WebVRFreeCamera.prototype._checkInputs = function () {
  32682. if (this._vrEnabled) {
  32683. this._cacheState = this._sensorDevice.getState();
  32684. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32685. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32686. this.rotation.x = -this._cacheRotation.z;
  32687. this.rotation.y = -this._cacheRotation.y;
  32688. this.rotation.z = this._cacheRotation.x;
  32689. }
  32690. _super.prototype._checkInputs.call(this);
  32691. };
  32692. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32693. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32694. if (navigator.getVRDevices) {
  32695. navigator.getVRDevices().then(this._getWebVRDevices);
  32696. }
  32697. else if (navigator.mozGetVRDevices) {
  32698. navigator.mozGetVRDevices(this._getWebVRDevices);
  32699. }
  32700. };
  32701. WebVRFreeCamera.prototype.detachControl = function (element) {
  32702. _super.prototype.detachControl.call(this, element);
  32703. this._vrEnabled = false;
  32704. };
  32705. return WebVRFreeCamera;
  32706. })(BABYLON.FreeCamera);
  32707. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32708. })(BABYLON || (BABYLON = {}));
  32709. var BABYLON;
  32710. (function (BABYLON) {
  32711. // Standard optimizations
  32712. var SceneOptimization = (function () {
  32713. function SceneOptimization(priority) {
  32714. if (priority === void 0) { priority = 0; }
  32715. this.priority = priority;
  32716. this.apply = function (scene) {
  32717. return true; // Return true if everything that can be done was applied
  32718. };
  32719. }
  32720. return SceneOptimization;
  32721. })();
  32722. BABYLON.SceneOptimization = SceneOptimization;
  32723. var TextureOptimization = (function (_super) {
  32724. __extends(TextureOptimization, _super);
  32725. function TextureOptimization(priority, maximumSize) {
  32726. var _this = this;
  32727. if (priority === void 0) { priority = 0; }
  32728. if (maximumSize === void 0) { maximumSize = 1024; }
  32729. _super.call(this, priority);
  32730. this.priority = priority;
  32731. this.maximumSize = maximumSize;
  32732. this.apply = function (scene) {
  32733. var allDone = true;
  32734. for (var index = 0; index < scene.textures.length; index++) {
  32735. var texture = scene.textures[index];
  32736. if (!texture.canRescale) {
  32737. continue;
  32738. }
  32739. var currentSize = texture.getSize();
  32740. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32741. if (maxDimension > _this.maximumSize) {
  32742. texture.scale(0.5);
  32743. allDone = false;
  32744. }
  32745. }
  32746. return allDone;
  32747. };
  32748. }
  32749. return TextureOptimization;
  32750. })(SceneOptimization);
  32751. BABYLON.TextureOptimization = TextureOptimization;
  32752. var HardwareScalingOptimization = (function (_super) {
  32753. __extends(HardwareScalingOptimization, _super);
  32754. function HardwareScalingOptimization(priority, maximumScale) {
  32755. var _this = this;
  32756. if (priority === void 0) { priority = 0; }
  32757. if (maximumScale === void 0) { maximumScale = 2; }
  32758. _super.call(this, priority);
  32759. this.priority = priority;
  32760. this.maximumScale = maximumScale;
  32761. this._currentScale = 1;
  32762. this.apply = function (scene) {
  32763. _this._currentScale++;
  32764. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32765. return _this._currentScale >= _this.maximumScale;
  32766. };
  32767. }
  32768. return HardwareScalingOptimization;
  32769. })(SceneOptimization);
  32770. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32771. var ShadowsOptimization = (function (_super) {
  32772. __extends(ShadowsOptimization, _super);
  32773. function ShadowsOptimization() {
  32774. _super.apply(this, arguments);
  32775. this.apply = function (scene) {
  32776. scene.shadowsEnabled = false;
  32777. return true;
  32778. };
  32779. }
  32780. return ShadowsOptimization;
  32781. })(SceneOptimization);
  32782. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32783. var PostProcessesOptimization = (function (_super) {
  32784. __extends(PostProcessesOptimization, _super);
  32785. function PostProcessesOptimization() {
  32786. _super.apply(this, arguments);
  32787. this.apply = function (scene) {
  32788. scene.postProcessesEnabled = false;
  32789. return true;
  32790. };
  32791. }
  32792. return PostProcessesOptimization;
  32793. })(SceneOptimization);
  32794. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32795. var LensFlaresOptimization = (function (_super) {
  32796. __extends(LensFlaresOptimization, _super);
  32797. function LensFlaresOptimization() {
  32798. _super.apply(this, arguments);
  32799. this.apply = function (scene) {
  32800. scene.lensFlaresEnabled = false;
  32801. return true;
  32802. };
  32803. }
  32804. return LensFlaresOptimization;
  32805. })(SceneOptimization);
  32806. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32807. var ParticlesOptimization = (function (_super) {
  32808. __extends(ParticlesOptimization, _super);
  32809. function ParticlesOptimization() {
  32810. _super.apply(this, arguments);
  32811. this.apply = function (scene) {
  32812. scene.particlesEnabled = false;
  32813. return true;
  32814. };
  32815. }
  32816. return ParticlesOptimization;
  32817. })(SceneOptimization);
  32818. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32819. var RenderTargetsOptimization = (function (_super) {
  32820. __extends(RenderTargetsOptimization, _super);
  32821. function RenderTargetsOptimization() {
  32822. _super.apply(this, arguments);
  32823. this.apply = function (scene) {
  32824. scene.renderTargetsEnabled = false;
  32825. return true;
  32826. };
  32827. }
  32828. return RenderTargetsOptimization;
  32829. })(SceneOptimization);
  32830. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32831. var MergeMeshesOptimization = (function (_super) {
  32832. __extends(MergeMeshesOptimization, _super);
  32833. function MergeMeshesOptimization() {
  32834. var _this = this;
  32835. _super.apply(this, arguments);
  32836. this._canBeMerged = function (abstractMesh) {
  32837. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32838. return false;
  32839. }
  32840. var mesh = abstractMesh;
  32841. if (!mesh.isVisible || !mesh.isEnabled()) {
  32842. return false;
  32843. }
  32844. if (mesh.instances.length > 0) {
  32845. return false;
  32846. }
  32847. if (mesh.skeleton || mesh.hasLODLevels) {
  32848. return false;
  32849. }
  32850. if (mesh.parent) {
  32851. return false;
  32852. }
  32853. return true;
  32854. };
  32855. this.apply = function (scene, updateSelectionTree) {
  32856. var globalPool = scene.meshes.slice(0);
  32857. var globalLength = globalPool.length;
  32858. for (var index = 0; index < globalLength; index++) {
  32859. var currentPool = new Array();
  32860. var current = globalPool[index];
  32861. // Checks
  32862. if (!_this._canBeMerged(current)) {
  32863. continue;
  32864. }
  32865. currentPool.push(current);
  32866. // Find compatible meshes
  32867. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32868. var otherMesh = globalPool[subIndex];
  32869. if (!_this._canBeMerged(otherMesh)) {
  32870. continue;
  32871. }
  32872. if (otherMesh.material !== current.material) {
  32873. continue;
  32874. }
  32875. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32876. continue;
  32877. }
  32878. currentPool.push(otherMesh);
  32879. globalLength--;
  32880. globalPool.splice(subIndex, 1);
  32881. subIndex--;
  32882. }
  32883. if (currentPool.length < 2) {
  32884. continue;
  32885. }
  32886. // Merge meshes
  32887. BABYLON.Mesh.MergeMeshes(currentPool);
  32888. }
  32889. if (updateSelectionTree != undefined) {
  32890. if (updateSelectionTree) {
  32891. scene.createOrUpdateSelectionOctree();
  32892. }
  32893. }
  32894. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32895. scene.createOrUpdateSelectionOctree();
  32896. }
  32897. return true;
  32898. };
  32899. }
  32900. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32901. get: function () {
  32902. return MergeMeshesOptimization._UpdateSelectionTree;
  32903. },
  32904. set: function (value) {
  32905. MergeMeshesOptimization._UpdateSelectionTree = value;
  32906. },
  32907. enumerable: true,
  32908. configurable: true
  32909. });
  32910. MergeMeshesOptimization._UpdateSelectionTree = false;
  32911. return MergeMeshesOptimization;
  32912. })(SceneOptimization);
  32913. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32914. // Options
  32915. var SceneOptimizerOptions = (function () {
  32916. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32917. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32918. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32919. this.targetFrameRate = targetFrameRate;
  32920. this.trackerDuration = trackerDuration;
  32921. this.optimizations = new Array();
  32922. }
  32923. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32924. var result = new SceneOptimizerOptions(targetFrameRate);
  32925. var priority = 0;
  32926. result.optimizations.push(new MergeMeshesOptimization(priority));
  32927. result.optimizations.push(new ShadowsOptimization(priority));
  32928. result.optimizations.push(new LensFlaresOptimization(priority));
  32929. // Next priority
  32930. priority++;
  32931. result.optimizations.push(new PostProcessesOptimization(priority));
  32932. result.optimizations.push(new ParticlesOptimization(priority));
  32933. // Next priority
  32934. priority++;
  32935. result.optimizations.push(new TextureOptimization(priority, 1024));
  32936. return result;
  32937. };
  32938. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32939. var result = new SceneOptimizerOptions(targetFrameRate);
  32940. var priority = 0;
  32941. result.optimizations.push(new MergeMeshesOptimization(priority));
  32942. result.optimizations.push(new ShadowsOptimization(priority));
  32943. result.optimizations.push(new LensFlaresOptimization(priority));
  32944. // Next priority
  32945. priority++;
  32946. result.optimizations.push(new PostProcessesOptimization(priority));
  32947. result.optimizations.push(new ParticlesOptimization(priority));
  32948. // Next priority
  32949. priority++;
  32950. result.optimizations.push(new TextureOptimization(priority, 512));
  32951. // Next priority
  32952. priority++;
  32953. result.optimizations.push(new RenderTargetsOptimization(priority));
  32954. // Next priority
  32955. priority++;
  32956. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32957. return result;
  32958. };
  32959. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32960. var result = new SceneOptimizerOptions(targetFrameRate);
  32961. var priority = 0;
  32962. result.optimizations.push(new MergeMeshesOptimization(priority));
  32963. result.optimizations.push(new ShadowsOptimization(priority));
  32964. result.optimizations.push(new LensFlaresOptimization(priority));
  32965. // Next priority
  32966. priority++;
  32967. result.optimizations.push(new PostProcessesOptimization(priority));
  32968. result.optimizations.push(new ParticlesOptimization(priority));
  32969. // Next priority
  32970. priority++;
  32971. result.optimizations.push(new TextureOptimization(priority, 256));
  32972. // Next priority
  32973. priority++;
  32974. result.optimizations.push(new RenderTargetsOptimization(priority));
  32975. // Next priority
  32976. priority++;
  32977. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32978. return result;
  32979. };
  32980. return SceneOptimizerOptions;
  32981. })();
  32982. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32983. // Scene optimizer tool
  32984. var SceneOptimizer = (function () {
  32985. function SceneOptimizer() {
  32986. }
  32987. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32988. // TODO: add an epsilon
  32989. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32990. if (onSuccess) {
  32991. onSuccess();
  32992. }
  32993. return;
  32994. }
  32995. // Apply current level of optimizations
  32996. var allDone = true;
  32997. var noOptimizationApplied = true;
  32998. for (var index = 0; index < options.optimizations.length; index++) {
  32999. var optimization = options.optimizations[index];
  33000. if (optimization.priority === currentPriorityLevel) {
  33001. noOptimizationApplied = false;
  33002. allDone = allDone && optimization.apply(scene);
  33003. }
  33004. }
  33005. // If no optimization was applied, this is a failure :(
  33006. if (noOptimizationApplied) {
  33007. if (onFailure) {
  33008. onFailure();
  33009. }
  33010. return;
  33011. }
  33012. // If all optimizations were done, move to next level
  33013. if (allDone) {
  33014. currentPriorityLevel++;
  33015. }
  33016. // Let's the system running for a specific amount of time before checking FPS
  33017. scene.executeWhenReady(function () {
  33018. setTimeout(function () {
  33019. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33020. }, options.trackerDuration);
  33021. });
  33022. };
  33023. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33024. if (!options) {
  33025. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33026. }
  33027. // Let's the system running for a specific amount of time before checking FPS
  33028. scene.executeWhenReady(function () {
  33029. setTimeout(function () {
  33030. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33031. }, options.trackerDuration);
  33032. });
  33033. };
  33034. return SceneOptimizer;
  33035. })();
  33036. BABYLON.SceneOptimizer = SceneOptimizer;
  33037. })(BABYLON || (BABYLON = {}));
  33038. var BABYLON;
  33039. (function (BABYLON) {
  33040. var Internals;
  33041. (function (Internals) {
  33042. var MeshLODLevel = (function () {
  33043. function MeshLODLevel(distance, mesh) {
  33044. this.distance = distance;
  33045. this.mesh = mesh;
  33046. }
  33047. return MeshLODLevel;
  33048. })();
  33049. Internals.MeshLODLevel = MeshLODLevel;
  33050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33051. })(BABYLON || (BABYLON = {}));
  33052. var BABYLON;
  33053. (function (BABYLON) {
  33054. var RawTexture = (function (_super) {
  33055. __extends(RawTexture, _super);
  33056. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33058. if (invertY === void 0) { invertY = false; }
  33059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33060. _super.call(this, null, scene, !generateMipMaps, invertY);
  33061. this.format = format;
  33062. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33063. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33064. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33065. }
  33066. RawTexture.prototype.update = function (data) {
  33067. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33068. };
  33069. // Statics
  33070. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33072. if (invertY === void 0) { invertY = false; }
  33073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33074. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33075. };
  33076. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33078. if (invertY === void 0) { invertY = false; }
  33079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33080. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33081. };
  33082. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33084. if (invertY === void 0) { invertY = false; }
  33085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33086. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33087. };
  33088. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33089. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33090. if (invertY === void 0) { invertY = false; }
  33091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33092. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33093. };
  33094. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33095. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33096. if (invertY === void 0) { invertY = false; }
  33097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33098. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33099. };
  33100. return RawTexture;
  33101. })(BABYLON.Texture);
  33102. BABYLON.RawTexture = RawTexture;
  33103. })(BABYLON || (BABYLON = {}));
  33104. var BABYLON;
  33105. (function (BABYLON) {
  33106. var IndexedVector2 = (function (_super) {
  33107. __extends(IndexedVector2, _super);
  33108. function IndexedVector2(original, index) {
  33109. _super.call(this, original.x, original.y);
  33110. this.index = index;
  33111. }
  33112. return IndexedVector2;
  33113. })(BABYLON.Vector2);
  33114. var PolygonPoints = (function () {
  33115. function PolygonPoints() {
  33116. this.elements = new Array();
  33117. }
  33118. PolygonPoints.prototype.add = function (originalPoints) {
  33119. var _this = this;
  33120. var result = new Array();
  33121. originalPoints.forEach(function (point) {
  33122. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33123. var newPoint = new IndexedVector2(point, _this.elements.length);
  33124. result.push(newPoint);
  33125. _this.elements.push(newPoint);
  33126. }
  33127. });
  33128. return result;
  33129. };
  33130. PolygonPoints.prototype.computeBounds = function () {
  33131. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33132. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33133. this.elements.forEach(function (point) {
  33134. // x
  33135. if (point.x < lmin.x) {
  33136. lmin.x = point.x;
  33137. }
  33138. else if (point.x > lmax.x) {
  33139. lmax.x = point.x;
  33140. }
  33141. // y
  33142. if (point.y < lmin.y) {
  33143. lmin.y = point.y;
  33144. }
  33145. else if (point.y > lmax.y) {
  33146. lmax.y = point.y;
  33147. }
  33148. });
  33149. return {
  33150. min: lmin,
  33151. max: lmax,
  33152. width: lmax.x - lmin.x,
  33153. height: lmax.y - lmin.y
  33154. };
  33155. };
  33156. return PolygonPoints;
  33157. })();
  33158. var Polygon = (function () {
  33159. function Polygon() {
  33160. }
  33161. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33162. return [
  33163. new BABYLON.Vector2(xmin, ymin),
  33164. new BABYLON.Vector2(xmax, ymin),
  33165. new BABYLON.Vector2(xmax, ymax),
  33166. new BABYLON.Vector2(xmin, ymax)
  33167. ];
  33168. };
  33169. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33170. if (cx === void 0) { cx = 0; }
  33171. if (cy === void 0) { cy = 0; }
  33172. if (numberOfSides === void 0) { numberOfSides = 32; }
  33173. var result = new Array();
  33174. var angle = 0;
  33175. var increment = (Math.PI * 2) / numberOfSides;
  33176. for (var i = 0; i < numberOfSides; i++) {
  33177. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33178. angle -= increment;
  33179. }
  33180. return result;
  33181. };
  33182. Polygon.Parse = function (input) {
  33183. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33184. var i, result = [];
  33185. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33186. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33187. }
  33188. return result;
  33189. };
  33190. Polygon.StartingAt = function (x, y) {
  33191. return BABYLON.Path2.StartingAt(x, y);
  33192. };
  33193. return Polygon;
  33194. })();
  33195. BABYLON.Polygon = Polygon;
  33196. var PolygonMeshBuilder = (function () {
  33197. function PolygonMeshBuilder(name, contours, scene) {
  33198. this._points = new PolygonPoints();
  33199. this._outlinepoints = new PolygonPoints();
  33200. this._holes = [];
  33201. if (!("poly2tri" in window)) {
  33202. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33203. }
  33204. this._name = name;
  33205. this._scene = scene;
  33206. var points;
  33207. if (contours instanceof BABYLON.Path2) {
  33208. points = contours.getPoints();
  33209. }
  33210. else {
  33211. points = contours;
  33212. }
  33213. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33214. this._outlinepoints.add(points);
  33215. }
  33216. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33217. this._swctx.addHole(this._points.add(hole));
  33218. var holepoints = new PolygonPoints();
  33219. holepoints.add(hole);
  33220. this._holes.push(holepoints);
  33221. return this;
  33222. };
  33223. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33224. var _this = this;
  33225. if (updatable === void 0) { updatable = false; }
  33226. var result = new BABYLON.Mesh(this._name, this._scene);
  33227. var normals = [];
  33228. var positions = [];
  33229. var uvs = [];
  33230. var bounds = this._points.computeBounds();
  33231. this._points.elements.forEach(function (p) {
  33232. normals.push(0, 1.0, 0);
  33233. positions.push(p.x, 0, p.y);
  33234. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33235. });
  33236. var indices = [];
  33237. this._swctx.triangulate();
  33238. this._swctx.getTriangles().forEach(function (triangle) {
  33239. triangle.getPoints().forEach(function (point) {
  33240. indices.push(point.index);
  33241. });
  33242. });
  33243. if (depth > 0) {
  33244. var positionscount = (positions.length / 3); //get the current pointcount
  33245. this._points.elements.forEach(function (p) {
  33246. normals.push(0, -1.0, 0);
  33247. positions.push(p.x, -depth, p.y);
  33248. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33249. });
  33250. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33251. var p2;
  33252. var poscounter = 0;
  33253. this._swctx.getTriangles().forEach(function (triangle) {
  33254. triangle.getPoints().forEach(function (point) {
  33255. switch (poscounter) {
  33256. case 0:
  33257. p1 = point;
  33258. break;
  33259. case 1:
  33260. p2 = point;
  33261. break;
  33262. case 2:
  33263. indices.push(point.index + positionscount);
  33264. indices.push(p2.index + positionscount);
  33265. indices.push(p1.index + positionscount);
  33266. poscounter = -1;
  33267. break;
  33268. }
  33269. poscounter++;
  33270. //indices.push((<IndexedVector2>point).index + positionscount);
  33271. });
  33272. });
  33273. //Add the sides
  33274. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  33275. this._holes.forEach(function (hole) {
  33276. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  33277. });
  33278. }
  33279. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  33280. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  33281. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  33282. result.setIndices(indices);
  33283. return result;
  33284. };
  33285. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  33286. var StartIndex = positions.length / 3;
  33287. var ulength = 0;
  33288. for (var i = 0; i < points.elements.length; i++) {
  33289. var p = points.elements[i];
  33290. var p1;
  33291. if ((i + 1) > points.elements.length - 1) {
  33292. p1 = points.elements[0];
  33293. }
  33294. else {
  33295. p1 = points.elements[i + 1];
  33296. }
  33297. positions.push(p.x, 0, p.y);
  33298. positions.push(p.x, -depth, p.y);
  33299. positions.push(p1.x, 0, p1.y);
  33300. positions.push(p1.x, -depth, p1.y);
  33301. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  33302. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  33303. var v3 = v2.subtract(v1);
  33304. var v4 = new BABYLON.Vector3(0, 1, 0);
  33305. var vn = BABYLON.Vector3.Cross(v3, v4);
  33306. vn = vn.normalize();
  33307. uvs.push(ulength / bounds.width, 0);
  33308. uvs.push(ulength / bounds.width, 1);
  33309. ulength += v3.length();
  33310. uvs.push((ulength / bounds.width), 0);
  33311. uvs.push((ulength / bounds.width), 1);
  33312. if (!flip) {
  33313. normals.push(-vn.x, -vn.y, -vn.z);
  33314. normals.push(-vn.x, -vn.y, -vn.z);
  33315. normals.push(-vn.x, -vn.y, -vn.z);
  33316. normals.push(-vn.x, -vn.y, -vn.z);
  33317. indices.push(StartIndex);
  33318. indices.push(StartIndex + 1);
  33319. indices.push(StartIndex + 2);
  33320. indices.push(StartIndex + 1);
  33321. indices.push(StartIndex + 3);
  33322. indices.push(StartIndex + 2);
  33323. }
  33324. else {
  33325. normals.push(vn.x, vn.y, vn.z);
  33326. normals.push(vn.x, vn.y, vn.z);
  33327. normals.push(vn.x, vn.y, vn.z);
  33328. normals.push(vn.x, vn.y, vn.z);
  33329. indices.push(StartIndex);
  33330. indices.push(StartIndex + 2);
  33331. indices.push(StartIndex + 1);
  33332. indices.push(StartIndex + 1);
  33333. indices.push(StartIndex + 2);
  33334. indices.push(StartIndex + 3);
  33335. }
  33336. StartIndex += 4;
  33337. }
  33338. ;
  33339. };
  33340. return PolygonMeshBuilder;
  33341. })();
  33342. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  33343. })(BABYLON || (BABYLON = {}));
  33344. var BABYLON;
  33345. (function (BABYLON) {
  33346. var Octree = (function () {
  33347. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  33348. if (maxDepth === void 0) { maxDepth = 2; }
  33349. this.maxDepth = maxDepth;
  33350. this.dynamicContent = new Array();
  33351. this._maxBlockCapacity = maxBlockCapacity || 64;
  33352. this._selectionContent = new BABYLON.SmartArray(1024);
  33353. this._creationFunc = creationFunc;
  33354. }
  33355. // Methods
  33356. Octree.prototype.update = function (worldMin, worldMax, entries) {
  33357. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  33358. };
  33359. Octree.prototype.addMesh = function (entry) {
  33360. for (var index = 0; index < this.blocks.length; index++) {
  33361. var block = this.blocks[index];
  33362. block.addEntry(entry);
  33363. }
  33364. };
  33365. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  33366. this._selectionContent.reset();
  33367. for (var index = 0; index < this.blocks.length; index++) {
  33368. var block = this.blocks[index];
  33369. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  33370. }
  33371. if (allowDuplicate) {
  33372. this._selectionContent.concat(this.dynamicContent);
  33373. }
  33374. else {
  33375. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33376. }
  33377. return this._selectionContent;
  33378. };
  33379. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  33380. this._selectionContent.reset();
  33381. for (var index = 0; index < this.blocks.length; index++) {
  33382. var block = this.blocks[index];
  33383. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  33384. }
  33385. if (allowDuplicate) {
  33386. this._selectionContent.concat(this.dynamicContent);
  33387. }
  33388. else {
  33389. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33390. }
  33391. return this._selectionContent;
  33392. };
  33393. Octree.prototype.intersectsRay = function (ray) {
  33394. this._selectionContent.reset();
  33395. for (var index = 0; index < this.blocks.length; index++) {
  33396. var block = this.blocks[index];
  33397. block.intersectsRay(ray, this._selectionContent);
  33398. }
  33399. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33400. return this._selectionContent;
  33401. };
  33402. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33403. target.blocks = new Array();
  33404. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33405. // Segmenting space
  33406. for (var x = 0; x < 2; x++) {
  33407. for (var y = 0; y < 2; y++) {
  33408. for (var z = 0; z < 2; z++) {
  33409. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33410. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33411. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33412. block.addEntries(entries);
  33413. target.blocks.push(block);
  33414. }
  33415. }
  33416. }
  33417. };
  33418. Octree.CreationFuncForMeshes = function (entry, block) {
  33419. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33420. block.entries.push(entry);
  33421. }
  33422. };
  33423. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33424. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33425. block.entries.push(entry);
  33426. }
  33427. };
  33428. return Octree;
  33429. })();
  33430. BABYLON.Octree = Octree;
  33431. })(BABYLON || (BABYLON = {}));
  33432. var BABYLON;
  33433. (function (BABYLON) {
  33434. var OctreeBlock = (function () {
  33435. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33436. this.entries = new Array();
  33437. this._boundingVectors = new Array();
  33438. this._capacity = capacity;
  33439. this._depth = depth;
  33440. this._maxDepth = maxDepth;
  33441. this._creationFunc = creationFunc;
  33442. this._minPoint = minPoint;
  33443. this._maxPoint = maxPoint;
  33444. this._boundingVectors.push(minPoint.clone());
  33445. this._boundingVectors.push(maxPoint.clone());
  33446. this._boundingVectors.push(minPoint.clone());
  33447. this._boundingVectors[2].x = maxPoint.x;
  33448. this._boundingVectors.push(minPoint.clone());
  33449. this._boundingVectors[3].y = maxPoint.y;
  33450. this._boundingVectors.push(minPoint.clone());
  33451. this._boundingVectors[4].z = maxPoint.z;
  33452. this._boundingVectors.push(maxPoint.clone());
  33453. this._boundingVectors[5].z = minPoint.z;
  33454. this._boundingVectors.push(maxPoint.clone());
  33455. this._boundingVectors[6].x = minPoint.x;
  33456. this._boundingVectors.push(maxPoint.clone());
  33457. this._boundingVectors[7].y = minPoint.y;
  33458. }
  33459. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33460. // Property
  33461. get: function () {
  33462. return this._capacity;
  33463. },
  33464. enumerable: true,
  33465. configurable: true
  33466. });
  33467. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  33468. get: function () {
  33469. return this._minPoint;
  33470. },
  33471. enumerable: true,
  33472. configurable: true
  33473. });
  33474. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33475. get: function () {
  33476. return this._maxPoint;
  33477. },
  33478. enumerable: true,
  33479. configurable: true
  33480. });
  33481. // Methods
  33482. OctreeBlock.prototype.addEntry = function (entry) {
  33483. if (this.blocks) {
  33484. for (var index = 0; index < this.blocks.length; index++) {
  33485. var block = this.blocks[index];
  33486. block.addEntry(entry);
  33487. }
  33488. return;
  33489. }
  33490. this._creationFunc(entry, this);
  33491. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33492. this.createInnerBlocks();
  33493. }
  33494. };
  33495. OctreeBlock.prototype.addEntries = function (entries) {
  33496. for (var index = 0; index < entries.length; index++) {
  33497. var mesh = entries[index];
  33498. this.addEntry(mesh);
  33499. }
  33500. };
  33501. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33502. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33503. if (this.blocks) {
  33504. for (var index = 0; index < this.blocks.length; index++) {
  33505. var block = this.blocks[index];
  33506. block.select(frustumPlanes, selection, allowDuplicate);
  33507. }
  33508. return;
  33509. }
  33510. if (allowDuplicate) {
  33511. selection.concat(this.entries);
  33512. }
  33513. else {
  33514. selection.concatWithNoDuplicate(this.entries);
  33515. }
  33516. }
  33517. };
  33518. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33519. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33520. if (this.blocks) {
  33521. for (var index = 0; index < this.blocks.length; index++) {
  33522. var block = this.blocks[index];
  33523. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33524. }
  33525. return;
  33526. }
  33527. if (allowDuplicate) {
  33528. selection.concat(this.entries);
  33529. }
  33530. else {
  33531. selection.concatWithNoDuplicate(this.entries);
  33532. }
  33533. }
  33534. };
  33535. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33536. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33537. if (this.blocks) {
  33538. for (var index = 0; index < this.blocks.length; index++) {
  33539. var block = this.blocks[index];
  33540. block.intersectsRay(ray, selection);
  33541. }
  33542. return;
  33543. }
  33544. selection.concatWithNoDuplicate(this.entries);
  33545. }
  33546. };
  33547. OctreeBlock.prototype.createInnerBlocks = function () {
  33548. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33549. };
  33550. return OctreeBlock;
  33551. })();
  33552. BABYLON.OctreeBlock = OctreeBlock;
  33553. })(BABYLON || (BABYLON = {}));
  33554. var BABYLON;
  33555. (function (BABYLON) {
  33556. var BlurPostProcess = (function (_super) {
  33557. __extends(BlurPostProcess, _super);
  33558. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33559. var _this = this;
  33560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33561. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33562. this.direction = direction;
  33563. this.blurWidth = blurWidth;
  33564. this.onApply = function (effect) {
  33565. effect.setFloat2("screenSize", _this.width, _this.height);
  33566. effect.setVector2("direction", _this.direction);
  33567. effect.setFloat("blurWidth", _this.blurWidth);
  33568. };
  33569. }
  33570. return BlurPostProcess;
  33571. })(BABYLON.PostProcess);
  33572. BABYLON.BlurPostProcess = BlurPostProcess;
  33573. })(BABYLON || (BABYLON = {}));
  33574. var BABYLON;
  33575. (function (BABYLON) {
  33576. var RefractionPostProcess = (function (_super) {
  33577. __extends(RefractionPostProcess, _super);
  33578. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33579. var _this = this;
  33580. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33581. this.color = color;
  33582. this.depth = depth;
  33583. this.colorLevel = colorLevel;
  33584. this.onActivate = function (cam) {
  33585. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33586. };
  33587. this.onApply = function (effect) {
  33588. effect.setColor3("baseColor", _this.color);
  33589. effect.setFloat("depth", _this.depth);
  33590. effect.setFloat("colorLevel", _this.colorLevel);
  33591. effect.setTexture("refractionSampler", _this._refRexture);
  33592. };
  33593. }
  33594. // Methods
  33595. RefractionPostProcess.prototype.dispose = function (camera) {
  33596. if (this._refRexture) {
  33597. this._refRexture.dispose();
  33598. }
  33599. _super.prototype.dispose.call(this, camera);
  33600. };
  33601. return RefractionPostProcess;
  33602. })(BABYLON.PostProcess);
  33603. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33604. })(BABYLON || (BABYLON = {}));
  33605. var BABYLON;
  33606. (function (BABYLON) {
  33607. var BlackAndWhitePostProcess = (function (_super) {
  33608. __extends(BlackAndWhitePostProcess, _super);
  33609. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33610. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33611. }
  33612. return BlackAndWhitePostProcess;
  33613. })(BABYLON.PostProcess);
  33614. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33615. })(BABYLON || (BABYLON = {}));
  33616. var BABYLON;
  33617. (function (BABYLON) {
  33618. var ConvolutionPostProcess = (function (_super) {
  33619. __extends(ConvolutionPostProcess, _super);
  33620. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33621. var _this = this;
  33622. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33623. this.kernel = kernel;
  33624. this.onApply = function (effect) {
  33625. effect.setFloat2("screenSize", _this.width, _this.height);
  33626. effect.setArray("kernel", _this.kernel);
  33627. };
  33628. }
  33629. // Statics
  33630. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33631. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33632. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33633. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33634. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33635. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33636. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33637. return ConvolutionPostProcess;
  33638. })(BABYLON.PostProcess);
  33639. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33640. })(BABYLON || (BABYLON = {}));
  33641. var BABYLON;
  33642. (function (BABYLON) {
  33643. var FilterPostProcess = (function (_super) {
  33644. __extends(FilterPostProcess, _super);
  33645. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33646. var _this = this;
  33647. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33648. this.kernelMatrix = kernelMatrix;
  33649. this.onApply = function (effect) {
  33650. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33651. };
  33652. }
  33653. return FilterPostProcess;
  33654. })(BABYLON.PostProcess);
  33655. BABYLON.FilterPostProcess = FilterPostProcess;
  33656. })(BABYLON || (BABYLON = {}));
  33657. var BABYLON;
  33658. (function (BABYLON) {
  33659. var FxaaPostProcess = (function (_super) {
  33660. __extends(FxaaPostProcess, _super);
  33661. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33662. var _this = this;
  33663. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33664. this.onSizeChanged = function () {
  33665. _this.texelWidth = 1.0 / _this.width;
  33666. _this.texelHeight = 1.0 / _this.height;
  33667. };
  33668. this.onApply = function (effect) {
  33669. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33670. };
  33671. }
  33672. return FxaaPostProcess;
  33673. })(BABYLON.PostProcess);
  33674. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33675. })(BABYLON || (BABYLON = {}));
  33676. var BABYLON;
  33677. (function (BABYLON) {
  33678. var StereoscopicInterlacePostProcess = (function (_super) {
  33679. __extends(StereoscopicInterlacePostProcess, _super);
  33680. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33681. var _this = this;
  33682. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33683. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33684. this.onSizeChanged = function () {
  33685. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33686. };
  33687. this.onApply = function (effect) {
  33688. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33689. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33690. };
  33691. }
  33692. return StereoscopicInterlacePostProcess;
  33693. })(BABYLON.PostProcess);
  33694. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33695. })(BABYLON || (BABYLON = {}));
  33696. var BABYLON;
  33697. (function (BABYLON) {
  33698. var LensFlare = (function () {
  33699. function LensFlare(size, position, color, imgUrl, system) {
  33700. this.size = size;
  33701. this.position = position;
  33702. this.dispose = function () {
  33703. if (this.texture) {
  33704. this.texture.dispose();
  33705. }
  33706. // Remove from scene
  33707. var index = this._system.lensFlares.indexOf(this);
  33708. this._system.lensFlares.splice(index, 1);
  33709. };
  33710. this.color = color || new BABYLON.Color3(1, 1, 1);
  33711. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33712. this._system = system;
  33713. system.lensFlares.push(this);
  33714. }
  33715. return LensFlare;
  33716. })();
  33717. BABYLON.LensFlare = LensFlare;
  33718. })(BABYLON || (BABYLON = {}));
  33719. var BABYLON;
  33720. (function (BABYLON) {
  33721. var LensFlareSystem = (function () {
  33722. function LensFlareSystem(name, emitter, scene) {
  33723. this.name = name;
  33724. this.lensFlares = new Array();
  33725. this.borderLimit = 300;
  33726. this.layerMask = 0x0FFFFFFF;
  33727. this._vertexDeclaration = [2];
  33728. this._vertexStrideSize = 2 * 4;
  33729. this._isEnabled = true;
  33730. this._scene = scene;
  33731. this._emitter = emitter;
  33732. scene.lensFlareSystems.push(this);
  33733. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33734. // VBO
  33735. var vertices = [];
  33736. vertices.push(1, 1);
  33737. vertices.push(-1, 1);
  33738. vertices.push(-1, -1);
  33739. vertices.push(1, -1);
  33740. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33741. // Indices
  33742. var indices = [];
  33743. indices.push(0);
  33744. indices.push(1);
  33745. indices.push(2);
  33746. indices.push(0);
  33747. indices.push(2);
  33748. indices.push(3);
  33749. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33750. // Effects
  33751. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33752. }
  33753. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33754. get: function () {
  33755. return this._isEnabled;
  33756. },
  33757. set: function (value) {
  33758. this._isEnabled = value;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. LensFlareSystem.prototype.getScene = function () {
  33764. return this._scene;
  33765. };
  33766. LensFlareSystem.prototype.getEmitter = function () {
  33767. return this._emitter;
  33768. };
  33769. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33770. this._emitter = newEmitter;
  33771. };
  33772. LensFlareSystem.prototype.getEmitterPosition = function () {
  33773. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33774. };
  33775. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33776. var position = this.getEmitterPosition();
  33777. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33778. this._positionX = position.x;
  33779. this._positionY = position.y;
  33780. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33781. if (position.z > 0) {
  33782. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33783. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33784. return true;
  33785. }
  33786. }
  33787. return false;
  33788. };
  33789. LensFlareSystem.prototype._isVisible = function () {
  33790. if (!this._isEnabled) {
  33791. return false;
  33792. }
  33793. var emitterPosition = this.getEmitterPosition();
  33794. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33795. var distance = direction.length();
  33796. direction.normalize();
  33797. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33798. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33799. return !pickInfo.hit || pickInfo.distance > distance;
  33800. };
  33801. LensFlareSystem.prototype.render = function () {
  33802. if (!this._effect.isReady())
  33803. return false;
  33804. var engine = this._scene.getEngine();
  33805. var viewport = this._scene.activeCamera.viewport;
  33806. var globalViewport = viewport.toScreenGlobal(engine);
  33807. // Position
  33808. if (!this.computeEffectivePosition(globalViewport)) {
  33809. return false;
  33810. }
  33811. // Visibility
  33812. if (!this._isVisible()) {
  33813. return false;
  33814. }
  33815. // Intensity
  33816. var awayX;
  33817. var awayY;
  33818. if (this._positionX < this.borderLimit + globalViewport.x) {
  33819. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33820. }
  33821. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33822. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33823. }
  33824. else {
  33825. awayX = 0;
  33826. }
  33827. if (this._positionY < this.borderLimit + globalViewport.y) {
  33828. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33829. }
  33830. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33831. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33832. }
  33833. else {
  33834. awayY = 0;
  33835. }
  33836. var away = (awayX > awayY) ? awayX : awayY;
  33837. if (away > this.borderLimit) {
  33838. away = this.borderLimit;
  33839. }
  33840. var intensity = 1.0 - (away / this.borderLimit);
  33841. if (intensity < 0) {
  33842. return false;
  33843. }
  33844. if (intensity > 1.0) {
  33845. intensity = 1.0;
  33846. }
  33847. // Position
  33848. var centerX = globalViewport.x + globalViewport.width / 2;
  33849. var centerY = globalViewport.y + globalViewport.height / 2;
  33850. var distX = centerX - this._positionX;
  33851. var distY = centerY - this._positionY;
  33852. // Effects
  33853. engine.enableEffect(this._effect);
  33854. engine.setState(false);
  33855. engine.setDepthBuffer(false);
  33856. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33857. // VBOs
  33858. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33859. // Flares
  33860. for (var index = 0; index < this.lensFlares.length; index++) {
  33861. var flare = this.lensFlares[index];
  33862. var x = centerX - (distX * flare.position);
  33863. var y = centerY - (distY * flare.position);
  33864. var cw = flare.size;
  33865. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33866. var cx = 2 * (x / globalViewport.width) - 1.0;
  33867. var cy = 1.0 - 2 * (y / globalViewport.height);
  33868. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33869. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33870. // Texture
  33871. this._effect.setTexture("textureSampler", flare.texture);
  33872. // Color
  33873. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33874. // Draw order
  33875. engine.draw(true, 0, 6);
  33876. }
  33877. engine.setDepthBuffer(true);
  33878. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33879. return true;
  33880. };
  33881. LensFlareSystem.prototype.dispose = function () {
  33882. if (this._vertexBuffer) {
  33883. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33884. this._vertexBuffer = null;
  33885. }
  33886. if (this._indexBuffer) {
  33887. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33888. this._indexBuffer = null;
  33889. }
  33890. while (this.lensFlares.length) {
  33891. this.lensFlares[0].dispose();
  33892. }
  33893. // Remove from scene
  33894. var index = this._scene.lensFlareSystems.indexOf(this);
  33895. this._scene.lensFlareSystems.splice(index, 1);
  33896. };
  33897. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33898. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33899. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33900. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33901. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33902. var parsedFlare = parsedLensFlareSystem.flares[index];
  33903. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33904. }
  33905. return lensFlareSystem;
  33906. };
  33907. LensFlareSystem.prototype.serialize = function () {
  33908. var serializationObject = {};
  33909. serializationObject.emitterId = this.getEmitter().id;
  33910. serializationObject.borderLimit = this.borderLimit;
  33911. serializationObject.flares = [];
  33912. for (var index = 0; index < this.lensFlares.length; index++) {
  33913. var flare = this.lensFlares[index];
  33914. serializationObject.flares.push({
  33915. size: flare.size,
  33916. position: flare.position,
  33917. color: flare.color.asArray(),
  33918. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33919. });
  33920. }
  33921. return serializationObject;
  33922. };
  33923. return LensFlareSystem;
  33924. })();
  33925. BABYLON.LensFlareSystem = LensFlareSystem;
  33926. })(BABYLON || (BABYLON = {}));
  33927. var BABYLON;
  33928. (function (BABYLON) {
  33929. // We're mainly based on the logic defined into the FreeCamera code
  33930. var DeviceOrientationCamera = (function (_super) {
  33931. __extends(DeviceOrientationCamera, _super);
  33932. function DeviceOrientationCamera(name, position, scene) {
  33933. var _this = this;
  33934. _super.call(this, name, position, scene);
  33935. this._offsetX = null;
  33936. this._offsetY = null;
  33937. this._orientationGamma = 0;
  33938. this._orientationBeta = 0;
  33939. this._initialOrientationGamma = 0;
  33940. this._initialOrientationBeta = 0;
  33941. this.angularSensibility = 10000.0;
  33942. this.moveSensibility = 50.0;
  33943. window.addEventListener("resize", function () {
  33944. _this._initialOrientationGamma = null;
  33945. }, false);
  33946. }
  33947. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33948. var _this = this;
  33949. if (this._attachedCanvas) {
  33950. return;
  33951. }
  33952. this._attachedCanvas = canvas;
  33953. if (!this._orientationChanged) {
  33954. this._orientationChanged = function (evt) {
  33955. if (!_this._initialOrientationGamma) {
  33956. _this._initialOrientationGamma = evt.gamma;
  33957. _this._initialOrientationBeta = evt.beta;
  33958. }
  33959. _this._orientationGamma = evt.gamma;
  33960. _this._orientationBeta = evt.beta;
  33961. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33962. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33963. };
  33964. }
  33965. window.addEventListener("deviceorientation", this._orientationChanged);
  33966. };
  33967. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33968. if (this._attachedCanvas !== canvas) {
  33969. return;
  33970. }
  33971. window.removeEventListener("deviceorientation", this._orientationChanged);
  33972. this._attachedCanvas = null;
  33973. this._orientationGamma = 0;
  33974. this._orientationBeta = 0;
  33975. this._initialOrientationGamma = 0;
  33976. this._initialOrientationBeta = 0;
  33977. };
  33978. DeviceOrientationCamera.prototype._checkInputs = function () {
  33979. if (!this._offsetX) {
  33980. return;
  33981. }
  33982. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33983. var speed = this._computeLocalCameraSpeed();
  33984. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33985. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33986. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33987. _super.prototype._checkInputs.call(this);
  33988. };
  33989. return DeviceOrientationCamera;
  33990. })(BABYLON.FreeCamera);
  33991. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33992. })(BABYLON || (BABYLON = {}));
  33993. var BABYLON;
  33994. (function (BABYLON) {
  33995. var Analyser = (function () {
  33996. function Analyser(scene) {
  33997. this.SMOOTHING = 0.75;
  33998. this.FFT_SIZE = 512;
  33999. this.BARGRAPHAMPLITUDE = 256;
  34000. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34001. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34002. this._scene = scene;
  34003. this._audioEngine = BABYLON.Engine.audioEngine;
  34004. if (this._audioEngine.canUseWebAudio) {
  34005. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34006. this._webAudioAnalyser.minDecibels = -140;
  34007. this._webAudioAnalyser.maxDecibels = 0;
  34008. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34009. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34010. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34011. }
  34012. }
  34013. Analyser.prototype.getFrequencyBinCount = function () {
  34014. if (this._audioEngine.canUseWebAudio) {
  34015. return this._webAudioAnalyser.frequencyBinCount;
  34016. }
  34017. else {
  34018. return 0;
  34019. }
  34020. };
  34021. Analyser.prototype.getByteFrequencyData = function () {
  34022. if (this._audioEngine.canUseWebAudio) {
  34023. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34024. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34025. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34026. }
  34027. return this._byteFreqs;
  34028. };
  34029. Analyser.prototype.getByteTimeDomainData = function () {
  34030. if (this._audioEngine.canUseWebAudio) {
  34031. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34032. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34033. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34034. }
  34035. return this._byteTime;
  34036. };
  34037. Analyser.prototype.getFloatFrequencyData = function () {
  34038. if (this._audioEngine.canUseWebAudio) {
  34039. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34040. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34041. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34042. }
  34043. return this._floatFreqs;
  34044. };
  34045. Analyser.prototype.drawDebugCanvas = function () {
  34046. var _this = this;
  34047. if (this._audioEngine.canUseWebAudio) {
  34048. if (!this._debugCanvas) {
  34049. this._debugCanvas = document.createElement("canvas");
  34050. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34051. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34052. this._debugCanvas.style.position = "absolute";
  34053. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34054. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34055. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34056. document.body.appendChild(this._debugCanvas);
  34057. this._registerFunc = function () {
  34058. _this.drawDebugCanvas();
  34059. };
  34060. this._scene.registerBeforeRender(this._registerFunc);
  34061. }
  34062. if (this._registerFunc) {
  34063. var workingArray = this.getByteFrequencyData();
  34064. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34065. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34066. // Draw the frequency domain chart.
  34067. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34068. var value = workingArray[i];
  34069. var percent = value / this.BARGRAPHAMPLITUDE;
  34070. var height = this.DEBUGCANVASSIZE.height * percent;
  34071. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34072. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34073. var hue = i / this.getFrequencyBinCount() * 360;
  34074. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34075. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34076. }
  34077. }
  34078. }
  34079. };
  34080. Analyser.prototype.stopDebugCanvas = function () {
  34081. if (this._debugCanvas) {
  34082. this._scene.unregisterBeforeRender(this._registerFunc);
  34083. this._registerFunc = null;
  34084. document.body.removeChild(this._debugCanvas);
  34085. this._debugCanvas = null;
  34086. this._debugCanvasContext = null;
  34087. }
  34088. };
  34089. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34090. if (this._audioEngine.canUseWebAudio) {
  34091. inputAudioNode.connect(this._webAudioAnalyser);
  34092. this._webAudioAnalyser.connect(outputAudioNode);
  34093. }
  34094. };
  34095. Analyser.prototype.dispose = function () {
  34096. if (this._audioEngine.canUseWebAudio) {
  34097. this._webAudioAnalyser.disconnect();
  34098. }
  34099. };
  34100. return Analyser;
  34101. })();
  34102. BABYLON.Analyser = Analyser;
  34103. })(BABYLON || (BABYLON = {}));
  34104. var BABYLON;
  34105. (function (BABYLON) {
  34106. var AudioEngine = (function () {
  34107. function AudioEngine() {
  34108. this._audioContext = null;
  34109. this._audioContextInitialized = false;
  34110. this.canUseWebAudio = false;
  34111. this.WarnedWebAudioUnsupported = false;
  34112. this.unlocked = false;
  34113. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34114. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34115. this.canUseWebAudio = true;
  34116. }
  34117. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34118. this._unlockiOSaudio();
  34119. }
  34120. else {
  34121. this.unlocked = true;
  34122. }
  34123. }
  34124. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34125. get: function () {
  34126. if (!this._audioContextInitialized) {
  34127. this._initializeAudioContext();
  34128. }
  34129. return this._audioContext;
  34130. },
  34131. enumerable: true,
  34132. configurable: true
  34133. });
  34134. AudioEngine.prototype._unlockiOSaudio = function () {
  34135. var _this = this;
  34136. var unlockaudio = function () {
  34137. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34138. var source = _this.audioContext.createBufferSource();
  34139. source.buffer = buffer;
  34140. source.connect(_this.audioContext.destination);
  34141. source.start(0);
  34142. setTimeout(function () {
  34143. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34144. _this.unlocked = true;
  34145. window.removeEventListener('touchend', unlockaudio, false);
  34146. if (_this.onAudioUnlocked) {
  34147. _this.onAudioUnlocked();
  34148. }
  34149. }
  34150. }, 0);
  34151. };
  34152. window.addEventListener('touchend', unlockaudio, false);
  34153. };
  34154. AudioEngine.prototype._initializeAudioContext = function () {
  34155. try {
  34156. if (this.canUseWebAudio) {
  34157. this._audioContext = new AudioContext();
  34158. // create a global volume gain node
  34159. this.masterGain = this._audioContext.createGain();
  34160. this.masterGain.gain.value = 1;
  34161. this.masterGain.connect(this._audioContext.destination);
  34162. this._audioContextInitialized = true;
  34163. }
  34164. }
  34165. catch (e) {
  34166. this.canUseWebAudio = false;
  34167. BABYLON.Tools.Error("Web Audio: " + e.message);
  34168. }
  34169. };
  34170. AudioEngine.prototype.dispose = function () {
  34171. if (this.canUseWebAudio && this._audioContextInitialized) {
  34172. if (this._connectedAnalyser) {
  34173. this._connectedAnalyser.stopDebugCanvas();
  34174. this._connectedAnalyser.dispose();
  34175. this.masterGain.disconnect();
  34176. this.masterGain.connect(this._audioContext.destination);
  34177. this._connectedAnalyser = null;
  34178. }
  34179. this.masterGain.gain.value = 1;
  34180. }
  34181. this.WarnedWebAudioUnsupported = false;
  34182. };
  34183. AudioEngine.prototype.getGlobalVolume = function () {
  34184. if (this.canUseWebAudio && this._audioContextInitialized) {
  34185. return this.masterGain.gain.value;
  34186. }
  34187. else {
  34188. return -1;
  34189. }
  34190. };
  34191. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34192. if (this.canUseWebAudio && this._audioContextInitialized) {
  34193. this.masterGain.gain.value = newVolume;
  34194. }
  34195. };
  34196. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34197. if (this._connectedAnalyser) {
  34198. this._connectedAnalyser.stopDebugCanvas();
  34199. }
  34200. if (this.canUseWebAudio && this._audioContextInitialized) {
  34201. this._connectedAnalyser = analyser;
  34202. this.masterGain.disconnect();
  34203. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34204. }
  34205. };
  34206. return AudioEngine;
  34207. })();
  34208. BABYLON.AudioEngine = AudioEngine;
  34209. })(BABYLON || (BABYLON = {}));
  34210. var BABYLON;
  34211. (function (BABYLON) {
  34212. var Sound = (function () {
  34213. /**
  34214. * Create a sound and attach it to a scene
  34215. * @param name Name of your sound
  34216. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34217. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34218. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34219. */
  34220. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34221. var _this = this;
  34222. this.autoplay = false;
  34223. this.loop = false;
  34224. this.useCustomAttenuation = false;
  34225. this.spatialSound = false;
  34226. this.refDistance = 1;
  34227. this.rolloffFactor = 1;
  34228. this.maxDistance = 100;
  34229. this.distanceModel = "linear";
  34230. this._panningModel = "equalpower";
  34231. this._playbackRate = 1;
  34232. this._streaming = false;
  34233. this._startTime = 0;
  34234. this._startOffset = 0;
  34235. this._position = BABYLON.Vector3.Zero();
  34236. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34237. this._volume = 1;
  34238. this._isLoaded = false;
  34239. this._isReadyToPlay = false;
  34240. this.isPlaying = false;
  34241. this.isPaused = false;
  34242. this._isDirectional = false;
  34243. // Used if you'd like to create a directional sound.
  34244. // If not set, the sound will be omnidirectional
  34245. this._coneInnerAngle = 360;
  34246. this._coneOuterAngle = 360;
  34247. this._coneOuterGain = 0;
  34248. this._isOutputConnected = false;
  34249. this.name = name;
  34250. this._scene = scene;
  34251. this._readyToPlayCallback = readyToPlayCallback;
  34252. // Default custom attenuation function is a linear attenuation
  34253. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34254. if (currentDistance < maxDistance) {
  34255. return currentVolume * (1 - currentDistance / maxDistance);
  34256. }
  34257. else {
  34258. return 0;
  34259. }
  34260. };
  34261. if (options) {
  34262. this.autoplay = options.autoplay || false;
  34263. this.loop = options.loop || false;
  34264. // if volume === 0, we need another way to check this option
  34265. if (options.volume !== undefined) {
  34266. this._volume = options.volume;
  34267. }
  34268. this.spatialSound = options.spatialSound || false;
  34269. this.maxDistance = options.maxDistance || 100;
  34270. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34271. this.rolloffFactor = options.rolloffFactor || 1;
  34272. this.refDistance = options.refDistance || 1;
  34273. this.distanceModel = options.distanceModel || "linear";
  34274. this._playbackRate = options.playbackRate || 1;
  34275. this._streaming = options.streaming || false;
  34276. }
  34277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34278. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34279. this._soundGain.gain.value = this._volume;
  34280. this._inputAudioNode = this._soundGain;
  34281. this._ouputAudioNode = this._soundGain;
  34282. if (this.spatialSound) {
  34283. this._createSpatialParameters();
  34284. }
  34285. this._scene.mainSoundTrack.AddSound(this);
  34286. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34287. if (urlOrArrayBuffer) {
  34288. // If it's an URL
  34289. if (typeof (urlOrArrayBuffer) === "string") {
  34290. // Loading sound using XHR2
  34291. if (!this._streaming) {
  34292. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34293. }
  34294. else {
  34295. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34296. this._htmlAudioElement.controls = false;
  34297. this._htmlAudioElement.loop = this.loop;
  34298. this._htmlAudioElement.crossOrigin = "anonymous";
  34299. this._htmlAudioElement.preload = "auto";
  34300. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34301. _this._isReadyToPlay = true;
  34302. if (_this.autoplay) {
  34303. _this.play();
  34304. }
  34305. if (_this._readyToPlayCallback) {
  34306. _this._readyToPlayCallback();
  34307. }
  34308. });
  34309. document.body.appendChild(this._htmlAudioElement);
  34310. }
  34311. }
  34312. else {
  34313. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34314. if (urlOrArrayBuffer.byteLength > 0) {
  34315. this._soundLoaded(urlOrArrayBuffer);
  34316. }
  34317. }
  34318. else {
  34319. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34320. }
  34321. }
  34322. }
  34323. }
  34324. else {
  34325. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34326. this._scene.mainSoundTrack.AddSound(this);
  34327. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34328. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34329. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34330. }
  34331. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34332. if (this._readyToPlayCallback) {
  34333. window.setTimeout(function () {
  34334. _this._readyToPlayCallback();
  34335. }, 1000);
  34336. }
  34337. }
  34338. }
  34339. Sound.prototype.dispose = function () {
  34340. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34341. if (this.isPlaying) {
  34342. this.stop();
  34343. }
  34344. this._isReadyToPlay = false;
  34345. if (this.soundTrackId === -1) {
  34346. this._scene.mainSoundTrack.RemoveSound(this);
  34347. }
  34348. else {
  34349. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34350. }
  34351. if (this._soundGain) {
  34352. this._soundGain.disconnect();
  34353. this._soundGain = null;
  34354. }
  34355. if (this._soundPanner) {
  34356. this._soundPanner.disconnect();
  34357. this._soundPanner = null;
  34358. }
  34359. if (this._soundSource) {
  34360. this._soundSource.disconnect();
  34361. this._soundSource = null;
  34362. }
  34363. this._audioBuffer = null;
  34364. if (this._htmlAudioElement) {
  34365. this._htmlAudioElement.pause();
  34366. this._htmlAudioElement.src = "";
  34367. document.body.removeChild(this._htmlAudioElement);
  34368. }
  34369. if (this._connectedMesh) {
  34370. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34371. this._connectedMesh = null;
  34372. }
  34373. }
  34374. };
  34375. Sound.prototype._soundLoaded = function (audioData) {
  34376. var _this = this;
  34377. this._isLoaded = true;
  34378. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34379. _this._audioBuffer = buffer;
  34380. _this._isReadyToPlay = true;
  34381. if (_this.autoplay) {
  34382. _this.play();
  34383. }
  34384. if (_this._readyToPlayCallback) {
  34385. _this._readyToPlayCallback();
  34386. }
  34387. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34388. };
  34389. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34391. this._audioBuffer = audioBuffer;
  34392. this._isReadyToPlay = true;
  34393. }
  34394. };
  34395. Sound.prototype.updateOptions = function (options) {
  34396. if (options) {
  34397. this.loop = options.loop || this.loop;
  34398. this.maxDistance = options.maxDistance || this.maxDistance;
  34399. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34400. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34401. this.refDistance = options.refDistance || this.refDistance;
  34402. this.distanceModel = options.distanceModel || this.distanceModel;
  34403. this._playbackRate = options.playbackRate || this._playbackRate;
  34404. this._updateSpatialParameters();
  34405. if (this.isPlaying) {
  34406. if (this._streaming) {
  34407. this._htmlAudioElement.playbackRate = this._playbackRate;
  34408. }
  34409. else {
  34410. this._soundSource.playbackRate.value = this._playbackRate;
  34411. }
  34412. }
  34413. }
  34414. };
  34415. Sound.prototype._createSpatialParameters = function () {
  34416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34417. if (this._scene.headphone) {
  34418. this._panningModel = "HRTF";
  34419. }
  34420. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34421. this._updateSpatialParameters();
  34422. this._soundPanner.connect(this._ouputAudioNode);
  34423. this._inputAudioNode = this._soundPanner;
  34424. }
  34425. };
  34426. Sound.prototype._updateSpatialParameters = function () {
  34427. if (this.spatialSound) {
  34428. if (this.useCustomAttenuation) {
  34429. // Tricks to disable in a way embedded Web Audio attenuation
  34430. this._soundPanner.distanceModel = "linear";
  34431. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34432. this._soundPanner.refDistance = 1;
  34433. this._soundPanner.rolloffFactor = 1;
  34434. this._soundPanner.panningModel = this._panningModel;
  34435. }
  34436. else {
  34437. this._soundPanner.distanceModel = this.distanceModel;
  34438. this._soundPanner.maxDistance = this.maxDistance;
  34439. this._soundPanner.refDistance = this.refDistance;
  34440. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34441. this._soundPanner.panningModel = this._panningModel;
  34442. }
  34443. }
  34444. };
  34445. Sound.prototype.switchPanningModelToHRTF = function () {
  34446. this._panningModel = "HRTF";
  34447. this._switchPanningModel();
  34448. };
  34449. Sound.prototype.switchPanningModelToEqualPower = function () {
  34450. this._panningModel = "equalpower";
  34451. this._switchPanningModel();
  34452. };
  34453. Sound.prototype._switchPanningModel = function () {
  34454. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34455. this._soundPanner.panningModel = this._panningModel;
  34456. }
  34457. };
  34458. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34459. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34460. if (this._isOutputConnected) {
  34461. this._ouputAudioNode.disconnect();
  34462. }
  34463. this._ouputAudioNode.connect(soundTrackAudioNode);
  34464. this._isOutputConnected = true;
  34465. }
  34466. };
  34467. /**
  34468. * Transform this sound into a directional source
  34469. * @param coneInnerAngle Size of the inner cone in degree
  34470. * @param coneOuterAngle Size of the outer cone in degree
  34471. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34472. */
  34473. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34474. if (coneOuterAngle < coneInnerAngle) {
  34475. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34476. return;
  34477. }
  34478. this._coneInnerAngle = coneInnerAngle;
  34479. this._coneOuterAngle = coneOuterAngle;
  34480. this._coneOuterGain = coneOuterGain;
  34481. this._isDirectional = true;
  34482. if (this.isPlaying && this.loop) {
  34483. this.stop();
  34484. this.play();
  34485. }
  34486. };
  34487. Sound.prototype.setPosition = function (newPosition) {
  34488. this._position = newPosition;
  34489. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34490. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34491. }
  34492. };
  34493. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34494. this._localDirection = newLocalDirection;
  34495. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34496. this._updateDirection();
  34497. }
  34498. };
  34499. Sound.prototype._updateDirection = function () {
  34500. var mat = this._connectedMesh.getWorldMatrix();
  34501. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34502. direction.normalize();
  34503. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34504. };
  34505. Sound.prototype.updateDistanceFromListener = function () {
  34506. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34507. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34508. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34509. }
  34510. };
  34511. Sound.prototype.setAttenuationFunction = function (callback) {
  34512. this._customAttenuationFunction = callback;
  34513. };
  34514. /**
  34515. * Play the sound
  34516. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34517. */
  34518. Sound.prototype.play = function (time) {
  34519. var _this = this;
  34520. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34521. try {
  34522. if (this._startOffset < 0) {
  34523. time = -this._startOffset;
  34524. this._startOffset = 0;
  34525. }
  34526. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34527. if (!this._soundSource || !this._streamingSource) {
  34528. if (this.spatialSound) {
  34529. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34530. if (this._isDirectional) {
  34531. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34532. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34533. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34534. if (this._connectedMesh) {
  34535. this._updateDirection();
  34536. }
  34537. else {
  34538. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34539. }
  34540. }
  34541. }
  34542. }
  34543. if (this._streaming) {
  34544. if (!this._streamingSource) {
  34545. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34546. this._htmlAudioElement.onended = function () { _this._onended(); };
  34547. this._htmlAudioElement.playbackRate = this._playbackRate;
  34548. }
  34549. this._streamingSource.disconnect();
  34550. this._streamingSource.connect(this._inputAudioNode);
  34551. this._htmlAudioElement.play();
  34552. }
  34553. else {
  34554. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34555. this._soundSource.buffer = this._audioBuffer;
  34556. this._soundSource.connect(this._inputAudioNode);
  34557. this._soundSource.loop = this.loop;
  34558. this._soundSource.playbackRate.value = this._playbackRate;
  34559. this._soundSource.onended = function () { _this._onended(); };
  34560. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34561. }
  34562. this._startTime = startTime;
  34563. this.isPlaying = true;
  34564. this.isPaused = false;
  34565. }
  34566. catch (ex) {
  34567. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34568. }
  34569. }
  34570. };
  34571. Sound.prototype._onended = function () {
  34572. this.isPlaying = false;
  34573. if (this.onended) {
  34574. this.onended();
  34575. }
  34576. };
  34577. /**
  34578. * Stop the sound
  34579. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34580. */
  34581. Sound.prototype.stop = function (time) {
  34582. if (this.isPlaying) {
  34583. if (this._streaming) {
  34584. this._htmlAudioElement.pause();
  34585. // Test needed for Firefox or it will generate an Invalid State Error
  34586. if (this._htmlAudioElement.currentTime > 0) {
  34587. this._htmlAudioElement.currentTime = 0;
  34588. }
  34589. }
  34590. else {
  34591. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34592. this._soundSource.stop(stopTime);
  34593. if (!this.isPaused) {
  34594. this._startOffset = 0;
  34595. }
  34596. }
  34597. this.isPlaying = false;
  34598. }
  34599. };
  34600. Sound.prototype.pause = function () {
  34601. if (this.isPlaying) {
  34602. this.isPaused = true;
  34603. if (this._streaming) {
  34604. this._htmlAudioElement.pause();
  34605. }
  34606. else {
  34607. this.stop(0);
  34608. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34609. }
  34610. }
  34611. };
  34612. Sound.prototype.setVolume = function (newVolume, time) {
  34613. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34614. if (time) {
  34615. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34616. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34617. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34618. }
  34619. else {
  34620. this._soundGain.gain.value = newVolume;
  34621. }
  34622. }
  34623. this._volume = newVolume;
  34624. };
  34625. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34626. this._playbackRate = newPlaybackRate;
  34627. if (this.isPlaying) {
  34628. if (this._streaming) {
  34629. this._htmlAudioElement.playbackRate = this._playbackRate;
  34630. }
  34631. else {
  34632. this._soundSource.playbackRate.value = this._playbackRate;
  34633. }
  34634. }
  34635. };
  34636. Sound.prototype.getVolume = function () {
  34637. return this._volume;
  34638. };
  34639. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34640. var _this = this;
  34641. if (this._connectedMesh) {
  34642. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34643. this._registerFunc = null;
  34644. }
  34645. this._connectedMesh = meshToConnectTo;
  34646. if (!this.spatialSound) {
  34647. this.spatialSound = true;
  34648. this._createSpatialParameters();
  34649. if (this.isPlaying && this.loop) {
  34650. this.stop();
  34651. this.play();
  34652. }
  34653. }
  34654. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34655. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34656. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34657. };
  34658. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34659. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34660. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34661. this._updateDirection();
  34662. }
  34663. };
  34664. Sound.prototype.clone = function () {
  34665. var _this = this;
  34666. if (!this._streaming) {
  34667. var setBufferAndRun = function () {
  34668. if (_this._isReadyToPlay) {
  34669. clonedSound._audioBuffer = _this.getAudioBuffer();
  34670. clonedSound._isReadyToPlay = true;
  34671. if (clonedSound.autoplay) {
  34672. clonedSound.play();
  34673. }
  34674. }
  34675. else {
  34676. window.setTimeout(setBufferAndRun, 300);
  34677. }
  34678. };
  34679. var currentOptions = {
  34680. autoplay: this.autoplay, loop: this.loop,
  34681. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34682. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34683. refDistance: this.refDistance, distanceModel: this.distanceModel
  34684. };
  34685. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34686. if (this.useCustomAttenuation) {
  34687. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34688. }
  34689. clonedSound.setPosition(this._position);
  34690. clonedSound.setPlaybackRate(this._playbackRate);
  34691. setBufferAndRun();
  34692. return clonedSound;
  34693. }
  34694. else {
  34695. return null;
  34696. }
  34697. };
  34698. Sound.prototype.getAudioBuffer = function () {
  34699. return this._audioBuffer;
  34700. };
  34701. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34702. var soundName = parsedSound.name;
  34703. var soundUrl;
  34704. if (parsedSound.url) {
  34705. soundUrl = rootUrl + parsedSound.url;
  34706. }
  34707. else {
  34708. soundUrl = rootUrl + soundName;
  34709. }
  34710. var options = {
  34711. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34712. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34713. rolloffFactor: parsedSound.rolloffFactor,
  34714. refDistance: parsedSound.refDistance,
  34715. distanceModel: parsedSound.distanceModel,
  34716. playbackRate: parsedSound.playbackRate
  34717. };
  34718. var newSound;
  34719. if (!sourceSound) {
  34720. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34721. scene._addPendingData(newSound);
  34722. }
  34723. else {
  34724. var setBufferAndRun = function () {
  34725. if (sourceSound._isReadyToPlay) {
  34726. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34727. newSound._isReadyToPlay = true;
  34728. if (newSound.autoplay) {
  34729. newSound.play();
  34730. }
  34731. }
  34732. else {
  34733. window.setTimeout(setBufferAndRun, 300);
  34734. }
  34735. };
  34736. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34737. setBufferAndRun();
  34738. }
  34739. if (parsedSound.position) {
  34740. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34741. newSound.setPosition(soundPosition);
  34742. }
  34743. if (parsedSound.isDirectional) {
  34744. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34745. if (parsedSound.localDirectionToMesh) {
  34746. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34747. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34748. }
  34749. }
  34750. if (parsedSound.connectedMeshId) {
  34751. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34752. if (connectedMesh) {
  34753. newSound.attachToMesh(connectedMesh);
  34754. }
  34755. }
  34756. return newSound;
  34757. };
  34758. return Sound;
  34759. })();
  34760. BABYLON.Sound = Sound;
  34761. })(BABYLON || (BABYLON = {}));
  34762. var BABYLON;
  34763. (function (BABYLON) {
  34764. var SoundTrack = (function () {
  34765. function SoundTrack(scene, options) {
  34766. this.id = -1;
  34767. this._isMainTrack = false;
  34768. this._isInitialized = false;
  34769. this._scene = scene;
  34770. this.soundCollection = new Array();
  34771. this._options = options;
  34772. if (!this._isMainTrack) {
  34773. this._scene.soundTracks.push(this);
  34774. this.id = this._scene.soundTracks.length - 1;
  34775. }
  34776. }
  34777. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34779. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34780. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34781. if (this._options) {
  34782. if (this._options.volume) {
  34783. this._outputAudioNode.gain.value = this._options.volume;
  34784. }
  34785. if (this._options.mainTrack) {
  34786. this._isMainTrack = this._options.mainTrack;
  34787. }
  34788. }
  34789. this._isInitialized = true;
  34790. }
  34791. };
  34792. SoundTrack.prototype.dispose = function () {
  34793. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34794. if (this._connectedAnalyser) {
  34795. this._connectedAnalyser.stopDebugCanvas();
  34796. }
  34797. while (this.soundCollection.length) {
  34798. this.soundCollection[0].dispose();
  34799. }
  34800. if (this._outputAudioNode) {
  34801. this._outputAudioNode.disconnect();
  34802. }
  34803. this._outputAudioNode = null;
  34804. }
  34805. };
  34806. SoundTrack.prototype.AddSound = function (sound) {
  34807. if (!this._isInitialized) {
  34808. this._initializeSoundTrackAudioGraph();
  34809. }
  34810. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34811. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34812. }
  34813. if (sound.soundTrackId) {
  34814. if (sound.soundTrackId === -1) {
  34815. this._scene.mainSoundTrack.RemoveSound(sound);
  34816. }
  34817. else {
  34818. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34819. }
  34820. }
  34821. this.soundCollection.push(sound);
  34822. sound.soundTrackId = this.id;
  34823. };
  34824. SoundTrack.prototype.RemoveSound = function (sound) {
  34825. var index = this.soundCollection.indexOf(sound);
  34826. if (index !== -1) {
  34827. this.soundCollection.splice(index, 1);
  34828. }
  34829. };
  34830. SoundTrack.prototype.setVolume = function (newVolume) {
  34831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34832. this._outputAudioNode.gain.value = newVolume;
  34833. }
  34834. };
  34835. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34836. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34837. for (var i = 0; i < this.soundCollection.length; i++) {
  34838. this.soundCollection[i].switchPanningModelToHRTF();
  34839. }
  34840. }
  34841. };
  34842. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34843. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34844. for (var i = 0; i < this.soundCollection.length; i++) {
  34845. this.soundCollection[i].switchPanningModelToEqualPower();
  34846. }
  34847. }
  34848. };
  34849. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34850. if (this._connectedAnalyser) {
  34851. this._connectedAnalyser.stopDebugCanvas();
  34852. }
  34853. this._connectedAnalyser = analyser;
  34854. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34855. this._outputAudioNode.disconnect();
  34856. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34857. }
  34858. };
  34859. return SoundTrack;
  34860. })();
  34861. BABYLON.SoundTrack = SoundTrack;
  34862. })(BABYLON || (BABYLON = {}));
  34863. var BABYLON;
  34864. (function (BABYLON) {
  34865. var DepthRenderer = (function () {
  34866. function DepthRenderer(scene, type) {
  34867. var _this = this;
  34868. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34869. this._viewMatrix = BABYLON.Matrix.Zero();
  34870. this._projectionMatrix = BABYLON.Matrix.Zero();
  34871. this._transformMatrix = BABYLON.Matrix.Zero();
  34872. this._worldViewProjection = BABYLON.Matrix.Zero();
  34873. this._scene = scene;
  34874. var engine = scene.getEngine();
  34875. // Render target
  34876. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34877. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34878. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34879. this._depthMap.refreshRate = 1;
  34880. this._depthMap.renderParticles = false;
  34881. this._depthMap.renderList = null;
  34882. // set default depth value to 1.0 (far away)
  34883. this._depthMap.onClear = function (engine) {
  34884. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34885. };
  34886. // Custom render function
  34887. var renderSubMesh = function (subMesh) {
  34888. var mesh = subMesh.getRenderingMesh();
  34889. var scene = _this._scene;
  34890. var engine = scene.getEngine();
  34891. // Culling
  34892. engine.setState(subMesh.getMaterial().backFaceCulling);
  34893. // Managing instances
  34894. var batch = mesh._getInstancesRenderList(subMesh._id);
  34895. if (batch.mustReturn) {
  34896. return;
  34897. }
  34898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34899. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34900. engine.enableEffect(_this._effect);
  34901. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34902. var material = subMesh.getMaterial();
  34903. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34904. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34905. // Alpha test
  34906. if (material && material.needAlphaTesting()) {
  34907. var alphaTexture = material.getAlphaTestTexture();
  34908. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34909. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34910. }
  34911. // Bones
  34912. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34913. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34914. }
  34915. // Draw
  34916. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34917. }
  34918. };
  34919. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34920. var index;
  34921. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34922. renderSubMesh(opaqueSubMeshes.data[index]);
  34923. }
  34924. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34925. renderSubMesh(alphaTestSubMeshes.data[index]);
  34926. }
  34927. };
  34928. }
  34929. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34930. var defines = [];
  34931. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34932. var mesh = subMesh.getMesh();
  34933. var scene = mesh.getScene();
  34934. var material = subMesh.getMaterial();
  34935. // Alpha test
  34936. if (material && material.needAlphaTesting()) {
  34937. defines.push("#define ALPHATEST");
  34938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34939. attribs.push(BABYLON.VertexBuffer.UVKind);
  34940. defines.push("#define UV1");
  34941. }
  34942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34944. defines.push("#define UV2");
  34945. }
  34946. }
  34947. // Bones
  34948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34951. if (mesh.numBoneInfluencers > 4) {
  34952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34954. }
  34955. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34956. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34957. }
  34958. else {
  34959. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34960. }
  34961. // Instances
  34962. if (useInstances) {
  34963. defines.push("#define INSTANCES");
  34964. attribs.push("world0");
  34965. attribs.push("world1");
  34966. attribs.push("world2");
  34967. attribs.push("world3");
  34968. }
  34969. // Get correct effect
  34970. var join = defines.join("\n");
  34971. if (this._cachedDefines !== join) {
  34972. this._cachedDefines = join;
  34973. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34974. }
  34975. return this._effect.isReady();
  34976. };
  34977. DepthRenderer.prototype.getDepthMap = function () {
  34978. return this._depthMap;
  34979. };
  34980. // Methods
  34981. DepthRenderer.prototype.dispose = function () {
  34982. this._depthMap.dispose();
  34983. };
  34984. return DepthRenderer;
  34985. })();
  34986. BABYLON.DepthRenderer = DepthRenderer;
  34987. })(BABYLON || (BABYLON = {}));
  34988. var BABYLON;
  34989. (function (BABYLON) {
  34990. var SSAORenderingPipeline = (function (_super) {
  34991. __extends(SSAORenderingPipeline, _super);
  34992. /**
  34993. * @constructor
  34994. * @param {string} name - The rendering pipeline name
  34995. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34996. * @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 }
  34997. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34998. */
  34999. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35000. var _this = this;
  35001. _super.call(this, scene.getEngine(), name);
  35002. // Members
  35003. /**
  35004. * The PassPostProcess id in the pipeline that contains the original scene color
  35005. * @type {string}
  35006. */
  35007. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35008. /**
  35009. * The SSAO PostProcess id in the pipeline
  35010. * @type {string}
  35011. */
  35012. this.SSAORenderEffect = "SSAORenderEffect";
  35013. /**
  35014. * The horizontal blur PostProcess id in the pipeline
  35015. * @type {string}
  35016. */
  35017. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35018. /**
  35019. * The vertical blur PostProcess id in the pipeline
  35020. * @type {string}
  35021. */
  35022. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35023. /**
  35024. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35025. * @type {string}
  35026. */
  35027. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35028. /**
  35029. * The output strength of the SSAO post-process. Default value is 1.0.
  35030. * @type {number}
  35031. */
  35032. this.totalStrength = 1.0;
  35033. /**
  35034. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35035. * @type {number}
  35036. */
  35037. this.radius = 0.0001;
  35038. /**
  35039. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35040. * Must not be equal to fallOff and superior to fallOff.
  35041. * Default value is 0.975
  35042. * @type {number}
  35043. */
  35044. this.area = 0.0075;
  35045. /**
  35046. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35047. * Must not be equal to area and inferior to area.
  35048. * Default value is 0.0
  35049. * @type {number}
  35050. */
  35051. this.fallOff = 0.000001;
  35052. /**
  35053. * The base color of the SSAO post-process
  35054. * The final result is "base + ssao" between [0, 1]
  35055. * @type {number}
  35056. */
  35057. this.base = 0.5;
  35058. this._firstUpdate = true;
  35059. this._scene = scene;
  35060. // Set up assets
  35061. this._createRandomTexture();
  35062. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35063. var ssaoRatio = ratio.ssaoRatio || ratio;
  35064. var combineRatio = ratio.combineRatio || ratio;
  35065. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35066. this._createSSAOPostProcess(ssaoRatio);
  35067. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35068. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35069. this._createSSAOCombinePostProcess(combineRatio);
  35070. // Set up pipeline
  35071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35076. // Finish
  35077. scene.postProcessRenderPipelineManager.addPipeline(this);
  35078. if (cameras)
  35079. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35080. }
  35081. // Public Methods
  35082. /**
  35083. * Returns the horizontal blur PostProcess
  35084. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35085. */
  35086. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35087. return this._blurHPostProcess;
  35088. };
  35089. /**
  35090. * Returns the vertical blur PostProcess
  35091. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35092. */
  35093. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35094. return this._blurVPostProcess;
  35095. };
  35096. /**
  35097. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35098. */
  35099. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35100. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35101. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35102. this._originalColorPostProcess = undefined;
  35103. this._ssaoPostProcess = undefined;
  35104. this._blurHPostProcess = undefined;
  35105. this._blurVPostProcess = undefined;
  35106. this._ssaoCombinePostProcess = undefined;
  35107. this._randomTexture.dispose();
  35108. if (disableDepthRender)
  35109. this._scene.disableDepthRenderer();
  35110. };
  35111. // Private Methods
  35112. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35113. var _this = this;
  35114. var numSamples = 16;
  35115. var sampleSphere = [
  35116. 0.5381, 0.1856, -0.4319,
  35117. 0.1379, 0.2486, 0.4430,
  35118. 0.3371, 0.5679, -0.0057,
  35119. -0.6999, -0.0451, -0.0019,
  35120. 0.0689, -0.1598, -0.8547,
  35121. 0.0560, 0.0069, -0.1843,
  35122. -0.0146, 0.1402, 0.0762,
  35123. 0.0100, -0.1924, -0.0344,
  35124. -0.3577, -0.5301, -0.4358,
  35125. -0.3169, 0.1063, 0.0158,
  35126. 0.0103, -0.5869, 0.0046,
  35127. -0.0897, -0.4940, 0.3287,
  35128. 0.7119, -0.0154, -0.0918,
  35129. -0.0533, 0.0596, -0.5411,
  35130. 0.0352, -0.0631, 0.5460,
  35131. -0.4776, 0.2847, -0.0271
  35132. ];
  35133. var samplesFactor = 1.0 / numSamples;
  35134. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35135. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35136. "area", "fallOff", "base"
  35137. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35138. this._ssaoPostProcess.onApply = function (effect) {
  35139. if (_this._firstUpdate) {
  35140. effect.setArray3("sampleSphere", sampleSphere);
  35141. effect.setFloat("samplesFactor", samplesFactor);
  35142. effect.setFloat("randTextureTiles", 4.0);
  35143. _this._firstUpdate = false;
  35144. }
  35145. effect.setFloat("totalStrength", _this.totalStrength);
  35146. effect.setFloat("radius", _this.radius);
  35147. effect.setFloat("area", _this.area);
  35148. effect.setFloat("fallOff", _this.fallOff);
  35149. effect.setFloat("base", _this.base);
  35150. effect.setTexture("textureSampler", _this._depthTexture);
  35151. effect.setTexture("randomSampler", _this._randomTexture);
  35152. };
  35153. };
  35154. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35155. var _this = this;
  35156. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35157. this._ssaoCombinePostProcess.onApply = function (effect) {
  35158. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35159. };
  35160. };
  35161. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35162. var size = 512;
  35163. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35164. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35165. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35166. var context = this._randomTexture.getContext();
  35167. var rand = function (min, max) {
  35168. return Math.random() * (max - min) + min;
  35169. };
  35170. var randVector = BABYLON.Vector3.Zero();
  35171. for (var x = 0; x < size; x++) {
  35172. for (var y = 0; y < size; y++) {
  35173. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35174. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35175. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35176. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35177. context.fillRect(x, y, 1, 1);
  35178. }
  35179. }
  35180. this._randomTexture.update(false);
  35181. };
  35182. return SSAORenderingPipeline;
  35183. })(BABYLON.PostProcessRenderPipeline);
  35184. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35185. })(BABYLON || (BABYLON = {}));
  35186. var BABYLON;
  35187. (function (BABYLON) {
  35188. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35189. var VolumetricLightScatteringPostProcess = (function (_super) {
  35190. __extends(VolumetricLightScatteringPostProcess, _super);
  35191. /**
  35192. * @constructor
  35193. * @param {string} name - The post-process name
  35194. * @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)
  35195. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35196. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35197. * @param {number} samples - The post-process quality, default 100
  35198. * @param {number} samplingMode - The post-process filtering mode
  35199. * @param {BABYLON.Engine} engine - The babylon engine
  35200. * @param {boolean} reusable - If the post-process is reusable
  35201. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35202. */
  35203. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35204. var _this = this;
  35205. if (samples === void 0) { samples = 100; }
  35206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35207. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35208. this._screenCoordinates = BABYLON.Vector2.Zero();
  35209. /**
  35210. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35211. * @type {boolean}
  35212. */
  35213. this.useCustomMeshPosition = false;
  35214. /**
  35215. * If the post-process should inverse the light scattering direction
  35216. * @type {boolean}
  35217. */
  35218. this.invert = true;
  35219. /**
  35220. * Set to true to use the diffuseColor instead of the diffuseTexture
  35221. * @type {boolean}
  35222. */
  35223. this.useDiffuseColor = false;
  35224. /**
  35225. * Array containing the excluded meshes not rendered in the internal pass
  35226. */
  35227. this.excludedMeshes = new Array();
  35228. /**
  35229. * Controls the overall intensity of the post-process
  35230. * @type {number}
  35231. */
  35232. this.exposure = 0.3;
  35233. /**
  35234. * Dissipates each sample's contribution in range [0, 1]
  35235. * @type {number}
  35236. */
  35237. this.decay = 0.96815;
  35238. /**
  35239. * Controls the overall intensity of each sample
  35240. * @type {number}
  35241. */
  35242. this.weight = 0.58767;
  35243. /**
  35244. * Controls the density of each sample
  35245. * @type {number}
  35246. */
  35247. this.density = 0.926;
  35248. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35249. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35250. // Configure mesh
  35251. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35252. // Configure
  35253. this._createPass(scene, ratio.passRatio || ratio);
  35254. this.onActivate = function (camera) {
  35255. if (!_this.isSupported) {
  35256. _this.dispose(camera);
  35257. }
  35258. _this.onActivate = null;
  35259. };
  35260. this.onApply = function (effect) {
  35261. _this._updateMeshScreenCoordinates(scene);
  35262. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35263. effect.setFloat("exposure", _this.exposure);
  35264. effect.setFloat("decay", _this.decay);
  35265. effect.setFloat("weight", _this.weight);
  35266. effect.setFloat("density", _this.density);
  35267. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35268. };
  35269. }
  35270. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35271. var mesh = subMesh.getMesh();
  35272. var defines = [];
  35273. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35274. var material = subMesh.getMaterial();
  35275. var needUV = false;
  35276. // Render this.mesh as default
  35277. if (mesh === this.mesh) {
  35278. if (this.useDiffuseColor) {
  35279. defines.push("#define DIFFUSE_COLOR_RENDER");
  35280. }
  35281. else if (material) {
  35282. if (material.diffuseTexture !== undefined) {
  35283. defines.push("#define BASIC_RENDER");
  35284. }
  35285. else {
  35286. defines.push("#define DIFFUSE_COLOR_RENDER");
  35287. }
  35288. }
  35289. defines.push("#define NEED_UV");
  35290. needUV = true;
  35291. }
  35292. // Alpha test
  35293. if (material) {
  35294. if (material.needAlphaTesting()) {
  35295. defines.push("#define ALPHATEST");
  35296. }
  35297. if (material.opacityTexture !== undefined) {
  35298. defines.push("#define OPACITY");
  35299. if (material.opacityTexture.getAlphaFromRGB) {
  35300. defines.push("#define OPACITYRGB");
  35301. }
  35302. if (!needUV) {
  35303. defines.push("#define NEED_UV");
  35304. }
  35305. }
  35306. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35307. attribs.push(BABYLON.VertexBuffer.UVKind);
  35308. defines.push("#define UV1");
  35309. }
  35310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35311. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35312. defines.push("#define UV2");
  35313. }
  35314. }
  35315. // Bones
  35316. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35317. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35318. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35319. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35320. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35321. }
  35322. else {
  35323. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35324. }
  35325. // Instances
  35326. if (useInstances) {
  35327. defines.push("#define INSTANCES");
  35328. attribs.push("world0");
  35329. attribs.push("world1");
  35330. attribs.push("world2");
  35331. attribs.push("world3");
  35332. }
  35333. // Get correct effect
  35334. var join = defines.join("\n");
  35335. if (this._cachedDefines !== join) {
  35336. this._cachedDefines = join;
  35337. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35338. }
  35339. return this._volumetricLightScatteringPass.isReady();
  35340. };
  35341. /**
  35342. * Sets the new light position for light scattering effect
  35343. * @param {BABYLON.Vector3} The new custom light position
  35344. */
  35345. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35346. this._customMeshPosition = position;
  35347. };
  35348. /**
  35349. * Returns the light position for light scattering effect
  35350. * @return {BABYLON.Vector3} The custom light position
  35351. */
  35352. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35353. return this._customMeshPosition;
  35354. };
  35355. /**
  35356. * Disposes the internal assets and detaches the post-process from the camera
  35357. */
  35358. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35359. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35360. if (rttIndex !== -1) {
  35361. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35362. }
  35363. this._volumetricLightScatteringRTT.dispose();
  35364. _super.prototype.dispose.call(this, camera);
  35365. };
  35366. /**
  35367. * Returns the render target texture used by the post-process
  35368. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35369. */
  35370. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35371. return this._volumetricLightScatteringRTT;
  35372. };
  35373. // Private methods
  35374. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35375. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35376. return true;
  35377. }
  35378. return false;
  35379. };
  35380. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35381. var _this = this;
  35382. var engine = scene.getEngine();
  35383. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35384. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35385. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35386. this._volumetricLightScatteringRTT.renderList = null;
  35387. this._volumetricLightScatteringRTT.renderParticles = false;
  35388. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35389. // Custom render function for submeshes
  35390. var renderSubMesh = function (subMesh) {
  35391. var mesh = subMesh.getRenderingMesh();
  35392. if (_this._meshExcluded(mesh)) {
  35393. return;
  35394. }
  35395. var scene = mesh.getScene();
  35396. var engine = scene.getEngine();
  35397. // Culling
  35398. engine.setState(subMesh.getMaterial().backFaceCulling);
  35399. // Managing instances
  35400. var batch = mesh._getInstancesRenderList(subMesh._id);
  35401. if (batch.mustReturn) {
  35402. return;
  35403. }
  35404. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35405. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35406. engine.enableEffect(_this._volumetricLightScatteringPass);
  35407. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35408. var material = subMesh.getMaterial();
  35409. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35410. // Alpha test
  35411. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35412. var alphaTexture = material.getAlphaTestTexture();
  35413. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35414. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35415. }
  35416. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35417. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35418. if (alphaTexture) {
  35419. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35420. }
  35421. }
  35422. if (material.opacityTexture !== undefined) {
  35423. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35424. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35425. }
  35426. }
  35427. // Bones
  35428. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35429. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35430. }
  35431. // Draw
  35432. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35433. }
  35434. };
  35435. // Render target texture callbacks
  35436. var savedSceneClearColor;
  35437. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35438. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35439. savedSceneClearColor = scene.clearColor;
  35440. scene.clearColor = sceneClearColor;
  35441. };
  35442. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35443. scene.clearColor = savedSceneClearColor;
  35444. };
  35445. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35446. var engine = scene.getEngine();
  35447. var index;
  35448. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35449. renderSubMesh(opaqueSubMeshes.data[index]);
  35450. }
  35451. engine.setAlphaTesting(true);
  35452. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35453. renderSubMesh(alphaTestSubMeshes.data[index]);
  35454. }
  35455. engine.setAlphaTesting(false);
  35456. if (transparentSubMeshes.length) {
  35457. // Sort sub meshes
  35458. for (index = 0; index < transparentSubMeshes.length; index++) {
  35459. var submesh = transparentSubMeshes.data[index];
  35460. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35461. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35462. }
  35463. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35464. sortedArray.sort(function (a, b) {
  35465. // Alpha index first
  35466. if (a._alphaIndex > b._alphaIndex) {
  35467. return 1;
  35468. }
  35469. if (a._alphaIndex < b._alphaIndex) {
  35470. return -1;
  35471. }
  35472. // Then distance to camera
  35473. if (a._distanceToCamera < b._distanceToCamera) {
  35474. return 1;
  35475. }
  35476. if (a._distanceToCamera > b._distanceToCamera) {
  35477. return -1;
  35478. }
  35479. return 0;
  35480. });
  35481. // Render sub meshes
  35482. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35483. for (index = 0; index < sortedArray.length; index++) {
  35484. renderSubMesh(sortedArray[index]);
  35485. }
  35486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35487. }
  35488. };
  35489. };
  35490. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35491. var transform = scene.getTransformMatrix();
  35492. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35493. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35494. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35495. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35496. if (this.invert)
  35497. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35498. };
  35499. // Static methods
  35500. /**
  35501. * Creates a default mesh for the Volumeric Light Scattering post-process
  35502. * @param {string} The mesh name
  35503. * @param {BABYLON.Scene} The scene where to create the mesh
  35504. * @return {BABYLON.Mesh} the default mesh
  35505. */
  35506. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35507. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35508. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35509. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35510. return mesh;
  35511. };
  35512. return VolumetricLightScatteringPostProcess;
  35513. })(BABYLON.PostProcess);
  35514. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35515. })(BABYLON || (BABYLON = {}));
  35516. // BABYLON.JS Chromatic Aberration GLSL Shader
  35517. // Author: Olivier Guyot
  35518. // Separates very slightly R, G and B colors on the edges of the screen
  35519. // Inspired by Francois Tarlier & Martins Upitis
  35520. var BABYLON;
  35521. (function (BABYLON) {
  35522. var LensRenderingPipeline = (function (_super) {
  35523. __extends(LensRenderingPipeline, _super);
  35524. /**
  35525. * @constructor
  35526. *
  35527. * Effect parameters are as follow:
  35528. * {
  35529. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35530. * edge_blur: number; // from 0 to x (1 for realism)
  35531. * distortion: number; // from 0 to x (1 for realism)
  35532. * grain_amount: number; // from 0 to 1
  35533. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35534. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35535. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35536. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35537. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35538. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35539. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35540. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35541. * }
  35542. * Note: if an effect parameter is unset, effect is disabled
  35543. *
  35544. * @param {string} name - The rendering pipeline name
  35545. * @param {object} parameters - An object containing all parameters (see above)
  35546. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35547. * @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)
  35548. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35549. */
  35550. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35551. var _this = this;
  35552. if (ratio === void 0) { ratio = 1.0; }
  35553. _super.call(this, scene.getEngine(), name);
  35554. // Lens effects can be of the following:
  35555. // - chromatic aberration (slight shift of RGB colors)
  35556. // - blur on the edge of the lens
  35557. // - lens distortion
  35558. // - depth-of-field blur & highlights enhancing
  35559. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35560. // - grain effect (noise or custom texture)
  35561. // Two additional texture samplers are needed:
  35562. // - depth map (for depth-of-field)
  35563. // - grain texture
  35564. /**
  35565. * The chromatic aberration PostProcess id in the pipeline
  35566. * @type {string}
  35567. */
  35568. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35569. /**
  35570. * The highlights enhancing PostProcess id in the pipeline
  35571. * @type {string}
  35572. */
  35573. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35574. /**
  35575. * The depth-of-field PostProcess id in the pipeline
  35576. * @type {string}
  35577. */
  35578. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35579. this._scene = scene;
  35580. // Fetch texture samplers
  35581. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35582. if (parameters.grain_texture) {
  35583. this._grainTexture = parameters.grain_texture;
  35584. }
  35585. else {
  35586. this._createGrainTexture();
  35587. }
  35588. // save parameters
  35589. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35590. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35591. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35592. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35593. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35594. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35595. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35596. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35597. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35598. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35599. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35600. // Create effects
  35601. this._createChromaticAberrationPostProcess(ratio);
  35602. this._createHighlightsPostProcess(ratio);
  35603. this._createDepthOfFieldPostProcess(ratio / 4);
  35604. // Set up pipeline
  35605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35606. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35607. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35608. if (this._highlightsGain === -1) {
  35609. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35610. }
  35611. // Finish
  35612. scene.postProcessRenderPipelineManager.addPipeline(this);
  35613. if (cameras) {
  35614. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35615. }
  35616. }
  35617. // public methods (self explanatory)
  35618. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35619. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35620. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35621. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35622. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35623. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35624. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35625. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35626. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35627. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35628. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35629. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35630. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35631. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35632. };
  35633. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35634. this._highlightsPostProcess.updateEffect();
  35635. };
  35636. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35637. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35638. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35639. this._highlightsGain = amount;
  35640. };
  35641. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35642. if (this._highlightsGain === -1) {
  35643. this._highlightsGain = 1.0;
  35644. }
  35645. this._highlightsThreshold = amount;
  35646. };
  35647. LensRenderingPipeline.prototype.disableHighlights = function () {
  35648. this._highlightsGain = -1;
  35649. };
  35650. /**
  35651. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35652. */
  35653. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35654. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35655. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35656. this._chromaticAberrationPostProcess = undefined;
  35657. this._highlightsPostProcess = undefined;
  35658. this._depthOfFieldPostProcess = undefined;
  35659. this._grainTexture.dispose();
  35660. if (disableDepthRender)
  35661. this._scene.disableDepthRenderer();
  35662. };
  35663. // colors shifting and distortion
  35664. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35665. var _this = this;
  35666. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35667. [], // samplers
  35668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35669. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35670. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35671. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35672. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35673. };
  35674. };
  35675. // highlights enhancing
  35676. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35677. var _this = this;
  35678. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35679. [], // samplers
  35680. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35681. this._highlightsPostProcess.onApply = function (effect) {
  35682. effect.setFloat('gain', _this._highlightsGain);
  35683. effect.setFloat('threshold', _this._highlightsThreshold);
  35684. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35685. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35686. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35687. };
  35688. };
  35689. // colors shifting and distortion
  35690. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35691. var _this = this;
  35692. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35693. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35694. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35695. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35696. this._depthOfFieldPostProcess.onApply = function (effect) {
  35697. effect.setTexture("depthSampler", _this._depthTexture);
  35698. effect.setTexture("grainSampler", _this._grainTexture);
  35699. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35700. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35701. effect.setFloat('grain_amount', _this._grainAmount);
  35702. effect.setBool('blur_noise', _this._blurNoise);
  35703. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35704. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35705. effect.setFloat('distortion', _this._distortion);
  35706. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35707. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35708. effect.setFloat('aperture', _this._dofAperture);
  35709. effect.setFloat('darken', _this._dofDarken);
  35710. effect.setFloat('edge_blur', _this._edgeBlur);
  35711. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35712. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35713. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35714. };
  35715. };
  35716. // creates a black and white random noise texture, 512x512
  35717. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35718. var size = 512;
  35719. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35720. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35721. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35722. var context = this._grainTexture.getContext();
  35723. var rand = function (min, max) {
  35724. return Math.random() * (max - min) + min;
  35725. };
  35726. var value;
  35727. for (var x = 0; x < size; x++) {
  35728. for (var y = 0; y < size; y++) {
  35729. value = Math.floor(rand(0.42, 0.58) * 255);
  35730. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35731. context.fillRect(x, y, 1, 1);
  35732. }
  35733. }
  35734. this._grainTexture.update(false);
  35735. };
  35736. return LensRenderingPipeline;
  35737. })(BABYLON.PostProcessRenderPipeline);
  35738. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35739. })(BABYLON || (BABYLON = {}));
  35740. //
  35741. // This post-process allows the modification of rendered colors by using
  35742. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35743. //
  35744. // The object needs to be provided an url to a texture containing the color
  35745. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35746. // Use an image editing software to tweak the LUT to match your needs.
  35747. //
  35748. // For an example of a color LUT, see here:
  35749. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35750. // For explanations on color grading, see here:
  35751. // http://udn.epicgames.com/Three/ColorGrading.html
  35752. //
  35753. var BABYLON;
  35754. (function (BABYLON) {
  35755. var ColorCorrectionPostProcess = (function (_super) {
  35756. __extends(ColorCorrectionPostProcess, _super);
  35757. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35758. var _this = this;
  35759. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35760. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35761. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35762. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35763. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35764. this.onApply = function (effect) {
  35765. effect.setTexture("colorTable", _this._colorTableTexture);
  35766. };
  35767. }
  35768. return ColorCorrectionPostProcess;
  35769. })(BABYLON.PostProcess);
  35770. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35771. })(BABYLON || (BABYLON = {}));
  35772. var BABYLON;
  35773. (function (BABYLON) {
  35774. var HDRRenderingPipeline = (function (_super) {
  35775. __extends(HDRRenderingPipeline, _super);
  35776. /**
  35777. * @constructor
  35778. * @param {string} name - The rendering pipeline name
  35779. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35780. * @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)
  35781. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35782. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35783. */
  35784. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35785. var _this = this;
  35786. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35787. _super.call(this, scene.getEngine(), name);
  35788. /**
  35789. * Public members
  35790. */
  35791. // Gaussian Blur
  35792. /**
  35793. * Gaussian blur coefficient
  35794. * @type {number}
  35795. */
  35796. this.gaussCoeff = 0.3;
  35797. /**
  35798. * Gaussian blur mean
  35799. * @type {number}
  35800. */
  35801. this.gaussMean = 1.0;
  35802. /**
  35803. * Gaussian blur standard deviation
  35804. * @type {number}
  35805. */
  35806. this.gaussStandDev = 0.8;
  35807. /**
  35808. * Gaussian blur multiplier. Multiplies the blur effect
  35809. * @type {number}
  35810. */
  35811. this.gaussMultiplier = 4.0;
  35812. // HDR
  35813. /**
  35814. * Exposure, controls the overall intensity of the pipeline
  35815. * @type {number}
  35816. */
  35817. this.exposure = 1.0;
  35818. /**
  35819. * Minimum luminance that the post-process can output. Luminance is >= 0
  35820. * @type {number}
  35821. */
  35822. this.minimumLuminance = 1.0;
  35823. /**
  35824. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35825. * @type {number}
  35826. */
  35827. this.maximumLuminance = 1e20;
  35828. /**
  35829. * Increase rate for luminance: eye adaptation speed to dark
  35830. * @type {number}
  35831. */
  35832. this.luminanceIncreaserate = 0.5;
  35833. /**
  35834. * Decrease rate for luminance: eye adaptation speed to bright
  35835. * @type {number}
  35836. */
  35837. this.luminanceDecreaseRate = 0.5;
  35838. // Bright pass
  35839. /**
  35840. * Minimum luminance needed to compute HDR
  35841. * @type {number}
  35842. */
  35843. this.brightThreshold = 0.8;
  35844. this._needUpdate = true;
  35845. this._scene = scene;
  35846. // Bright pass
  35847. this._createBrightPassPostProcess(scene, ratio);
  35848. // Down sample X4
  35849. this._createDownSampleX4PostProcess(scene, ratio);
  35850. // Create gaussian blur post-processes
  35851. this._createGaussianBlurPostProcess(scene, ratio);
  35852. // Texture adder
  35853. this._createTextureAdderPostProcess(scene, ratio);
  35854. // Luminance generator
  35855. this._createLuminanceGeneratorPostProcess(scene);
  35856. // HDR
  35857. this._createHDRPostProcess(scene, ratio);
  35858. // Pass postprocess
  35859. if (originalPostProcess === null) {
  35860. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35861. }
  35862. else {
  35863. this._originalPostProcess = originalPostProcess;
  35864. }
  35865. // Configure pipeline
  35866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35872. var addDownSamplerPostProcess = function (id) {
  35873. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35874. };
  35875. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35876. addDownSamplerPostProcess(i);
  35877. }
  35878. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35879. // Finish
  35880. scene.postProcessRenderPipelineManager.addPipeline(this);
  35881. if (cameras !== null) {
  35882. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35883. }
  35884. this.update();
  35885. }
  35886. /**
  35887. * Tells the pipeline to update its post-processes
  35888. */
  35889. HDRRenderingPipeline.prototype.update = function () {
  35890. this._needUpdate = true;
  35891. };
  35892. /**
  35893. * Returns the current calculated luminance
  35894. */
  35895. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35896. return this._hdrCurrentLuminance;
  35897. };
  35898. /**
  35899. * Returns the currently drawn luminance
  35900. */
  35901. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35902. return this._hdrOutputLuminance;
  35903. };
  35904. /**
  35905. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35906. */
  35907. HDRRenderingPipeline.prototype.dispose = function () {
  35908. this._originalPostProcess = undefined;
  35909. this._brightPassPostProcess = undefined;
  35910. this._downSampleX4PostProcess = undefined;
  35911. this._guassianBlurHPostProcess = undefined;
  35912. this._guassianBlurVPostProcess = undefined;
  35913. this._textureAdderPostProcess = undefined;
  35914. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35915. this._downSamplePostProcesses[i] = undefined;
  35916. }
  35917. this._hdrPostProcess = undefined;
  35918. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35919. };
  35920. /**
  35921. * Creates the HDR post-process and computes the luminance adaptation
  35922. */
  35923. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35924. var _this = this;
  35925. var hdrLastLuminance = 0.0;
  35926. this._hdrOutputLuminance = -1.0;
  35927. this._hdrCurrentLuminance = 1.0;
  35928. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35929. this._hdrPostProcess.onApply = function (effect) {
  35930. if (_this._hdrOutputLuminance < 0.0) {
  35931. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35932. }
  35933. else {
  35934. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35935. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35936. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35937. }
  35938. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35939. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35940. }
  35941. else {
  35942. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35943. }
  35944. }
  35945. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35946. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35947. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35948. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35949. effect.setFloat("exposure", _this.exposure);
  35950. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35951. _this._needUpdate = false;
  35952. };
  35953. };
  35954. /**
  35955. * Texture Adder post-process
  35956. */
  35957. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35958. var _this = this;
  35959. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35960. this._textureAdderPostProcess.onApply = function (effect) {
  35961. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35962. };
  35963. };
  35964. /**
  35965. * Down sample X4 post-process
  35966. */
  35967. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35968. var _this = this;
  35969. var downSampleX4Offsets = new Array(32);
  35970. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35971. this._downSampleX4PostProcess.onApply = function (effect) {
  35972. if (_this._needUpdate) {
  35973. var id = 0;
  35974. for (var i = -2; i < 2; i++) {
  35975. for (var j = -2; j < 2; j++) {
  35976. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35977. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35978. id += 2;
  35979. }
  35980. }
  35981. }
  35982. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35983. };
  35984. };
  35985. /**
  35986. * Bright pass post-process
  35987. */
  35988. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35989. var _this = this;
  35990. var brightOffsets = new Array(8);
  35991. var brightPassCallback = function (effect) {
  35992. if (_this._needUpdate) {
  35993. var sU = (1.0 / _this._brightPassPostProcess.width);
  35994. var sV = (1.0 / _this._brightPassPostProcess.height);
  35995. brightOffsets[0] = -0.5 * sU;
  35996. brightOffsets[1] = 0.5 * sV;
  35997. brightOffsets[2] = 0.5 * sU;
  35998. brightOffsets[3] = 0.5 * sV;
  35999. brightOffsets[4] = -0.5 * sU;
  36000. brightOffsets[5] = -0.5 * sV;
  36001. brightOffsets[6] = 0.5 * sU;
  36002. brightOffsets[7] = -0.5 * sV;
  36003. }
  36004. effect.setArray2("dsOffsets", brightOffsets);
  36005. effect.setFloat("brightThreshold", _this.brightThreshold);
  36006. };
  36007. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36008. this._brightPassPostProcess.onApply = brightPassCallback;
  36009. };
  36010. /**
  36011. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36012. */
  36013. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36014. var _this = this;
  36015. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36016. var luminanceOffsets = new Array(8);
  36017. var downSampleOffsets = new Array(18);
  36018. var halfDestPixelSize;
  36019. this._downSamplePostProcesses = new Array(lumSteps);
  36020. // Utils for luminance
  36021. var luminanceUpdateSourceOffsets = function (width, height) {
  36022. var sU = (1.0 / width);
  36023. var sV = (1.0 / height);
  36024. luminanceOffsets[0] = -0.5 * sU;
  36025. luminanceOffsets[1] = 0.5 * sV;
  36026. luminanceOffsets[2] = 0.5 * sU;
  36027. luminanceOffsets[3] = 0.5 * sV;
  36028. luminanceOffsets[4] = -0.5 * sU;
  36029. luminanceOffsets[5] = -0.5 * sV;
  36030. luminanceOffsets[6] = 0.5 * sU;
  36031. luminanceOffsets[7] = -0.5 * sV;
  36032. };
  36033. var luminanceUpdateDestOffsets = function (width, height) {
  36034. var id = 0;
  36035. for (var x = -1; x < 2; x++) {
  36036. for (var y = -1; y < 2; y++) {
  36037. downSampleOffsets[id] = (x) / width;
  36038. downSampleOffsets[id + 1] = (y) / height;
  36039. id += 2;
  36040. }
  36041. }
  36042. };
  36043. // Luminance callback
  36044. var luminanceCallback = function (effect) {
  36045. if (_this._needUpdate) {
  36046. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36047. }
  36048. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36049. effect.setArray2("lumOffsets", luminanceOffsets);
  36050. };
  36051. // Down sample callbacks
  36052. var downSampleCallback = function (indice) {
  36053. var i = indice;
  36054. return function (effect) {
  36055. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36056. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36057. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36058. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36059. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36060. effect.setArray2("dsOffsets", downSampleOffsets);
  36061. };
  36062. };
  36063. var downSampleAfterRenderCallback = function (effect) {
  36064. // Unpack result
  36065. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36066. 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);
  36067. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36068. };
  36069. // Create luminance post-process
  36070. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36071. 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);
  36072. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36073. // Create down sample post-processes
  36074. for (var i = lumSteps - 2; i >= 0; i--) {
  36075. var length = Math.pow(3, i);
  36076. ratio = { width: length, height: length };
  36077. var defines = "#define DOWN_SAMPLE\n";
  36078. if (i === 0) {
  36079. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36080. }
  36081. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36082. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36083. if (i === 0) {
  36084. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36085. }
  36086. }
  36087. };
  36088. /**
  36089. * Gaussian blur post-processes. Horizontal and Vertical
  36090. */
  36091. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36092. var _this = this;
  36093. var blurOffsetsW = new Array(9);
  36094. var blurOffsetsH = new Array(9);
  36095. var blurWeights = new Array(9);
  36096. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36097. // Utils for gaussian blur
  36098. var calculateBlurOffsets = function (height) {
  36099. var lastOutputDimensions = {
  36100. width: scene.getEngine().getRenderWidth(),
  36101. height: scene.getEngine().getRenderHeight()
  36102. };
  36103. for (var i = 0; i < 9; i++) {
  36104. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36105. if (height) {
  36106. blurOffsetsH[i] = value;
  36107. }
  36108. else {
  36109. blurOffsetsW[i] = value;
  36110. }
  36111. }
  36112. };
  36113. var calculateWeights = function () {
  36114. var x = 0.0;
  36115. for (var i = 0; i < 9; i++) {
  36116. x = (i - 4.0) / 4.0;
  36117. 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));
  36118. }
  36119. };
  36120. // Callback
  36121. var gaussianBlurCallback = function (height) {
  36122. return function (effect) {
  36123. if (_this._needUpdate) {
  36124. calculateWeights();
  36125. calculateBlurOffsets(height);
  36126. }
  36127. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36128. effect.setArray("blurWeights", blurWeights);
  36129. effect.setFloat("multiplier", _this.gaussMultiplier);
  36130. };
  36131. };
  36132. // Create horizontal gaussian blur post-processes
  36133. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36134. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36135. // Create vertical gaussian blur post-process
  36136. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36137. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36138. };
  36139. // Luminance generator
  36140. HDRRenderingPipeline.LUM_STEPS = 6;
  36141. return HDRRenderingPipeline;
  36142. })(BABYLON.PostProcessRenderPipeline);
  36143. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36144. })(BABYLON || (BABYLON = {}));
  36145. var BABYLON;
  36146. (function (BABYLON) {
  36147. var FaceAdjacencies = (function () {
  36148. function FaceAdjacencies() {
  36149. this.edges = new Array();
  36150. this.edgesConnectedCount = 0;
  36151. }
  36152. return FaceAdjacencies;
  36153. })();
  36154. var EdgesRenderer = (function () {
  36155. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36156. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36157. if (epsilon === void 0) { epsilon = 0.95; }
  36158. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36159. this.edgesWidthScalerForOrthographic = 1000.0;
  36160. this.edgesWidthScalerForPerspective = 50.0;
  36161. this._linesPositions = new Array();
  36162. this._linesNormals = new Array();
  36163. this._linesIndices = new Array();
  36164. this._buffers = new Array();
  36165. this._checkVerticesInsteadOfIndices = false;
  36166. this._source = source;
  36167. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36168. this._epsilon = epsilon;
  36169. this._prepareRessources();
  36170. this._generateEdgesLines();
  36171. }
  36172. EdgesRenderer.prototype._prepareRessources = function () {
  36173. if (this._lineShader) {
  36174. return;
  36175. }
  36176. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36177. attributes: ["position", "normal"],
  36178. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36179. });
  36180. this._lineShader.disableDepthWrite = true;
  36181. this._lineShader.backFaceCulling = false;
  36182. };
  36183. EdgesRenderer.prototype.dispose = function () {
  36184. this._vb0.dispose();
  36185. this._vb1.dispose();
  36186. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36187. this._lineShader.dispose();
  36188. };
  36189. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36190. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36191. return 0;
  36192. }
  36193. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36194. return 1;
  36195. }
  36196. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36197. return 2;
  36198. }
  36199. return -1;
  36200. };
  36201. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36202. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36203. return 0;
  36204. }
  36205. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36206. return 1;
  36207. }
  36208. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36209. return 2;
  36210. }
  36211. return -1;
  36212. };
  36213. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36214. var needToCreateLine;
  36215. if (edge === undefined) {
  36216. needToCreateLine = true;
  36217. }
  36218. else {
  36219. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36220. needToCreateLine = dotProduct < this._epsilon;
  36221. }
  36222. if (needToCreateLine) {
  36223. var offset = this._linesPositions.length / 3;
  36224. var normal = p0.subtract(p1);
  36225. normal.normalize();
  36226. // Positions
  36227. this._linesPositions.push(p0.x);
  36228. this._linesPositions.push(p0.y);
  36229. this._linesPositions.push(p0.z);
  36230. this._linesPositions.push(p0.x);
  36231. this._linesPositions.push(p0.y);
  36232. this._linesPositions.push(p0.z);
  36233. this._linesPositions.push(p1.x);
  36234. this._linesPositions.push(p1.y);
  36235. this._linesPositions.push(p1.z);
  36236. this._linesPositions.push(p1.x);
  36237. this._linesPositions.push(p1.y);
  36238. this._linesPositions.push(p1.z);
  36239. // Normals
  36240. this._linesNormals.push(p1.x);
  36241. this._linesNormals.push(p1.y);
  36242. this._linesNormals.push(p1.z);
  36243. this._linesNormals.push(-1);
  36244. this._linesNormals.push(p1.x);
  36245. this._linesNormals.push(p1.y);
  36246. this._linesNormals.push(p1.z);
  36247. this._linesNormals.push(1);
  36248. this._linesNormals.push(p0.x);
  36249. this._linesNormals.push(p0.y);
  36250. this._linesNormals.push(p0.z);
  36251. this._linesNormals.push(-1);
  36252. this._linesNormals.push(p0.x);
  36253. this._linesNormals.push(p0.y);
  36254. this._linesNormals.push(p0.z);
  36255. this._linesNormals.push(1);
  36256. // Indices
  36257. this._linesIndices.push(offset);
  36258. this._linesIndices.push(offset + 1);
  36259. this._linesIndices.push(offset + 2);
  36260. this._linesIndices.push(offset);
  36261. this._linesIndices.push(offset + 2);
  36262. this._linesIndices.push(offset + 3);
  36263. }
  36264. };
  36265. EdgesRenderer.prototype._generateEdgesLines = function () {
  36266. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36267. var indices = this._source.getIndices();
  36268. // First let's find adjacencies
  36269. var adjacencies = new Array();
  36270. var faceNormals = new Array();
  36271. var index;
  36272. var faceAdjacencies;
  36273. // Prepare faces
  36274. for (index = 0; index < indices.length; index += 3) {
  36275. faceAdjacencies = new FaceAdjacencies();
  36276. var p0Index = indices[index];
  36277. var p1Index = indices[index + 1];
  36278. var p2Index = indices[index + 2];
  36279. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36280. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36281. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36282. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36283. faceNormal.normalize();
  36284. faceNormals.push(faceNormal);
  36285. adjacencies.push(faceAdjacencies);
  36286. }
  36287. // Scan
  36288. for (index = 0; index < adjacencies.length; index++) {
  36289. faceAdjacencies = adjacencies[index];
  36290. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36291. var otherFaceAdjacencies = adjacencies[otherIndex];
  36292. if (faceAdjacencies.edgesConnectedCount === 3) {
  36293. break;
  36294. }
  36295. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36296. continue;
  36297. }
  36298. var otherP0 = indices[otherIndex * 3];
  36299. var otherP1 = indices[otherIndex * 3 + 1];
  36300. var otherP2 = indices[otherIndex * 3 + 2];
  36301. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36302. var otherEdgeIndex;
  36303. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36304. continue;
  36305. }
  36306. switch (edgeIndex) {
  36307. case 0:
  36308. if (this._checkVerticesInsteadOfIndices) {
  36309. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36310. }
  36311. else {
  36312. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36313. }
  36314. break;
  36315. case 1:
  36316. if (this._checkVerticesInsteadOfIndices) {
  36317. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36318. }
  36319. else {
  36320. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36321. }
  36322. break;
  36323. case 2:
  36324. if (this._checkVerticesInsteadOfIndices) {
  36325. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36326. }
  36327. else {
  36328. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36329. }
  36330. break;
  36331. }
  36332. if (otherEdgeIndex === -1) {
  36333. continue;
  36334. }
  36335. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36336. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36337. faceAdjacencies.edgesConnectedCount++;
  36338. otherFaceAdjacencies.edgesConnectedCount++;
  36339. if (faceAdjacencies.edgesConnectedCount === 3) {
  36340. break;
  36341. }
  36342. }
  36343. }
  36344. }
  36345. // Create lines
  36346. for (index = 0; index < adjacencies.length; index++) {
  36347. // 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
  36348. var current = adjacencies[index];
  36349. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36350. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36351. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36352. }
  36353. // Merge into a single mesh
  36354. var engine = this._source.getScene().getEngine();
  36355. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36356. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36357. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36358. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36359. this._ib = engine.createIndexBuffer(this._linesIndices);
  36360. this._indicesCount = this._linesIndices.length;
  36361. };
  36362. EdgesRenderer.prototype.render = function () {
  36363. if (!this._lineShader.isReady()) {
  36364. return;
  36365. }
  36366. var scene = this._source.getScene();
  36367. var engine = scene.getEngine();
  36368. this._lineShader._preBind();
  36369. // VBOs
  36370. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36371. scene.resetCachedMaterial();
  36372. this._lineShader.setColor4("color", this._source.edgesColor);
  36373. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36374. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36375. }
  36376. else {
  36377. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36378. }
  36379. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36380. this._lineShader.bind(this._source.getWorldMatrix());
  36381. // Draw order
  36382. engine.draw(true, 0, this._indicesCount);
  36383. this._lineShader.unbind();
  36384. engine.setDepthWrite(true);
  36385. };
  36386. return EdgesRenderer;
  36387. })();
  36388. BABYLON.EdgesRenderer = EdgesRenderer;
  36389. })(BABYLON || (BABYLON = {}));
  36390. var BABYLON;
  36391. (function (BABYLON) {
  36392. (function (TonemappingOperator) {
  36393. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36394. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36395. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36396. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36397. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36398. var TonemappingOperator = BABYLON.TonemappingOperator;
  36399. ;
  36400. var TonemapPostProcess = (function (_super) {
  36401. __extends(TonemapPostProcess, _super);
  36402. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36403. var _this = this;
  36404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36405. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36406. this._operator = operator;
  36407. this.exposureAdjustment = exposureAdjustment;
  36408. var params = ["_ExposureAdjustment"];
  36409. var defines = "#define ";
  36410. if (operator === TonemappingOperator.Hable)
  36411. defines += "HABLE_TONEMAPPING";
  36412. else if (operator === TonemappingOperator.Reinhard)
  36413. defines += "REINHARD_TONEMAPPING";
  36414. else if (operator === TonemappingOperator.HejiDawson)
  36415. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36416. else if (operator === TonemappingOperator.Photographic)
  36417. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36418. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36419. this.onApply = function (effect) {
  36420. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  36421. };
  36422. }
  36423. return TonemapPostProcess;
  36424. })(BABYLON.PostProcess);
  36425. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36426. })(BABYLON || (BABYLON = {}));
  36427. var BABYLON;
  36428. (function (BABYLON) {
  36429. var ReflectionProbe = (function () {
  36430. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36431. var _this = this;
  36432. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36433. this.name = name;
  36434. this._viewMatrix = BABYLON.Matrix.Identity();
  36435. this._target = BABYLON.Vector3.Zero();
  36436. this._add = BABYLON.Vector3.Zero();
  36437. this.position = BABYLON.Vector3.Zero();
  36438. this._scene = scene;
  36439. this._scene.reflectionProbes.push(this);
  36440. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36441. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36442. switch (faceIndex) {
  36443. case 0:
  36444. _this._add.copyFromFloats(1, 0, 0);
  36445. break;
  36446. case 1:
  36447. _this._add.copyFromFloats(-1, 0, 0);
  36448. break;
  36449. case 2:
  36450. _this._add.copyFromFloats(0, -1, 0);
  36451. break;
  36452. case 3:
  36453. _this._add.copyFromFloats(0, 1, 0);
  36454. break;
  36455. case 4:
  36456. _this._add.copyFromFloats(0, 0, 1);
  36457. break;
  36458. case 5:
  36459. _this._add.copyFromFloats(0, 0, -1);
  36460. break;
  36461. }
  36462. if (_this._attachedMesh) {
  36463. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36464. }
  36465. _this.position.addToRef(_this._add, _this._target);
  36466. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36467. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36468. };
  36469. this._renderTargetTexture.onAfterUnbind = function () {
  36470. scene.updateTransformMatrix(true);
  36471. };
  36472. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36473. }
  36474. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36475. get: function () {
  36476. return this._renderTargetTexture.refreshRate;
  36477. },
  36478. set: function (value) {
  36479. this._renderTargetTexture.refreshRate = value;
  36480. },
  36481. enumerable: true,
  36482. configurable: true
  36483. });
  36484. ReflectionProbe.prototype.getScene = function () {
  36485. return this._scene;
  36486. };
  36487. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36488. get: function () {
  36489. return this._renderTargetTexture;
  36490. },
  36491. enumerable: true,
  36492. configurable: true
  36493. });
  36494. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36495. get: function () {
  36496. return this._renderTargetTexture.renderList;
  36497. },
  36498. enumerable: true,
  36499. configurable: true
  36500. });
  36501. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36502. this._attachedMesh = mesh;
  36503. };
  36504. ReflectionProbe.prototype.dispose = function () {
  36505. var index = this._scene.reflectionProbes.indexOf(this);
  36506. if (index !== -1) {
  36507. // Remove from the scene if found
  36508. this._scene.reflectionProbes.splice(index, 1);
  36509. }
  36510. if (this._renderTargetTexture) {
  36511. this._renderTargetTexture.dispose();
  36512. this._renderTargetTexture = null;
  36513. }
  36514. };
  36515. return ReflectionProbe;
  36516. })();
  36517. BABYLON.ReflectionProbe = ReflectionProbe;
  36518. })(BABYLON || (BABYLON = {}));
  36519. var BABYLON;
  36520. (function (BABYLON) {
  36521. var SolidParticle = (function () {
  36522. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36523. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36524. this.position = BABYLON.Vector3.Zero(); // position
  36525. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36526. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36527. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36528. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36529. this.alive = true; // alive
  36530. this.idx = particleIndex;
  36531. this._pos = positionIndex;
  36532. this._model = model;
  36533. this.shapeId = shapeId;
  36534. this.idxInShape = idxInShape;
  36535. }
  36536. return SolidParticle;
  36537. })();
  36538. BABYLON.SolidParticle = SolidParticle;
  36539. var ModelShape = (function () {
  36540. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36541. this.shapeID = id;
  36542. this._shape = shape;
  36543. this._shapeUV = shapeUV;
  36544. this._positionFunction = posFunction;
  36545. this._vertexFunction = vtxFunction;
  36546. }
  36547. return ModelShape;
  36548. })();
  36549. BABYLON.ModelShape = ModelShape;
  36550. })(BABYLON || (BABYLON = {}));
  36551. var BABYLON;
  36552. (function (BABYLON) {
  36553. /**
  36554. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36555. */
  36556. var SolidParticleSystem = (function () {
  36557. /**
  36558. * Creates a SPS (Solid Particle System) object.
  36559. * @param name the SPS name, this will be the underlying mesh name
  36560. * @param updatable (default true) if the SPS must be updatable or immutable
  36561. * @param isPickable (default false) if the solid particles must be pickable
  36562. */
  36563. function SolidParticleSystem(name, scene, options) {
  36564. // public members
  36565. this.particles = new Array();
  36566. this.nbParticles = 0;
  36567. this.billboard = false;
  36568. this.counter = 0;
  36569. this.vars = {};
  36570. this._positions = new Array();
  36571. this._indices = new Array();
  36572. this._normals = new Array();
  36573. this._colors = new Array();
  36574. this._uvs = new Array();
  36575. this._index = 0; // indices index
  36576. this._updatable = true;
  36577. this._pickable = false;
  36578. this._isVisibilityBoxLocked = false;
  36579. this._alwaysVisible = false;
  36580. this._shapeCounter = 0;
  36581. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36582. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36583. this._computeParticleColor = true;
  36584. this._computeParticleTexture = true;
  36585. this._computeParticleRotation = true;
  36586. this._computeParticleVertex = false;
  36587. this._cam_axisZ = BABYLON.Vector3.Zero();
  36588. this._cam_axisY = BABYLON.Vector3.Zero();
  36589. this._cam_axisX = BABYLON.Vector3.Zero();
  36590. this._axisX = BABYLON.Axis.X;
  36591. this._axisY = BABYLON.Axis.Y;
  36592. this._axisZ = BABYLON.Axis.Z;
  36593. this._fakeCamPos = BABYLON.Vector3.Zero();
  36594. this._rotMatrix = new BABYLON.Matrix();
  36595. this._invertMatrix = new BABYLON.Matrix();
  36596. this._rotated = BABYLON.Vector3.Zero();
  36597. this._quaternion = new BABYLON.Quaternion();
  36598. this._vertex = BABYLON.Vector3.Zero();
  36599. this._normal = BABYLON.Vector3.Zero();
  36600. this._yaw = 0.0;
  36601. this._pitch = 0.0;
  36602. this._roll = 0.0;
  36603. this._halfroll = 0.0;
  36604. this._halfpitch = 0.0;
  36605. this._halfyaw = 0.0;
  36606. this._sinRoll = 0.0;
  36607. this._cosRoll = 0.0;
  36608. this._sinPitch = 0.0;
  36609. this._cosPitch = 0.0;
  36610. this._sinYaw = 0.0;
  36611. this._cosYaw = 0.0;
  36612. this._w = 0.0;
  36613. this.name = name;
  36614. this._scene = scene;
  36615. this._camera = scene.activeCamera;
  36616. this._pickable = options ? options.isPickable : false;
  36617. if (options && options.updatable) {
  36618. this._updatable = options.updatable;
  36619. }
  36620. else {
  36621. this._updatable = true;
  36622. }
  36623. if (this._pickable) {
  36624. this.pickedParticles = [];
  36625. }
  36626. }
  36627. /**
  36628. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36629. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36630. */
  36631. SolidParticleSystem.prototype.buildMesh = function () {
  36632. if (this.nbParticles === 0) {
  36633. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36634. this.addShape(triangle, 1);
  36635. triangle.dispose();
  36636. }
  36637. this._positions32 = new Float32Array(this._positions);
  36638. this._uvs32 = new Float32Array(this._uvs);
  36639. this._colors32 = new Float32Array(this._colors);
  36640. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36641. this._normals32 = new Float32Array(this._normals);
  36642. this._fixedNormal32 = new Float32Array(this._normals);
  36643. var vertexData = new BABYLON.VertexData();
  36644. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36645. vertexData.indices = this._indices;
  36646. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36647. if (this._uvs32) {
  36648. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36649. ;
  36650. }
  36651. if (this._colors32) {
  36652. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36653. }
  36654. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36655. vertexData.applyToMesh(mesh, this._updatable);
  36656. this.mesh = mesh;
  36657. this.mesh.isPickable = this._pickable;
  36658. // free memory
  36659. this._positions = null;
  36660. this._normals = null;
  36661. this._uvs = null;
  36662. this._colors = null;
  36663. if (!this._updatable) {
  36664. this.particles.length = 0;
  36665. }
  36666. return mesh;
  36667. };
  36668. /**
  36669. * Digests the mesh and generates as many solid particles in the system as wanted.
  36670. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36671. * Thus the particles generated from digest() have their property "positiion" yet set.
  36672. * @param mesh the mesh to be digested
  36673. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  36674. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  36675. */
  36676. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36677. var size = (options && options.facetNb) || 1;
  36678. var number = (options && options.number);
  36679. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36680. var meshInd = mesh.getIndices();
  36681. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36682. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36683. var f = 0; // facet counter
  36684. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36685. // compute size from number
  36686. if (number) {
  36687. number = (number > totalFacets) ? totalFacets : number;
  36688. size = Math.round(totalFacets / number);
  36689. }
  36690. else {
  36691. size = (size > totalFacets) ? totalFacets : size;
  36692. }
  36693. var facetPos = []; // submesh positions
  36694. var facetInd = []; // submesh indices
  36695. var facetUV = []; // submesh UV
  36696. var facetCol = []; // submesh colors
  36697. var barycenter = BABYLON.Tmp.Vector3[0];
  36698. while (f < totalFacets) {
  36699. if (f > totalFacets - size) {
  36700. size = totalFacets - f;
  36701. }
  36702. // reset temp arrays
  36703. facetPos.length = 0;
  36704. facetInd.length = 0;
  36705. facetUV.length = 0;
  36706. facetCol.length = 0;
  36707. // iterate over "size" facets
  36708. var fi = 0;
  36709. for (var j = f * 3; j < (f + size) * 3; j++) {
  36710. facetInd.push(fi);
  36711. var i = meshInd[j];
  36712. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36713. if (meshUV) {
  36714. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36715. }
  36716. if (meshCol) {
  36717. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36718. }
  36719. fi++;
  36720. }
  36721. // create a model shape for each single particle
  36722. var idx = this.nbParticles;
  36723. var shape = this._posToShape(facetPos);
  36724. var shapeUV = this._uvsToShapeUV(facetUV);
  36725. // compute the barycenter of the shape
  36726. var v;
  36727. for (v = 0; v < shape.length; v++) {
  36728. barycenter.addInPlace(shape[v]);
  36729. }
  36730. barycenter.scaleInPlace(1 / shape.length);
  36731. // shift the shape from its barycenter to the origin
  36732. for (v = 0; v < shape.length; v++) {
  36733. shape[v].subtractInPlace(barycenter);
  36734. }
  36735. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36736. // add the particle in the SPS
  36737. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  36738. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  36739. // initialize the particle position
  36740. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36741. this._index += shape.length;
  36742. idx++;
  36743. this.nbParticles++;
  36744. this._shapeCounter++;
  36745. f += size;
  36746. }
  36747. };
  36748. //reset copy
  36749. SolidParticleSystem.prototype._resetCopy = function () {
  36750. this._copy.position.x = 0;
  36751. this._copy.position.y = 0;
  36752. this._copy.position.z = 0;
  36753. this._copy.rotation.x = 0;
  36754. this._copy.rotation.y = 0;
  36755. this._copy.rotation.z = 0;
  36756. this._copy.quaternion = null;
  36757. this._copy.scale.x = 1;
  36758. this._copy.scale.y = 1;
  36759. this._copy.scale.z = 1;
  36760. this._copy.uvs.x = 0;
  36761. this._copy.uvs.y = 0;
  36762. this._copy.uvs.z = 1;
  36763. this._copy.uvs.w = 1;
  36764. this._copy.color = null;
  36765. };
  36766. // _meshBuilder : inserts the shape model in the global SPS mesh
  36767. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36768. var i;
  36769. var u = 0;
  36770. var c = 0;
  36771. this._resetCopy();
  36772. if (options && options.positionFunction) {
  36773. options.positionFunction(this._copy, idx, idxInShape);
  36774. }
  36775. if (this._copy.quaternion) {
  36776. this._quaternion.x = this._copy.quaternion.x;
  36777. this._quaternion.y = this._copy.quaternion.y;
  36778. this._quaternion.z = this._copy.quaternion.z;
  36779. this._quaternion.w = this._copy.quaternion.w;
  36780. }
  36781. else {
  36782. this._yaw = this._copy.rotation.y;
  36783. this._pitch = this._copy.rotation.x;
  36784. this._roll = this._copy.rotation.z;
  36785. this._quaternionRotationYPR();
  36786. }
  36787. this._quaternionToRotationMatrix();
  36788. for (i = 0; i < shape.length; i++) {
  36789. this._vertex.x = shape[i].x;
  36790. this._vertex.y = shape[i].y;
  36791. this._vertex.z = shape[i].z;
  36792. if (options && options.vertexFunction) {
  36793. options.vertexFunction(this._copy, this._vertex, i);
  36794. }
  36795. this._vertex.x *= this._copy.scale.x;
  36796. this._vertex.y *= this._copy.scale.y;
  36797. this._vertex.z *= this._copy.scale.z;
  36798. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36799. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36800. if (meshUV) {
  36801. 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);
  36802. u += 2;
  36803. }
  36804. if (this._copy.color) {
  36805. this._color = this._copy.color;
  36806. }
  36807. else if (meshCol && meshCol[c]) {
  36808. this._color.r = meshCol[c];
  36809. this._color.g = meshCol[c + 1];
  36810. this._color.b = meshCol[c + 2];
  36811. this._color.a = meshCol[c + 3];
  36812. }
  36813. else {
  36814. this._color.r = 1;
  36815. this._color.g = 1;
  36816. this._color.b = 1;
  36817. this._color.a = 1;
  36818. }
  36819. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36820. c += 4;
  36821. }
  36822. for (i = 0; i < meshInd.length; i++) {
  36823. indices.push(p + meshInd[i]);
  36824. }
  36825. if (this._pickable) {
  36826. var nbfaces = meshInd.length / 3;
  36827. for (i = 0; i < nbfaces; i++) {
  36828. this.pickedParticles.push({ idx: idx, faceId: i });
  36829. }
  36830. }
  36831. };
  36832. // returns a shape array from positions array
  36833. SolidParticleSystem.prototype._posToShape = function (positions) {
  36834. var shape = [];
  36835. for (var i = 0; i < positions.length; i += 3) {
  36836. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36837. }
  36838. return shape;
  36839. };
  36840. // returns a shapeUV array from a Vector4 uvs
  36841. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36842. var shapeUV = [];
  36843. if (uvs) {
  36844. for (var i = 0; i < uvs.length; i++)
  36845. shapeUV.push(uvs[i]);
  36846. }
  36847. return shapeUV;
  36848. };
  36849. // adds a new particle object in the particles array
  36850. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36851. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36852. };
  36853. /**
  36854. * Adds some particles to the SPS from the model shape.
  36855. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  36856. * @param mesh any Mesh object that will be used as a model for the solid particles.
  36857. * @param nb the number of particles to be created from this model
  36858. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  36859. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  36860. */
  36861. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36862. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36863. var meshInd = mesh.getIndices();
  36864. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36865. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36866. var shape = this._posToShape(meshPos);
  36867. var shapeUV = this._uvsToShapeUV(meshUV);
  36868. var posfunc = options ? options.positionFunction : null;
  36869. var vtxfunc = options ? options.vertexFunction : null;
  36870. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36871. // particles
  36872. var idx = this.nbParticles;
  36873. for (var i = 0; i < nb; i++) {
  36874. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36875. if (this._updatable) {
  36876. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36877. }
  36878. this._index += shape.length;
  36879. idx++;
  36880. }
  36881. this.nbParticles += nb;
  36882. this._shapeCounter++;
  36883. return this._shapeCounter - 1;
  36884. };
  36885. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36886. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36887. this._resetCopy();
  36888. if (particle._model._positionFunction) {
  36889. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36890. }
  36891. if (this._copy.quaternion) {
  36892. this._quaternion.x = this._copy.quaternion.x;
  36893. this._quaternion.y = this._copy.quaternion.y;
  36894. this._quaternion.z = this._copy.quaternion.z;
  36895. this._quaternion.w = this._copy.quaternion.w;
  36896. }
  36897. else {
  36898. this._yaw = this._copy.rotation.y;
  36899. this._pitch = this._copy.rotation.x;
  36900. this._roll = this._copy.rotation.z;
  36901. this._quaternionRotationYPR();
  36902. }
  36903. this._quaternionToRotationMatrix();
  36904. this._shape = particle._model._shape;
  36905. for (var pt = 0; pt < this._shape.length; pt++) {
  36906. this._vertex.x = this._shape[pt].x;
  36907. this._vertex.y = this._shape[pt].y;
  36908. this._vertex.z = this._shape[pt].z;
  36909. if (particle._model._vertexFunction) {
  36910. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36911. }
  36912. this._vertex.x *= this._copy.scale.x;
  36913. this._vertex.y *= this._copy.scale.y;
  36914. this._vertex.z *= this._copy.scale.z;
  36915. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36916. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36917. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36918. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36919. }
  36920. particle.position.x = 0;
  36921. particle.position.y = 0;
  36922. particle.position.z = 0;
  36923. particle.rotation.x = 0;
  36924. particle.rotation.y = 0;
  36925. particle.rotation.z = 0;
  36926. particle.quaternion = null;
  36927. particle.scale.x = 1;
  36928. particle.scale.y = 1;
  36929. particle.scale.z = 1;
  36930. };
  36931. /**
  36932. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36933. */
  36934. SolidParticleSystem.prototype.rebuildMesh = function () {
  36935. for (var p = 0; p < this.particles.length; p++) {
  36936. this._rebuildParticle(this.particles[p]);
  36937. }
  36938. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36939. };
  36940. /**
  36941. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36942. * This method calls updateParticle() for each particles of the SPS.
  36943. * For an animated SPS, it is usually called within the render loop.
  36944. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  36945. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  36946. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  36947. */
  36948. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36949. if (start === void 0) { start = 0; }
  36950. if (end === void 0) { end = this.nbParticles - 1; }
  36951. if (update === void 0) { update = true; }
  36952. if (!this._updatable) {
  36953. return;
  36954. }
  36955. // custom beforeUpdate
  36956. this.beforeUpdateParticles(start, end, update);
  36957. this._cam_axisX.x = 1;
  36958. this._cam_axisX.y = 0;
  36959. this._cam_axisX.z = 0;
  36960. this._cam_axisY.x = 0;
  36961. this._cam_axisY.y = 1;
  36962. this._cam_axisY.z = 0;
  36963. this._cam_axisZ.x = 0;
  36964. this._cam_axisZ.y = 0;
  36965. this._cam_axisZ.z = 1;
  36966. // if the particles will always face the camera
  36967. if (this.billboard) {
  36968. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36969. this._yaw = this.mesh.rotation.y;
  36970. this._pitch = this.mesh.rotation.x;
  36971. this._roll = this.mesh.rotation.z;
  36972. this._quaternionRotationYPR();
  36973. this._quaternionToRotationMatrix();
  36974. this._rotMatrix.invertToRef(this._invertMatrix);
  36975. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36976. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36977. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36978. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36979. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36980. this._cam_axisY.normalize();
  36981. this._cam_axisX.normalize();
  36982. this._cam_axisZ.normalize();
  36983. }
  36984. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36985. var idx = 0;
  36986. var index = 0;
  36987. var colidx = 0;
  36988. var colorIndex = 0;
  36989. var uvidx = 0;
  36990. var uvIndex = 0;
  36991. // particle loop
  36992. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36993. for (var p = start; p <= end; p++) {
  36994. this._particle = this.particles[p];
  36995. this._shape = this._particle._model._shape;
  36996. this._shapeUV = this._particle._model._shapeUV;
  36997. // call to custom user function to update the particle properties
  36998. this.updateParticle(this._particle);
  36999. // particle rotation matrix
  37000. if (this.billboard) {
  37001. this._particle.rotation.x = 0.0;
  37002. this._particle.rotation.y = 0.0;
  37003. }
  37004. if (this._computeParticleRotation) {
  37005. if (this._particle.quaternion) {
  37006. this._quaternion.x = this._particle.quaternion.x;
  37007. this._quaternion.y = this._particle.quaternion.y;
  37008. this._quaternion.z = this._particle.quaternion.z;
  37009. this._quaternion.w = this._particle.quaternion.w;
  37010. }
  37011. else {
  37012. this._yaw = this._particle.rotation.y;
  37013. this._pitch = this._particle.rotation.x;
  37014. this._roll = this._particle.rotation.z;
  37015. this._quaternionRotationYPR();
  37016. }
  37017. this._quaternionToRotationMatrix();
  37018. }
  37019. for (var pt = 0; pt < this._shape.length; pt++) {
  37020. idx = index + pt * 3;
  37021. colidx = colorIndex + pt * 4;
  37022. uvidx = uvIndex + pt * 2;
  37023. this._vertex.x = this._shape[pt].x;
  37024. this._vertex.y = this._shape[pt].y;
  37025. this._vertex.z = this._shape[pt].z;
  37026. if (this._computeParticleVertex) {
  37027. this.updateParticleVertex(this._particle, this._vertex, pt);
  37028. }
  37029. // positions
  37030. this._vertex.x *= this._particle.scale.x;
  37031. this._vertex.y *= this._particle.scale.y;
  37032. this._vertex.z *= this._particle.scale.z;
  37033. 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];
  37034. 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;
  37035. 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;
  37036. 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;
  37037. 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;
  37038. 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;
  37039. 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;
  37040. // normals : if the particles can't be morphed then just rotate the normals
  37041. if (!this._computeParticleVertex && !this.billboard) {
  37042. this._normal.x = this._fixedNormal32[idx];
  37043. this._normal.y = this._fixedNormal32[idx + 1];
  37044. this._normal.z = this._fixedNormal32[idx + 2];
  37045. 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];
  37046. 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;
  37047. 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;
  37048. 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;
  37049. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37050. 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;
  37051. 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;
  37052. }
  37053. if (this._computeParticleColor) {
  37054. this._colors32[colidx] = this._particle.color.r;
  37055. this._colors32[colidx + 1] = this._particle.color.g;
  37056. this._colors32[colidx + 2] = this._particle.color.b;
  37057. this._colors32[colidx + 3] = this._particle.color.a;
  37058. }
  37059. if (this._computeParticleTexture) {
  37060. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37061. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37062. }
  37063. }
  37064. index = idx + 3;
  37065. colorIndex = colidx + 4;
  37066. uvIndex = uvidx + 2;
  37067. }
  37068. if (update) {
  37069. if (this._computeParticleColor) {
  37070. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37071. }
  37072. if (this._computeParticleTexture) {
  37073. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37074. }
  37075. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37076. if (!this.mesh.areNormalsFrozen) {
  37077. if (this._computeParticleVertex || this.billboard) {
  37078. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37079. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37080. for (var i = 0; i < this._normals32.length; i++) {
  37081. this._fixedNormal32[i] = this._normals32[i];
  37082. }
  37083. }
  37084. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37085. }
  37086. }
  37087. this.afterUpdateParticles(start, end, update);
  37088. };
  37089. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37090. this._halfroll = this._roll * 0.5;
  37091. this._halfpitch = this._pitch * 0.5;
  37092. this._halfyaw = this._yaw * 0.5;
  37093. this._sinRoll = Math.sin(this._halfroll);
  37094. this._cosRoll = Math.cos(this._halfroll);
  37095. this._sinPitch = Math.sin(this._halfpitch);
  37096. this._cosPitch = Math.cos(this._halfpitch);
  37097. this._sinYaw = Math.sin(this._halfyaw);
  37098. this._cosYaw = Math.cos(this._halfyaw);
  37099. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37100. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37101. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37102. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37103. };
  37104. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37105. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37106. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37107. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37108. this._rotMatrix.m[3] = 0;
  37109. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37110. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37111. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37112. this._rotMatrix.m[7] = 0;
  37113. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37114. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37115. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37116. this._rotMatrix.m[11] = 0;
  37117. this._rotMatrix.m[12] = 0;
  37118. this._rotMatrix.m[13] = 0;
  37119. this._rotMatrix.m[14] = 0;
  37120. this._rotMatrix.m[15] = 1.0;
  37121. };
  37122. /**
  37123. * Disposes the SPS
  37124. */
  37125. SolidParticleSystem.prototype.dispose = function () {
  37126. this.mesh.dispose();
  37127. this.vars = null;
  37128. // drop references to internal big arrays for the GC
  37129. this._positions = null;
  37130. this._indices = null;
  37131. this._normals = null;
  37132. this._uvs = null;
  37133. this._colors = null;
  37134. this._positions32 = null;
  37135. this._normals32 = null;
  37136. this._fixedNormal32 = null;
  37137. this._uvs32 = null;
  37138. this._colors32 = null;
  37139. this.pickedParticles = null;
  37140. };
  37141. /**
  37142. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37143. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37144. */
  37145. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37146. if (!this._isVisibilityBoxLocked) {
  37147. this.mesh.refreshBoundingInfo();
  37148. }
  37149. };
  37150. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37151. * @param size the size (float) of the visibility box
  37152. * note : this doesn't lock the SPS mesh bounding box.
  37153. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37154. */
  37155. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37156. var vis = size / 2;
  37157. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37158. };
  37159. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37160. // getter and setter
  37161. /**
  37162. * True if the SPS is set as always visible
  37163. */
  37164. get: function () {
  37165. return this._alwaysVisible;
  37166. },
  37167. /**
  37168. * Sets the SPS as always visible or not
  37169. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37170. */
  37171. set: function (val) {
  37172. this._alwaysVisible = val;
  37173. this.mesh.alwaysSelectAsActiveMesh = val;
  37174. },
  37175. enumerable: true,
  37176. configurable: true
  37177. });
  37178. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37179. /**
  37180. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37181. */
  37182. get: function () {
  37183. return this._isVisibilityBoxLocked;
  37184. },
  37185. /**
  37186. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37187. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37188. */
  37189. set: function (val) {
  37190. this._isVisibilityBoxLocked = val;
  37191. this.mesh.getBoundingInfo().isLocked = val;
  37192. },
  37193. enumerable: true,
  37194. configurable: true
  37195. });
  37196. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37197. // getters
  37198. get: function () {
  37199. return this._computeParticleRotation;
  37200. },
  37201. // Optimizer setters
  37202. /**
  37203. * Tells to setParticle() to compute the particle rotations or not.
  37204. * Default value : true. The SPS is faster when it's set to false.
  37205. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37206. */
  37207. set: function (val) {
  37208. this._computeParticleRotation = val;
  37209. },
  37210. enumerable: true,
  37211. configurable: true
  37212. });
  37213. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37214. get: function () {
  37215. return this._computeParticleColor;
  37216. },
  37217. /**
  37218. * Tells to setParticle() to compute the particle colors or not.
  37219. * Default value : true. The SPS is faster when it's set to false.
  37220. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37221. */
  37222. set: function (val) {
  37223. this._computeParticleColor = val;
  37224. },
  37225. enumerable: true,
  37226. configurable: true
  37227. });
  37228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37229. get: function () {
  37230. return this._computeParticleTexture;
  37231. },
  37232. /**
  37233. * Tells to setParticle() to compute the particle textures or not.
  37234. * Default value : true. The SPS is faster when it's set to false.
  37235. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37236. */
  37237. set: function (val) {
  37238. this._computeParticleTexture = val;
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37244. get: function () {
  37245. return this._computeParticleVertex;
  37246. },
  37247. /**
  37248. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37249. * Default value : false. The SPS is faster when it's set to false.
  37250. * Note : the particle custom vertex positions aren't stored values.
  37251. */
  37252. set: function (val) {
  37253. this._computeParticleVertex = val;
  37254. },
  37255. enumerable: true,
  37256. configurable: true
  37257. });
  37258. // =======================================================================
  37259. // Particle behavior logic
  37260. // these following methods may be overwritten by the user to fit his needs
  37261. /**
  37262. * This function does nothing. It may be overwritten to set all the particles first values.
  37263. * The SPS doesn't call this function, you may have to call it by your own.
  37264. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37265. */
  37266. SolidParticleSystem.prototype.initParticles = function () {
  37267. };
  37268. /**
  37269. * This function does nothing. It may be overwritten to recycle a particle.
  37270. * The SPS doesn't call this function, you may have to call it by your own.
  37271. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37272. */
  37273. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37274. return particle;
  37275. };
  37276. /**
  37277. * Updates a particle : this function should be overwritten by the user.
  37278. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37279. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37280. * ex : just set a particle position or velocity and recycle conditions
  37281. */
  37282. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37283. return particle;
  37284. };
  37285. /**
  37286. * Updates a vertex of a particle : it can be overwritten by the user.
  37287. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37288. * @param particle the current particle
  37289. * @param vertex the current index of the current particle
  37290. * @param pt the index of the current vertex in the particle shape
  37291. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37292. * ex : just set a vertex particle position
  37293. */
  37294. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37295. return vertex;
  37296. };
  37297. /**
  37298. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37299. * This does nothing and may be overwritten by the user.
  37300. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37301. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37302. * @param update the boolean update value actually passed to setParticles()
  37303. */
  37304. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37305. };
  37306. /**
  37307. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37308. * This will be passed three parameters.
  37309. * This does nothing and may be overwritten by the user.
  37310. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37311. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37312. * @param update the boolean update value actually passed to setParticles()
  37313. */
  37314. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37315. };
  37316. return SolidParticleSystem;
  37317. })();
  37318. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37319. })(BABYLON || (BABYLON = {}));
  37320. var BABYLON;
  37321. (function (BABYLON) {
  37322. // We're mainly based on the logic defined into the FreeCamera code
  37323. var UniversalCamera = (function (_super) {
  37324. __extends(UniversalCamera, _super);
  37325. function UniversalCamera(name, position, scene) {
  37326. var _this = this;
  37327. _super.call(this, name, position, scene);
  37328. this.gamepadAngularSensibility = 200;
  37329. this.gamepadMoveSensibility = 40;
  37330. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  37331. }
  37332. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  37333. // Only the first gamepad can control the camera
  37334. if (gamepad.index === 0) {
  37335. this.gamepad = gamepad;
  37336. }
  37337. };
  37338. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  37339. _super.prototype.attachControl.call(this, canvas, false);
  37340. };
  37341. UniversalCamera.prototype.detachControl = function (canvas) {
  37342. _super.prototype.detachControl.call(this, canvas);
  37343. };
  37344. UniversalCamera.prototype._checkInputs = function () {
  37345. if (this.gamepad) {
  37346. var LSValues = this.gamepad.leftStick;
  37347. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  37348. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  37349. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  37350. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  37351. var RSValues = this.gamepad.rightStick;
  37352. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  37353. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  37354. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  37355. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  37356. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  37357. var speed = this._computeLocalCameraSpeed() * 50.0;
  37358. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  37359. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  37360. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  37361. }
  37362. _super.prototype._checkInputs.call(this);
  37363. };
  37364. UniversalCamera.prototype.dispose = function () {
  37365. this._gamepads.dispose();
  37366. _super.prototype.dispose.call(this);
  37367. };
  37368. return UniversalCamera;
  37369. })(BABYLON.TouchCamera);
  37370. BABYLON.UniversalCamera = UniversalCamera;
  37371. })(BABYLON || (BABYLON = {}));
  37372. var BABYLON;
  37373. (function (BABYLON) {
  37374. var Gamepads = (function () {
  37375. function Gamepads(ongamedpadconnected) {
  37376. var _this = this;
  37377. this.babylonGamepads = [];
  37378. this.oneGamepadConnected = false;
  37379. this.isMonitoring = false;
  37380. this.gamepadEventSupported = 'GamepadEvent' in window;
  37381. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37382. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37383. this._callbackGamepadConnected = ongamedpadconnected;
  37384. if (this.gamepadSupportAvailable) {
  37385. // Checking if the gamepad connected event is supported (like in Firefox)
  37386. if (this.gamepadEventSupported) {
  37387. window.addEventListener('gamepadconnected', function (evt) {
  37388. _this._onGamepadConnected(evt);
  37389. }, false);
  37390. window.addEventListener('gamepaddisconnected', function (evt) {
  37391. _this._onGamepadDisconnected(evt);
  37392. }, false);
  37393. }
  37394. else {
  37395. this._startMonitoringGamepads();
  37396. }
  37397. }
  37398. }
  37399. Gamepads.prototype.dispose = function () {
  37400. if (Gamepads.gamepadDOMInfo) {
  37401. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37402. }
  37403. };
  37404. Gamepads.prototype._onGamepadConnected = function (evt) {
  37405. var newGamepad = this._addNewGamepad(evt.gamepad);
  37406. if (this._callbackGamepadConnected)
  37407. this._callbackGamepadConnected(newGamepad);
  37408. this._startMonitoringGamepads();
  37409. };
  37410. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37411. if (!this.oneGamepadConnected) {
  37412. this.oneGamepadConnected = true;
  37413. if (Gamepads.gamepadDOMInfo) {
  37414. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37415. Gamepads.gamepadDOMInfo = null;
  37416. }
  37417. }
  37418. var newGamepad;
  37419. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37420. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37421. }
  37422. else {
  37423. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37424. }
  37425. this.babylonGamepads.push(newGamepad);
  37426. return newGamepad;
  37427. };
  37428. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37429. // Remove the gamepad from the list of gamepads to monitor.
  37430. for (var i in this.babylonGamepads) {
  37431. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37432. this.babylonGamepads.splice(i, 1);
  37433. break;
  37434. }
  37435. }
  37436. // If no gamepads are left, stop the polling loop.
  37437. if (this.babylonGamepads.length == 0) {
  37438. this._stopMonitoringGamepads();
  37439. }
  37440. };
  37441. Gamepads.prototype._startMonitoringGamepads = function () {
  37442. if (!this.isMonitoring) {
  37443. this.isMonitoring = true;
  37444. this._checkGamepadsStatus();
  37445. }
  37446. };
  37447. Gamepads.prototype._stopMonitoringGamepads = function () {
  37448. this.isMonitoring = false;
  37449. };
  37450. Gamepads.prototype._checkGamepadsStatus = function () {
  37451. var _this = this;
  37452. // updating gamepad objects
  37453. this._updateGamepadObjects();
  37454. for (var i in this.babylonGamepads) {
  37455. this.babylonGamepads[i].update();
  37456. }
  37457. if (this.isMonitoring) {
  37458. if (window.requestAnimationFrame) {
  37459. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37460. }
  37461. else if (window.mozRequestAnimationFrame) {
  37462. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37463. }
  37464. else if (window.webkitRequestAnimationFrame) {
  37465. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37466. }
  37467. }
  37468. };
  37469. // This function is called only on Chrome, which does not yet support
  37470. // connection/disconnection events, but requires you to monitor
  37471. // an array for changes.
  37472. Gamepads.prototype._updateGamepadObjects = function () {
  37473. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37474. for (var i = 0; i < gamepads.length; i++) {
  37475. if (gamepads[i]) {
  37476. if (!(gamepads[i].index in this.babylonGamepads)) {
  37477. var newGamepad = this._addNewGamepad(gamepads[i]);
  37478. if (this._callbackGamepadConnected) {
  37479. this._callbackGamepadConnected(newGamepad);
  37480. }
  37481. }
  37482. else {
  37483. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37484. }
  37485. }
  37486. }
  37487. };
  37488. return Gamepads;
  37489. })();
  37490. BABYLON.Gamepads = Gamepads;
  37491. var StickValues = (function () {
  37492. function StickValues(x, y) {
  37493. this.x = x;
  37494. this.y = y;
  37495. }
  37496. return StickValues;
  37497. })();
  37498. BABYLON.StickValues = StickValues;
  37499. var Gamepad = (function () {
  37500. function Gamepad(id, index, browserGamepad) {
  37501. this.id = id;
  37502. this.index = index;
  37503. this.browserGamepad = browserGamepad;
  37504. if (this.browserGamepad.axes.length >= 2) {
  37505. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37506. }
  37507. if (this.browserGamepad.axes.length >= 4) {
  37508. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37509. }
  37510. }
  37511. Gamepad.prototype.onleftstickchanged = function (callback) {
  37512. this._onleftstickchanged = callback;
  37513. };
  37514. Gamepad.prototype.onrightstickchanged = function (callback) {
  37515. this._onrightstickchanged = callback;
  37516. };
  37517. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37518. get: function () {
  37519. return this._leftStick;
  37520. },
  37521. set: function (newValues) {
  37522. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37523. this._onleftstickchanged(newValues);
  37524. }
  37525. this._leftStick = newValues;
  37526. },
  37527. enumerable: true,
  37528. configurable: true
  37529. });
  37530. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37531. get: function () {
  37532. return this._rightStick;
  37533. },
  37534. set: function (newValues) {
  37535. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37536. this._onrightstickchanged(newValues);
  37537. }
  37538. this._rightStick = newValues;
  37539. },
  37540. enumerable: true,
  37541. configurable: true
  37542. });
  37543. Gamepad.prototype.update = function () {
  37544. if (this._leftStick) {
  37545. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37546. }
  37547. if (this._rightStick) {
  37548. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37549. }
  37550. };
  37551. return Gamepad;
  37552. })();
  37553. BABYLON.Gamepad = Gamepad;
  37554. var GenericPad = (function (_super) {
  37555. __extends(GenericPad, _super);
  37556. function GenericPad(id, index, gamepad) {
  37557. _super.call(this, id, index, gamepad);
  37558. this.id = id;
  37559. this.index = index;
  37560. this.gamepad = gamepad;
  37561. this._buttons = new Array(gamepad.buttons.length);
  37562. }
  37563. GenericPad.prototype.onbuttondown = function (callback) {
  37564. this._onbuttondown = callback;
  37565. };
  37566. GenericPad.prototype.onbuttonup = function (callback) {
  37567. this._onbuttonup = callback;
  37568. };
  37569. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37570. if (newValue !== currentValue) {
  37571. if (this._onbuttondown && newValue === 1) {
  37572. this._onbuttondown(buttonIndex);
  37573. }
  37574. if (this._onbuttonup && newValue === 0) {
  37575. this._onbuttonup(buttonIndex);
  37576. }
  37577. }
  37578. return newValue;
  37579. };
  37580. GenericPad.prototype.update = function () {
  37581. _super.prototype.update.call(this);
  37582. for (var index = 0; index < this._buttons.length; index++) {
  37583. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37584. }
  37585. };
  37586. return GenericPad;
  37587. })(Gamepad);
  37588. BABYLON.GenericPad = GenericPad;
  37589. (function (Xbox360Button) {
  37590. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37591. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37592. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37593. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37594. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37595. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37596. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37597. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37598. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37599. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37600. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37601. var Xbox360Button = BABYLON.Xbox360Button;
  37602. (function (Xbox360Dpad) {
  37603. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37604. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37605. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37606. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37607. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37608. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37609. var Xbox360Pad = (function (_super) {
  37610. __extends(Xbox360Pad, _super);
  37611. function Xbox360Pad() {
  37612. _super.apply(this, arguments);
  37613. this._leftTrigger = 0;
  37614. this._rightTrigger = 0;
  37615. this._buttonA = 0;
  37616. this._buttonB = 0;
  37617. this._buttonX = 0;
  37618. this._buttonY = 0;
  37619. this._buttonBack = 0;
  37620. this._buttonStart = 0;
  37621. this._buttonLB = 0;
  37622. this._buttonRB = 0;
  37623. this._buttonLeftStick = 0;
  37624. this._buttonRightStick = 0;
  37625. this._dPadUp = 0;
  37626. this._dPadDown = 0;
  37627. this._dPadLeft = 0;
  37628. this._dPadRight = 0;
  37629. }
  37630. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37631. this._onlefttriggerchanged = callback;
  37632. };
  37633. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37634. this._onrighttriggerchanged = callback;
  37635. };
  37636. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37637. get: function () {
  37638. return this._leftTrigger;
  37639. },
  37640. set: function (newValue) {
  37641. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37642. this._onlefttriggerchanged(newValue);
  37643. }
  37644. this._leftTrigger = newValue;
  37645. },
  37646. enumerable: true,
  37647. configurable: true
  37648. });
  37649. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37650. get: function () {
  37651. return this._rightTrigger;
  37652. },
  37653. set: function (newValue) {
  37654. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37655. this._onrighttriggerchanged(newValue);
  37656. }
  37657. this._rightTrigger = newValue;
  37658. },
  37659. enumerable: true,
  37660. configurable: true
  37661. });
  37662. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37663. this._onbuttondown = callback;
  37664. };
  37665. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37666. this._onbuttonup = callback;
  37667. };
  37668. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37669. this._ondpaddown = callback;
  37670. };
  37671. Xbox360Pad.prototype.ondpadup = function (callback) {
  37672. this._ondpadup = callback;
  37673. };
  37674. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37675. if (newValue !== currentValue) {
  37676. if (this._onbuttondown && newValue === 1) {
  37677. this._onbuttondown(buttonType);
  37678. }
  37679. if (this._onbuttonup && newValue === 0) {
  37680. this._onbuttonup(buttonType);
  37681. }
  37682. }
  37683. return newValue;
  37684. };
  37685. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37686. if (newValue !== currentValue) {
  37687. if (this._ondpaddown && newValue === 1) {
  37688. this._ondpaddown(buttonType);
  37689. }
  37690. if (this._ondpadup && newValue === 0) {
  37691. this._ondpadup(buttonType);
  37692. }
  37693. }
  37694. return newValue;
  37695. };
  37696. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37697. get: function () {
  37698. return this._buttonA;
  37699. },
  37700. set: function (value) {
  37701. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37702. },
  37703. enumerable: true,
  37704. configurable: true
  37705. });
  37706. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37707. get: function () {
  37708. return this._buttonB;
  37709. },
  37710. set: function (value) {
  37711. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37712. },
  37713. enumerable: true,
  37714. configurable: true
  37715. });
  37716. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37717. get: function () {
  37718. return this._buttonX;
  37719. },
  37720. set: function (value) {
  37721. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37722. },
  37723. enumerable: true,
  37724. configurable: true
  37725. });
  37726. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37727. get: function () {
  37728. return this._buttonY;
  37729. },
  37730. set: function (value) {
  37731. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37732. },
  37733. enumerable: true,
  37734. configurable: true
  37735. });
  37736. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37737. get: function () {
  37738. return this._buttonStart;
  37739. },
  37740. set: function (value) {
  37741. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37742. },
  37743. enumerable: true,
  37744. configurable: true
  37745. });
  37746. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37747. get: function () {
  37748. return this._buttonBack;
  37749. },
  37750. set: function (value) {
  37751. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37752. },
  37753. enumerable: true,
  37754. configurable: true
  37755. });
  37756. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37757. get: function () {
  37758. return this._buttonLB;
  37759. },
  37760. set: function (value) {
  37761. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37762. },
  37763. enumerable: true,
  37764. configurable: true
  37765. });
  37766. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37767. get: function () {
  37768. return this._buttonRB;
  37769. },
  37770. set: function (value) {
  37771. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37772. },
  37773. enumerable: true,
  37774. configurable: true
  37775. });
  37776. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37777. get: function () {
  37778. return this._buttonLeftStick;
  37779. },
  37780. set: function (value) {
  37781. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  37782. },
  37783. enumerable: true,
  37784. configurable: true
  37785. });
  37786. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  37787. get: function () {
  37788. return this._buttonRightStick;
  37789. },
  37790. set: function (value) {
  37791. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  37792. },
  37793. enumerable: true,
  37794. configurable: true
  37795. });
  37796. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  37797. get: function () {
  37798. return this._dPadUp;
  37799. },
  37800. set: function (value) {
  37801. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  37802. },
  37803. enumerable: true,
  37804. configurable: true
  37805. });
  37806. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  37807. get: function () {
  37808. return this._dPadDown;
  37809. },
  37810. set: function (value) {
  37811. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  37817. get: function () {
  37818. return this._dPadLeft;
  37819. },
  37820. set: function (value) {
  37821. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  37822. },
  37823. enumerable: true,
  37824. configurable: true
  37825. });
  37826. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  37827. get: function () {
  37828. return this._dPadRight;
  37829. },
  37830. set: function (value) {
  37831. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  37832. },
  37833. enumerable: true,
  37834. configurable: true
  37835. });
  37836. Xbox360Pad.prototype.update = function () {
  37837. _super.prototype.update.call(this);
  37838. this.buttonA = this.browserGamepad.buttons[0].value;
  37839. this.buttonB = this.browserGamepad.buttons[1].value;
  37840. this.buttonX = this.browserGamepad.buttons[2].value;
  37841. this.buttonY = this.browserGamepad.buttons[3].value;
  37842. this.buttonLB = this.browserGamepad.buttons[4].value;
  37843. this.buttonRB = this.browserGamepad.buttons[5].value;
  37844. this.leftTrigger = this.browserGamepad.buttons[6].value;
  37845. this.rightTrigger = this.browserGamepad.buttons[7].value;
  37846. this.buttonBack = this.browserGamepad.buttons[8].value;
  37847. this.buttonStart = this.browserGamepad.buttons[9].value;
  37848. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  37849. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  37850. this.dPadUp = this.browserGamepad.buttons[12].value;
  37851. this.dPadDown = this.browserGamepad.buttons[13].value;
  37852. this.dPadLeft = this.browserGamepad.buttons[14].value;
  37853. this.dPadRight = this.browserGamepad.buttons[15].value;
  37854. };
  37855. return Xbox360Pad;
  37856. })(Gamepad);
  37857. BABYLON.Xbox360Pad = Xbox360Pad;
  37858. })(BABYLON || (BABYLON = {}));
  37859. var BABYLON;
  37860. (function (BABYLON) {
  37861. // We're mainly based on the logic defined into the FreeCamera code
  37862. var GamepadCamera = (function (_super) {
  37863. __extends(GamepadCamera, _super);
  37864. function GamepadCamera(name, position, scene) {
  37865. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  37866. _super.call(this, name, position, scene);
  37867. }
  37868. return GamepadCamera;
  37869. })(BABYLON.UniversalCamera);
  37870. BABYLON.GamepadCamera = GamepadCamera;
  37871. })(BABYLON || (BABYLON = {}));
  37872. var BABYLON;
  37873. (function (BABYLON) {
  37874. var AnaglyphFreeCamera = (function (_super) {
  37875. __extends(AnaglyphFreeCamera, _super);
  37876. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  37877. _super.call(this, name, position, scene);
  37878. this.interaxialDistance = interaxialDistance;
  37879. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37880. }
  37881. return AnaglyphFreeCamera;
  37882. })(BABYLON.FreeCamera);
  37883. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  37884. var AnaglyphArcRotateCamera = (function (_super) {
  37885. __extends(AnaglyphArcRotateCamera, _super);
  37886. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  37887. _super.call(this, name, alpha, beta, radius, target, scene);
  37888. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37889. }
  37890. return AnaglyphArcRotateCamera;
  37891. })(BABYLON.ArcRotateCamera);
  37892. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  37893. var AnaglyphGamepadCamera = (function (_super) {
  37894. __extends(AnaglyphGamepadCamera, _super);
  37895. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  37896. _super.call(this, name, position, scene);
  37897. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  37898. }
  37899. return AnaglyphGamepadCamera;
  37900. })(BABYLON.GamepadCamera);
  37901. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  37902. var StereoscopicFreeCamera = (function (_super) {
  37903. __extends(StereoscopicFreeCamera, _super);
  37904. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  37905. _super.call(this, name, position, scene);
  37906. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37907. }
  37908. return StereoscopicFreeCamera;
  37909. })(BABYLON.FreeCamera);
  37910. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  37911. var StereoscopicArcRotateCamera = (function (_super) {
  37912. __extends(StereoscopicArcRotateCamera, _super);
  37913. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  37914. _super.call(this, name, alpha, beta, radius, target, scene);
  37915. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37916. }
  37917. return StereoscopicArcRotateCamera;
  37918. })(BABYLON.ArcRotateCamera);
  37919. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  37920. var StereoscopicGamepadCamera = (function (_super) {
  37921. __extends(StereoscopicGamepadCamera, _super);
  37922. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  37923. _super.call(this, name, position, scene);
  37924. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  37925. }
  37926. return StereoscopicGamepadCamera;
  37927. })(BABYLON.GamepadCamera);
  37928. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  37929. })(BABYLON || (BABYLON = {}));
  37930. 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(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\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#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// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(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 REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\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 + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, 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 vec2 scale;\r\nuniform vec2 offset;\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\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 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}"};
  37931. 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=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,y=0,c=0,p=0,l=0,x=0,z=0,w=-1,v=0,g=M.Vector3[0],d=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,g),g.normalize(),i.Dot(h,g)<0&&(w=1),d=i.Dot(e,T),d=Math.min(1,Math.max(-1,d)),c=Math.acos(d)*w,i.Dot(T,a)<0&&(c=Math.PI+c,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,g),g.normalize(),i.Dot(T,g)<0&&(w=1),d=i.Dot(h,R),d=Math.min(1,Math.max(-1,d)),y=Math.acos(d)*w,i.Dot(_,u)<0&&(y=Math.PI+y,v++),w=-1,i.CrossToRef(a,T,g),g.normalize(),i.Dot(g,u)<0&&(w=1),d=i.Dot(T,a),d=Math.min(1,Math.max(-1,d)),m=-Math.acos(d)*w,0>d&&2>v&&(m=Math.PI+m),s.x=y,s.y=m,s.z=c},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(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,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,Z=s*x-a*p,I=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,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*Z+o*I)*b,t.m[10]=(i*P-n*Z+o*E)*b,t.m[14]=-(i*C-n*I+r*E)*b,t.m[3]=-(n*L-r*q+o*S)*b,t.m[7]=(i*L-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*S-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],Z=t.m[12],I=t.m[13],E=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*g+o*_+s*A+e*I,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*Z,i[n+5]=h*g+a*_+u*A+m*I,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*Z,i[n+9]=y*g+c*_+p*A+f*I,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*Z,i[n+13]=l*g+x*_+z*A+w*I,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;\n},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){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.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),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={}));";
  37932. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37933. module.exports = BABYLON;
  37934. };