babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936
  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 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 = Vector3.Normalize(axis1);
  870. var w = Vector3.Normalize(axis3);
  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;
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1;
  890. var v1;
  891. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  892. z = 1.0;
  893. }
  894. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  895. x = 1.0;
  896. }
  897. else {
  898. t = w.z / w.x;
  899. x = -t * Math.sqrt(1 / (1 + t * t));
  900. z = Math.sqrt(1 / (1 + t * t));
  901. }
  902. u1 = new Vector3(x, y, z);
  903. u1.normalize();
  904. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  905. v1.normalize();
  906. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  907. cross.normalize();
  908. if (Vector3.Dot(w, cross) < 0) {
  909. sign = 1.0;
  910. }
  911. dot = Vector3.Dot(u, u1);
  912. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  913. roll = Math.acos(dot) * sign;
  914. if (Vector3.Dot(u1, X) < 0) {
  915. roll = Math.PI + roll;
  916. u1 = u1.scaleInPlace(-1);
  917. v1 = v1.scaleInPlace(-1);
  918. nbRevert++;
  919. }
  920. // step 2 : rotate around u1
  921. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  922. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  923. var w2;
  924. var v2;
  925. x = 0.0;
  926. y = 0.0;
  927. z = 0.0;
  928. sign = -1;
  929. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  930. x = 1.0;
  931. }
  932. else {
  933. t = u1.z / u1.x;
  934. x = -t * Math.sqrt(1 / (1 + t * t));
  935. z = Math.sqrt(1 / (1 + t * t));
  936. }
  937. w2 = new Vector3(x, y, z);
  938. w2.normalize();
  939. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. cross = Vector3.Cross(w, w2); // 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. v2 = v2.scaleInPlace(-1);
  952. w2 = w2.scaleInPlace(-1);
  953. nbRevert++;
  954. }
  955. // step 3 : rotate around v2
  956. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  957. sign = -1;
  958. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  959. cross.normalize();
  960. if (Vector3.Dot(cross, Y) < 0) {
  961. sign = 1.0;
  962. }
  963. dot = Vector3.Dot(u1, X);
  964. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  965. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  966. if (dot < 0 && nbRevert < 2) {
  967. yaw = Math.PI + yaw;
  968. }
  969. ref.x = pitch;
  970. ref.y = yaw;
  971. ref.z = roll;
  972. };
  973. return Vector3;
  974. })();
  975. BABYLON.Vector3 = Vector3;
  976. //Vector4 class created for EulerAngle class conversion to Quaternion
  977. var Vector4 = (function () {
  978. function Vector4(x, y, z, w) {
  979. this.x = x;
  980. this.y = y;
  981. this.z = z;
  982. this.w = w;
  983. }
  984. Vector4.prototype.toString = function () {
  985. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  986. };
  987. // Operators
  988. Vector4.prototype.asArray = function () {
  989. var result = [];
  990. this.toArray(result, 0);
  991. return result;
  992. };
  993. Vector4.prototype.toArray = function (array, index) {
  994. if (index === undefined) {
  995. index = 0;
  996. }
  997. array[index] = this.x;
  998. array[index + 1] = this.y;
  999. array[index + 2] = this.z;
  1000. array[index + 3] = this.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.addInPlace = function (otherVector) {
  1004. this.x += otherVector.x;
  1005. this.y += otherVector.y;
  1006. this.z += otherVector.z;
  1007. this.w += otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.add = function (otherVector) {
  1011. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1012. };
  1013. Vector4.prototype.addToRef = function (otherVector, result) {
  1014. result.x = this.x + otherVector.x;
  1015. result.y = this.y + otherVector.y;
  1016. result.z = this.z + otherVector.z;
  1017. result.w = this.w + otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractInPlace = function (otherVector) {
  1021. this.x -= otherVector.x;
  1022. this.y -= otherVector.y;
  1023. this.z -= otherVector.z;
  1024. this.w -= otherVector.w;
  1025. return this;
  1026. };
  1027. Vector4.prototype.subtract = function (otherVector) {
  1028. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1029. };
  1030. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1031. result.x = this.x - otherVector.x;
  1032. result.y = this.y - otherVector.y;
  1033. result.z = this.z - otherVector.z;
  1034. result.w = this.w - otherVector.w;
  1035. return this;
  1036. };
  1037. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1038. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1039. };
  1040. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1041. result.x = this.x - x;
  1042. result.y = this.y - y;
  1043. result.z = this.z - z;
  1044. result.w = this.w - w;
  1045. return this;
  1046. };
  1047. Vector4.prototype.negate = function () {
  1048. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1049. };
  1050. Vector4.prototype.scaleInPlace = function (scale) {
  1051. this.x *= scale;
  1052. this.y *= scale;
  1053. this.z *= scale;
  1054. this.w *= scale;
  1055. return this;
  1056. };
  1057. Vector4.prototype.scale = function (scale) {
  1058. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1059. };
  1060. Vector4.prototype.scaleToRef = function (scale, result) {
  1061. result.x = this.x * scale;
  1062. result.y = this.y * scale;
  1063. result.z = this.z * scale;
  1064. result.w = this.w * scale;
  1065. };
  1066. Vector4.prototype.equals = function (otherVector) {
  1067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1068. };
  1069. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1070. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1071. return otherVector
  1072. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1074. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1075. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1076. };
  1077. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1078. return this.x === x && this.y === y && this.z === z && this.w === w;
  1079. };
  1080. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1081. this.x *= otherVector.x;
  1082. this.y *= otherVector.y;
  1083. this.z *= otherVector.z;
  1084. this.w *= otherVector.w;
  1085. return this;
  1086. };
  1087. Vector4.prototype.multiply = function (otherVector) {
  1088. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1089. };
  1090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1091. result.x = this.x * otherVector.x;
  1092. result.y = this.y * otherVector.y;
  1093. result.z = this.z * otherVector.z;
  1094. result.w = this.w * otherVector.w;
  1095. return this;
  1096. };
  1097. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1098. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1099. };
  1100. Vector4.prototype.divide = function (otherVector) {
  1101. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1102. };
  1103. Vector4.prototype.divideToRef = function (otherVector, result) {
  1104. result.x = this.x / otherVector.x;
  1105. result.y = this.y / otherVector.y;
  1106. result.z = this.z / otherVector.z;
  1107. result.w = this.w / otherVector.w;
  1108. return this;
  1109. };
  1110. Vector4.prototype.MinimizeInPlace = function (other) {
  1111. if (other.x < this.x)
  1112. this.x = other.x;
  1113. if (other.y < this.y)
  1114. this.y = other.y;
  1115. if (other.z < this.z)
  1116. this.z = other.z;
  1117. if (other.w < this.w)
  1118. this.w = other.w;
  1119. return this;
  1120. };
  1121. Vector4.prototype.MaximizeInPlace = function (other) {
  1122. if (other.x > this.x)
  1123. this.x = other.x;
  1124. if (other.y > this.y)
  1125. this.y = other.y;
  1126. if (other.z > this.z)
  1127. this.z = other.z;
  1128. if (other.w > this.w)
  1129. this.w = other.w;
  1130. return this;
  1131. };
  1132. // Properties
  1133. Vector4.prototype.length = function () {
  1134. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1135. };
  1136. Vector4.prototype.lengthSquared = function () {
  1137. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1138. };
  1139. // Methods
  1140. Vector4.prototype.normalize = function () {
  1141. var len = this.length();
  1142. if (len === 0)
  1143. return this;
  1144. var num = 1.0 / len;
  1145. this.x *= num;
  1146. this.y *= num;
  1147. this.z *= num;
  1148. this.w *= num;
  1149. return this;
  1150. };
  1151. Vector4.prototype.clone = function () {
  1152. return new Vector4(this.x, this.y, this.z, this.w);
  1153. };
  1154. Vector4.prototype.copyFrom = function (source) {
  1155. this.x = source.x;
  1156. this.y = source.y;
  1157. this.z = source.z;
  1158. this.w = source.w;
  1159. return this;
  1160. };
  1161. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1162. this.x = x;
  1163. this.y = y;
  1164. this.z = z;
  1165. this.w = w;
  1166. return this;
  1167. };
  1168. // Statics
  1169. Vector4.FromArray = function (array, offset) {
  1170. if (!offset) {
  1171. offset = 0;
  1172. }
  1173. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1174. };
  1175. Vector4.FromArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1182. result.x = array[offset];
  1183. result.y = array[offset + 1];
  1184. result.z = array[offset + 2];
  1185. result.w = array[offset + 3];
  1186. };
  1187. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1188. result.x = x;
  1189. result.y = y;
  1190. result.z = z;
  1191. result.w = w;
  1192. };
  1193. Vector4.Zero = function () {
  1194. return new Vector4(0, 0, 0, 0);
  1195. };
  1196. Vector4.Normalize = function (vector) {
  1197. var result = Vector4.Zero();
  1198. Vector4.NormalizeToRef(vector, result);
  1199. return result;
  1200. };
  1201. Vector4.NormalizeToRef = function (vector, result) {
  1202. result.copyFrom(vector);
  1203. result.normalize();
  1204. };
  1205. Vector4.Minimize = function (left, right) {
  1206. var min = left.clone();
  1207. min.MinimizeInPlace(right);
  1208. return min;
  1209. };
  1210. Vector4.Maximize = function (left, right) {
  1211. var max = left.clone();
  1212. max.MaximizeInPlace(right);
  1213. return max;
  1214. };
  1215. Vector4.Distance = function (value1, value2) {
  1216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1217. };
  1218. Vector4.DistanceSquared = function (value1, value2) {
  1219. var x = value1.x - value2.x;
  1220. var y = value1.y - value2.y;
  1221. var z = value1.z - value2.z;
  1222. var w = value1.w - value2.w;
  1223. return (x * x) + (y * y) + (z * z) + (w * w);
  1224. };
  1225. Vector4.Center = function (value1, value2) {
  1226. var center = value1.add(value2);
  1227. center.scaleInPlace(0.5);
  1228. return center;
  1229. };
  1230. return Vector4;
  1231. })();
  1232. BABYLON.Vector4 = Vector4;
  1233. var Quaternion = (function () {
  1234. function Quaternion(x, y, z, w) {
  1235. if (x === void 0) { x = 0; }
  1236. if (y === void 0) { y = 0; }
  1237. if (z === void 0) { z = 0; }
  1238. if (w === void 0) { w = 1; }
  1239. this.x = x;
  1240. this.y = y;
  1241. this.z = z;
  1242. this.w = w;
  1243. }
  1244. Quaternion.prototype.toString = function () {
  1245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1246. };
  1247. Quaternion.prototype.asArray = function () {
  1248. return [this.x, this.y, this.z, this.w];
  1249. };
  1250. Quaternion.prototype.equals = function (otherQuaternion) {
  1251. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1252. };
  1253. Quaternion.prototype.clone = function () {
  1254. return new Quaternion(this.x, this.y, this.z, this.w);
  1255. };
  1256. Quaternion.prototype.copyFrom = function (other) {
  1257. this.x = other.x;
  1258. this.y = other.y;
  1259. this.z = other.z;
  1260. this.w = other.w;
  1261. return this;
  1262. };
  1263. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1264. this.x = x;
  1265. this.y = y;
  1266. this.z = z;
  1267. this.w = w;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.add = function (other) {
  1271. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1272. };
  1273. Quaternion.prototype.subtract = function (other) {
  1274. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1275. };
  1276. Quaternion.prototype.scale = function (value) {
  1277. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1278. };
  1279. Quaternion.prototype.multiply = function (q1) {
  1280. var result = new Quaternion(0, 0, 0, 1.0);
  1281. this.multiplyToRef(q1, result);
  1282. return result;
  1283. };
  1284. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1285. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1286. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1287. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1288. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1289. result.copyFromFloats(x, y, z, w);
  1290. return this;
  1291. };
  1292. Quaternion.prototype.multiplyInPlace = function (q1) {
  1293. this.multiplyToRef(q1, this);
  1294. return this;
  1295. };
  1296. Quaternion.prototype.length = function () {
  1297. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1298. };
  1299. Quaternion.prototype.normalize = function () {
  1300. var length = 1.0 / this.length();
  1301. this.x *= length;
  1302. this.y *= length;
  1303. this.z *= length;
  1304. this.w *= length;
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toEulerAngles = function () {
  1308. var result = Vector3.Zero();
  1309. this.toEulerAnglesToRef(result);
  1310. return result;
  1311. };
  1312. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1313. //result is an EulerAngles in the in the z-x-z convention
  1314. var qx = this.x;
  1315. var qy = this.y;
  1316. var qz = this.z;
  1317. var qw = this.w;
  1318. var qxy = qx * qy;
  1319. var qxz = qx * qz;
  1320. var qwy = qw * qy;
  1321. var qwz = qw * qz;
  1322. var qwx = qw * qx;
  1323. var qyz = qy * qz;
  1324. var sqx = qx * qx;
  1325. var sqy = qy * qy;
  1326. var determinant = sqx + sqy;
  1327. if (determinant !== 0.000 && determinant !== 1.000) {
  1328. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1329. result.y = Math.acos(1 - 2 * determinant);
  1330. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1331. }
  1332. else {
  1333. if (determinant === 0.0) {
  1334. result.x = 0.0;
  1335. result.y = 0.0;
  1336. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1337. }
  1338. else {
  1339. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1340. result.y = Math.PI;
  1341. result.z = 0.0;
  1342. }
  1343. }
  1344. return this;
  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. return Viewport;
  2244. })();
  2245. BABYLON.Viewport = Viewport;
  2246. var Frustum = (function () {
  2247. function Frustum() {
  2248. }
  2249. Frustum.GetPlanes = function (transform) {
  2250. var frustumPlanes = [];
  2251. for (var index = 0; index < 6; index++) {
  2252. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2253. }
  2254. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2255. return frustumPlanes;
  2256. };
  2257. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2258. // Near
  2259. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2260. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2261. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2262. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2263. frustumPlanes[0].normalize();
  2264. // Far
  2265. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2266. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2267. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2268. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2269. frustumPlanes[1].normalize();
  2270. // Left
  2271. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2272. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2273. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2274. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2275. frustumPlanes[2].normalize();
  2276. // Right
  2277. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2278. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2279. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2280. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2281. frustumPlanes[3].normalize();
  2282. // Top
  2283. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2284. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2285. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2286. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2287. frustumPlanes[4].normalize();
  2288. // Bottom
  2289. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2290. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2291. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2292. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2293. frustumPlanes[5].normalize();
  2294. };
  2295. return Frustum;
  2296. })();
  2297. BABYLON.Frustum = Frustum;
  2298. var Ray = (function () {
  2299. function Ray(origin, direction, length) {
  2300. if (length === void 0) { length = Number.MAX_VALUE; }
  2301. this.origin = origin;
  2302. this.direction = direction;
  2303. this.length = length;
  2304. }
  2305. // Methods
  2306. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2307. var d = 0.0;
  2308. var maxValue = Number.MAX_VALUE;
  2309. var inv;
  2310. var min;
  2311. var max;
  2312. var temp;
  2313. if (Math.abs(this.direction.x) < 0.0000001) {
  2314. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2315. return false;
  2316. }
  2317. }
  2318. else {
  2319. inv = 1.0 / this.direction.x;
  2320. min = (minimum.x - this.origin.x) * inv;
  2321. max = (maximum.x - this.origin.x) * inv;
  2322. if (max === -Infinity) {
  2323. max = Infinity;
  2324. }
  2325. if (min > max) {
  2326. temp = min;
  2327. min = max;
  2328. max = temp;
  2329. }
  2330. d = Math.max(min, d);
  2331. maxValue = Math.min(max, maxValue);
  2332. if (d > maxValue) {
  2333. return false;
  2334. }
  2335. }
  2336. if (Math.abs(this.direction.y) < 0.0000001) {
  2337. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2338. return false;
  2339. }
  2340. }
  2341. else {
  2342. inv = 1.0 / this.direction.y;
  2343. min = (minimum.y - this.origin.y) * inv;
  2344. max = (maximum.y - this.origin.y) * inv;
  2345. if (max === -Infinity) {
  2346. max = Infinity;
  2347. }
  2348. if (min > max) {
  2349. temp = min;
  2350. min = max;
  2351. max = temp;
  2352. }
  2353. d = Math.max(min, d);
  2354. maxValue = Math.min(max, maxValue);
  2355. if (d > maxValue) {
  2356. return false;
  2357. }
  2358. }
  2359. if (Math.abs(this.direction.z) < 0.0000001) {
  2360. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2361. return false;
  2362. }
  2363. }
  2364. else {
  2365. inv = 1.0 / this.direction.z;
  2366. min = (minimum.z - this.origin.z) * inv;
  2367. max = (maximum.z - this.origin.z) * inv;
  2368. if (max === -Infinity) {
  2369. max = Infinity;
  2370. }
  2371. if (min > max) {
  2372. temp = min;
  2373. min = max;
  2374. max = temp;
  2375. }
  2376. d = Math.max(min, d);
  2377. maxValue = Math.min(max, maxValue);
  2378. if (d > maxValue) {
  2379. return false;
  2380. }
  2381. }
  2382. return true;
  2383. };
  2384. Ray.prototype.intersectsBox = function (box) {
  2385. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2386. };
  2387. Ray.prototype.intersectsSphere = function (sphere) {
  2388. var x = sphere.center.x - this.origin.x;
  2389. var y = sphere.center.y - this.origin.y;
  2390. var z = sphere.center.z - this.origin.z;
  2391. var pyth = (x * x) + (y * y) + (z * z);
  2392. var rr = sphere.radius * sphere.radius;
  2393. if (pyth <= rr) {
  2394. return true;
  2395. }
  2396. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2397. if (dot < 0.0) {
  2398. return false;
  2399. }
  2400. var temp = pyth - (dot * dot);
  2401. return temp <= rr;
  2402. };
  2403. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2404. if (!this._edge1) {
  2405. this._edge1 = Vector3.Zero();
  2406. this._edge2 = Vector3.Zero();
  2407. this._pvec = Vector3.Zero();
  2408. this._tvec = Vector3.Zero();
  2409. this._qvec = Vector3.Zero();
  2410. }
  2411. vertex1.subtractToRef(vertex0, this._edge1);
  2412. vertex2.subtractToRef(vertex0, this._edge2);
  2413. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2414. var det = Vector3.Dot(this._edge1, this._pvec);
  2415. if (det === 0) {
  2416. return null;
  2417. }
  2418. var invdet = 1 / det;
  2419. this.origin.subtractToRef(vertex0, this._tvec);
  2420. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2421. if (bu < 0 || bu > 1.0) {
  2422. return null;
  2423. }
  2424. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2425. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2426. if (bv < 0 || bu + bv > 1.0) {
  2427. return null;
  2428. }
  2429. //check if the distance is longer than the predefined length.
  2430. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2431. if (distance > this.length) {
  2432. return null;
  2433. }
  2434. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2435. };
  2436. // Statics
  2437. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2438. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2439. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2440. var direction = end.subtract(start);
  2441. direction.normalize();
  2442. return new Ray(start, direction);
  2443. };
  2444. /**
  2445. * 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
  2446. * transformed to the given world matrix.
  2447. * @param origin The origin point
  2448. * @param end The end point
  2449. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2450. */
  2451. Ray.CreateNewFromTo = function (origin, end, world) {
  2452. if (world === void 0) { world = Matrix.Identity(); }
  2453. var direction = end.subtract(origin);
  2454. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2455. direction.normalize();
  2456. return Ray.Transform(new Ray(origin, direction, length), world);
  2457. };
  2458. Ray.Transform = function (ray, matrix) {
  2459. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2460. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2461. return new Ray(newOrigin, newDirection, ray.length);
  2462. };
  2463. return Ray;
  2464. })();
  2465. BABYLON.Ray = Ray;
  2466. (function (Space) {
  2467. Space[Space["LOCAL"] = 0] = "LOCAL";
  2468. Space[Space["WORLD"] = 1] = "WORLD";
  2469. })(BABYLON.Space || (BABYLON.Space = {}));
  2470. var Space = BABYLON.Space;
  2471. var Axis = (function () {
  2472. function Axis() {
  2473. }
  2474. Axis.X = new Vector3(1, 0, 0);
  2475. Axis.Y = new Vector3(0, 1, 0);
  2476. Axis.Z = new Vector3(0, 0, 1);
  2477. return Axis;
  2478. })();
  2479. BABYLON.Axis = Axis;
  2480. ;
  2481. var BezierCurve = (function () {
  2482. function BezierCurve() {
  2483. }
  2484. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2485. // Extract X (which is equal to time here)
  2486. var f0 = 1 - 3 * x2 + 3 * x1;
  2487. var f1 = 3 * x2 - 6 * x1;
  2488. var f2 = 3 * x1;
  2489. var refinedT = t;
  2490. for (var i = 0; i < 5; i++) {
  2491. var refinedT2 = refinedT * refinedT;
  2492. var refinedT3 = refinedT2 * refinedT;
  2493. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2494. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2495. refinedT -= (x - t) * slope;
  2496. refinedT = Math.min(1, Math.max(0, refinedT));
  2497. }
  2498. // Resolve cubic bezier for the given x
  2499. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2500. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2501. Math.pow(refinedT, 3);
  2502. };
  2503. return BezierCurve;
  2504. })();
  2505. BABYLON.BezierCurve = BezierCurve;
  2506. (function (Orientation) {
  2507. Orientation[Orientation["CW"] = 0] = "CW";
  2508. Orientation[Orientation["CCW"] = 1] = "CCW";
  2509. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2510. var Orientation = BABYLON.Orientation;
  2511. var Angle = (function () {
  2512. function Angle(radians) {
  2513. var _this = this;
  2514. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2515. this.radians = function () { return _this._radians; };
  2516. this._radians = radians;
  2517. if (this._radians < 0)
  2518. this._radians += (2 * Math.PI);
  2519. }
  2520. Angle.BetweenTwoPoints = function (a, b) {
  2521. var delta = b.subtract(a);
  2522. var theta = Math.atan2(delta.y, delta.x);
  2523. return new Angle(theta);
  2524. };
  2525. Angle.FromRadians = function (radians) {
  2526. return new Angle(radians);
  2527. };
  2528. Angle.FromDegrees = function (degrees) {
  2529. return new Angle(degrees * Math.PI / 180);
  2530. };
  2531. return Angle;
  2532. })();
  2533. BABYLON.Angle = Angle;
  2534. var Arc2 = (function () {
  2535. function Arc2(startPoint, midPoint, endPoint) {
  2536. this.startPoint = startPoint;
  2537. this.midPoint = midPoint;
  2538. this.endPoint = endPoint;
  2539. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2540. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2541. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2542. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2543. 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);
  2544. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2545. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2546. var a1 = this.startAngle.degrees();
  2547. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2548. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2549. // angles correction
  2550. if (a2 - a1 > +180.0)
  2551. a2 -= 360.0;
  2552. if (a2 - a1 < -180.0)
  2553. a2 += 360.0;
  2554. if (a3 - a2 > +180.0)
  2555. a3 -= 360.0;
  2556. if (a3 - a2 < -180.0)
  2557. a3 += 360.0;
  2558. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2559. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2560. }
  2561. return Arc2;
  2562. })();
  2563. BABYLON.Arc2 = Arc2;
  2564. var PathCursor = (function () {
  2565. function PathCursor(path) {
  2566. this.path = path;
  2567. this._onchange = new Array();
  2568. this.value = 0;
  2569. this.animations = new Array();
  2570. }
  2571. PathCursor.prototype.getPoint = function () {
  2572. var point = this.path.getPointAtLengthPosition(this.value);
  2573. return new Vector3(point.x, 0, point.y);
  2574. };
  2575. PathCursor.prototype.moveAhead = function (step) {
  2576. if (step === void 0) { step = 0.002; }
  2577. this.move(step);
  2578. return this;
  2579. };
  2580. PathCursor.prototype.moveBack = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(-step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.move = function (step) {
  2586. if (Math.abs(step) > 1) {
  2587. throw "step size should be less than 1.";
  2588. }
  2589. this.value += step;
  2590. this.ensureLimits();
  2591. this.raiseOnChange();
  2592. return this;
  2593. };
  2594. PathCursor.prototype.ensureLimits = function () {
  2595. while (this.value > 1) {
  2596. this.value -= 1;
  2597. }
  2598. while (this.value < 0) {
  2599. this.value += 1;
  2600. }
  2601. return this;
  2602. };
  2603. // used by animation engine
  2604. PathCursor.prototype.markAsDirty = function (propertyName) {
  2605. this.ensureLimits();
  2606. this.raiseOnChange();
  2607. return this;
  2608. };
  2609. PathCursor.prototype.raiseOnChange = function () {
  2610. var _this = this;
  2611. this._onchange.forEach(function (f) { return f(_this); });
  2612. return this;
  2613. };
  2614. PathCursor.prototype.onchange = function (f) {
  2615. this._onchange.push(f);
  2616. return this;
  2617. };
  2618. return PathCursor;
  2619. })();
  2620. BABYLON.PathCursor = PathCursor;
  2621. var Path2 = (function () {
  2622. function Path2(x, y) {
  2623. this._points = new Array();
  2624. this._length = 0;
  2625. this.closed = false;
  2626. this._points.push(new Vector2(x, y));
  2627. }
  2628. Path2.prototype.addLineTo = function (x, y) {
  2629. if (closed) {
  2630. BABYLON.Tools.Error("cannot add lines to closed paths");
  2631. return this;
  2632. }
  2633. var newPoint = new Vector2(x, y);
  2634. var previousPoint = this._points[this._points.length - 1];
  2635. this._points.push(newPoint);
  2636. this._length += newPoint.subtract(previousPoint).length();
  2637. return this;
  2638. };
  2639. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2640. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2641. if (closed) {
  2642. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2643. return this;
  2644. }
  2645. var startPoint = this._points[this._points.length - 1];
  2646. var midPoint = new Vector2(midX, midY);
  2647. var endPoint = new Vector2(endX, endY);
  2648. var arc = new Arc2(startPoint, midPoint, endPoint);
  2649. var increment = arc.angle.radians() / numberOfSegments;
  2650. if (arc.orientation === Orientation.CW)
  2651. increment *= -1;
  2652. var currentAngle = arc.startAngle.radians() + increment;
  2653. for (var i = 0; i < numberOfSegments; i++) {
  2654. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2655. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2656. this.addLineTo(x, y);
  2657. currentAngle += increment;
  2658. }
  2659. return this;
  2660. };
  2661. Path2.prototype.close = function () {
  2662. this.closed = true;
  2663. return this;
  2664. };
  2665. Path2.prototype.length = function () {
  2666. var result = this._length;
  2667. if (!this.closed) {
  2668. var lastPoint = this._points[this._points.length - 1];
  2669. var firstPoint = this._points[0];
  2670. result += (firstPoint.subtract(lastPoint).length());
  2671. }
  2672. return result;
  2673. };
  2674. Path2.prototype.getPoints = function () {
  2675. return this._points;
  2676. };
  2677. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2678. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2679. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2680. return Vector2.Zero();
  2681. }
  2682. var lengthPosition = normalizedLengthPosition * this.length();
  2683. var previousOffset = 0;
  2684. for (var i = 0; i < this._points.length; i++) {
  2685. var j = (i + 1) % this._points.length;
  2686. var a = this._points[i];
  2687. var b = this._points[j];
  2688. var bToA = b.subtract(a);
  2689. var nextOffset = (bToA.length() + previousOffset);
  2690. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2691. var dir = bToA.normalize();
  2692. var localOffset = lengthPosition - previousOffset;
  2693. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2694. }
  2695. previousOffset = nextOffset;
  2696. }
  2697. BABYLON.Tools.Error("internal error");
  2698. return Vector2.Zero();
  2699. };
  2700. Path2.StartingAt = function (x, y) {
  2701. return new Path2(x, y);
  2702. };
  2703. return Path2;
  2704. })();
  2705. BABYLON.Path2 = Path2;
  2706. var Path3D = (function () {
  2707. /**
  2708. * new Path3D(path, normal, raw)
  2709. * path : an array of Vector3, the curve axis of the Path3D
  2710. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2711. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2712. */
  2713. function Path3D(path, firstNormal, raw) {
  2714. this.path = path;
  2715. this._curve = new Array();
  2716. this._distances = new Array();
  2717. this._tangents = new Array();
  2718. this._normals = new Array();
  2719. this._binormals = new Array();
  2720. for (var p = 0; p < path.length; p++) {
  2721. this._curve[p] = path[p].clone(); // hard copy
  2722. }
  2723. this._raw = raw || false;
  2724. this._compute(firstNormal);
  2725. }
  2726. Path3D.prototype.getCurve = function () {
  2727. return this._curve;
  2728. };
  2729. Path3D.prototype.getTangents = function () {
  2730. return this._tangents;
  2731. };
  2732. Path3D.prototype.getNormals = function () {
  2733. return this._normals;
  2734. };
  2735. Path3D.prototype.getBinormals = function () {
  2736. return this._binormals;
  2737. };
  2738. Path3D.prototype.getDistances = function () {
  2739. return this._distances;
  2740. };
  2741. Path3D.prototype.update = function (path, firstNormal) {
  2742. for (var p = 0; p < path.length; p++) {
  2743. this._curve[p].x = path[p].x;
  2744. this._curve[p].y = path[p].y;
  2745. this._curve[p].z = path[p].z;
  2746. }
  2747. this._compute(firstNormal);
  2748. return this;
  2749. };
  2750. // private function compute() : computes tangents, normals and binormals
  2751. Path3D.prototype._compute = function (firstNormal) {
  2752. var l = this._curve.length;
  2753. // first and last tangents
  2754. this._tangents[0] = this._getFirstNonNullVector(0);
  2755. if (!this._raw) {
  2756. this._tangents[0].normalize();
  2757. }
  2758. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2759. if (!this._raw) {
  2760. this._tangents[l - 1].normalize();
  2761. }
  2762. // normals and binormals at first point : arbitrary vector with _normalVector()
  2763. var tg0 = this._tangents[0];
  2764. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2765. this._normals[0] = pp0;
  2766. if (!this._raw) {
  2767. this._normals[0].normalize();
  2768. }
  2769. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2770. if (!this._raw) {
  2771. this._binormals[0].normalize();
  2772. }
  2773. this._distances[0] = 0;
  2774. // normals and binormals : next points
  2775. var prev; // previous vector (segment)
  2776. var cur; // current vector (segment)
  2777. var curTang; // current tangent
  2778. // previous normal
  2779. var prevBinor; // previous binormal
  2780. for (var i = 1; i < l; i++) {
  2781. // tangents
  2782. prev = this._getLastNonNullVector(i);
  2783. if (i < l - 1) {
  2784. cur = this._getFirstNonNullVector(i);
  2785. this._tangents[i] = prev.add(cur);
  2786. this._tangents[i].normalize();
  2787. }
  2788. this._distances[i] = this._distances[i - 1] + prev.length();
  2789. // normals and binormals
  2790. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2791. curTang = this._tangents[i];
  2792. prevBinor = this._binormals[i - 1];
  2793. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2794. if (!this._raw) {
  2795. this._normals[i].normalize();
  2796. }
  2797. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2798. if (!this._raw) {
  2799. this._binormals[i].normalize();
  2800. }
  2801. }
  2802. };
  2803. // private function getFirstNonNullVector(index)
  2804. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2805. Path3D.prototype._getFirstNonNullVector = function (index) {
  2806. var i = 1;
  2807. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2808. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2809. i++;
  2810. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2811. }
  2812. return nNVector;
  2813. };
  2814. // private function getLastNonNullVector(index)
  2815. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2816. Path3D.prototype._getLastNonNullVector = function (index) {
  2817. var i = 1;
  2818. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2819. while (nLVector.length() === 0 && index > i + 1) {
  2820. i++;
  2821. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2822. }
  2823. return nLVector;
  2824. };
  2825. // private function normalVector(v0, vt, va) :
  2826. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2827. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2828. Path3D.prototype._normalVector = function (v0, vt, va) {
  2829. var normal0;
  2830. if (va === undefined || va === null) {
  2831. var point;
  2832. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2833. point = new Vector3(0, -1, 0);
  2834. }
  2835. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2836. point = new Vector3(1, 0, 0);
  2837. }
  2838. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2839. point = new Vector3(0, 0, 1);
  2840. }
  2841. normal0 = Vector3.Cross(vt, point);
  2842. }
  2843. else {
  2844. normal0 = Vector3.Cross(vt, va);
  2845. Vector3.CrossToRef(normal0, vt, normal0);
  2846. }
  2847. normal0.normalize();
  2848. return normal0;
  2849. };
  2850. return Path3D;
  2851. })();
  2852. BABYLON.Path3D = Path3D;
  2853. var Curve3 = (function () {
  2854. function Curve3(points) {
  2855. this._length = 0;
  2856. this._points = points;
  2857. this._length = this._computeLength(points);
  2858. }
  2859. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2860. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2861. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2862. var bez = new Array();
  2863. var equation = function (t, val0, val1, val2) {
  2864. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2865. return res;
  2866. };
  2867. for (var i = 0; i <= nbPoints; i++) {
  2868. 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)));
  2869. }
  2870. return new Curve3(bez);
  2871. };
  2872. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2873. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2874. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2875. var bez = new Array();
  2876. var equation = function (t, val0, val1, val2, val3) {
  2877. 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;
  2878. return res;
  2879. };
  2880. for (var i = 0; i <= nbPoints; i++) {
  2881. 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)));
  2882. }
  2883. return new Curve3(bez);
  2884. };
  2885. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2886. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2887. var hermite = new Array();
  2888. var step = 1 / nbPoints;
  2889. for (var i = 0; i <= nbPoints; i++) {
  2890. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2891. }
  2892. return new Curve3(hermite);
  2893. };
  2894. Curve3.prototype.getPoints = function () {
  2895. return this._points;
  2896. };
  2897. Curve3.prototype.length = function () {
  2898. return this._length;
  2899. };
  2900. Curve3.prototype.continue = function (curve) {
  2901. var lastPoint = this._points[this._points.length - 1];
  2902. var continuedPoints = this._points.slice();
  2903. var curvePoints = curve.getPoints();
  2904. for (var i = 1; i < curvePoints.length; i++) {
  2905. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2906. }
  2907. var continuedCurve = new Curve3(continuedPoints);
  2908. return continuedCurve;
  2909. };
  2910. Curve3.prototype._computeLength = function (path) {
  2911. var l = 0;
  2912. for (var i = 1; i < path.length; i++) {
  2913. l += (path[i].subtract(path[i - 1])).length();
  2914. }
  2915. return l;
  2916. };
  2917. return Curve3;
  2918. })();
  2919. BABYLON.Curve3 = Curve3;
  2920. // Vertex formats
  2921. var PositionNormalVertex = (function () {
  2922. function PositionNormalVertex(position, normal) {
  2923. if (position === void 0) { position = Vector3.Zero(); }
  2924. if (normal === void 0) { normal = Vector3.Up(); }
  2925. this.position = position;
  2926. this.normal = normal;
  2927. }
  2928. PositionNormalVertex.prototype.clone = function () {
  2929. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2930. };
  2931. return PositionNormalVertex;
  2932. })();
  2933. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2934. var PositionNormalTextureVertex = (function () {
  2935. function PositionNormalTextureVertex(position, normal, uv) {
  2936. if (position === void 0) { position = Vector3.Zero(); }
  2937. if (normal === void 0) { normal = Vector3.Up(); }
  2938. if (uv === void 0) { uv = Vector2.Zero(); }
  2939. this.position = position;
  2940. this.normal = normal;
  2941. this.uv = uv;
  2942. }
  2943. PositionNormalTextureVertex.prototype.clone = function () {
  2944. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2945. };
  2946. return PositionNormalTextureVertex;
  2947. })();
  2948. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. var Database = (function () {
  2953. function Database(urlToScene, callbackManifestChecked) {
  2954. // Handling various flavors of prefixed version of IndexedDB
  2955. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2956. this.callbackManifestChecked = callbackManifestChecked;
  2957. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2958. this.db = null;
  2959. this.enableSceneOffline = false;
  2960. this.enableTexturesOffline = false;
  2961. this.manifestVersionFound = 0;
  2962. this.mustUpdateRessources = false;
  2963. this.hasReachedQuota = false;
  2964. if (!Database.IDBStorageEnabled) {
  2965. this.callbackManifestChecked(true);
  2966. }
  2967. else {
  2968. this.checkManifestFile();
  2969. }
  2970. }
  2971. Database.prototype.checkManifestFile = function () {
  2972. var _this = this;
  2973. function noManifestFile() {
  2974. that.enableSceneOffline = false;
  2975. that.enableTexturesOffline = false;
  2976. that.callbackManifestChecked(false);
  2977. }
  2978. var that = this;
  2979. var manifestURL = this.currentSceneUrl + ".manifest";
  2980. var xhr = new XMLHttpRequest();
  2981. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2982. xhr.open("GET", manifestURLTimeStamped, true);
  2983. xhr.addEventListener("load", function () {
  2984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2985. try {
  2986. var manifestFile = JSON.parse(xhr.response);
  2987. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2988. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2990. _this.manifestVersionFound = manifestFile.version;
  2991. }
  2992. if (_this.callbackManifestChecked) {
  2993. _this.callbackManifestChecked(true);
  2994. }
  2995. }
  2996. catch (ex) {
  2997. noManifestFile();
  2998. }
  2999. }
  3000. else {
  3001. noManifestFile();
  3002. }
  3003. }, false);
  3004. xhr.addEventListener("error", function (event) {
  3005. noManifestFile();
  3006. }, false);
  3007. try {
  3008. xhr.send();
  3009. }
  3010. catch (ex) {
  3011. BABYLON.Tools.Error("Error on XHR send request.");
  3012. that.callbackManifestChecked(false);
  3013. }
  3014. };
  3015. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3016. var _this = this;
  3017. function handleError() {
  3018. that.isSupported = false;
  3019. if (errorCallback)
  3020. errorCallback();
  3021. }
  3022. var that = this;
  3023. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3024. // Your browser doesn't support IndexedDB
  3025. this.isSupported = false;
  3026. if (errorCallback)
  3027. errorCallback();
  3028. }
  3029. else {
  3030. // If the DB hasn't been opened or created yet
  3031. if (!this.db) {
  3032. this.hasReachedQuota = false;
  3033. this.isSupported = true;
  3034. var request = this.idbFactory.open("babylonjs", 1);
  3035. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3036. request.onerror = function (event) {
  3037. handleError();
  3038. };
  3039. // executes when a version change transaction cannot complete due to other active transactions
  3040. request.onblocked = function (event) {
  3041. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3042. handleError();
  3043. };
  3044. // DB has been opened successfully
  3045. request.onsuccess = function (event) {
  3046. _this.db = request.result;
  3047. successCallback();
  3048. };
  3049. // Initialization of the DB. Creating Scenes & Textures stores
  3050. request.onupgradeneeded = function (event) {
  3051. _this.db = (event.target).result;
  3052. try {
  3053. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3054. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3055. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3056. }
  3057. catch (ex) {
  3058. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3059. handleError();
  3060. }
  3061. };
  3062. }
  3063. else {
  3064. if (successCallback)
  3065. successCallback();
  3066. }
  3067. }
  3068. };
  3069. Database.prototype.loadImageFromDB = function (url, image) {
  3070. var _this = this;
  3071. var completeURL = Database.ReturnFullUrlLocation(url);
  3072. var saveAndLoadImage = function () {
  3073. if (!_this.hasReachedQuota && _this.db !== null) {
  3074. // the texture is not yet in the DB, let's try to save it
  3075. _this._saveImageIntoDBAsync(completeURL, image);
  3076. }
  3077. else {
  3078. image.src = url;
  3079. }
  3080. };
  3081. if (!this.mustUpdateRessources) {
  3082. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3083. }
  3084. else {
  3085. saveAndLoadImage();
  3086. }
  3087. };
  3088. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3089. if (this.isSupported && this.db !== null) {
  3090. var texture;
  3091. var transaction = this.db.transaction(["textures"]);
  3092. transaction.onabort = function (event) {
  3093. image.src = url;
  3094. };
  3095. transaction.oncomplete = function (event) {
  3096. var blobTextureURL;
  3097. if (texture) {
  3098. var URL = window.URL || window.webkitURL;
  3099. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3100. image.onerror = function () {
  3101. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3102. image.src = url;
  3103. };
  3104. image.src = blobTextureURL;
  3105. }
  3106. else {
  3107. notInDBCallback();
  3108. }
  3109. };
  3110. var getRequest = transaction.objectStore("textures").get(url);
  3111. getRequest.onsuccess = function (event) {
  3112. texture = (event.target).result;
  3113. };
  3114. getRequest.onerror = function (event) {
  3115. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3116. image.src = url;
  3117. };
  3118. }
  3119. else {
  3120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3121. image.src = url;
  3122. }
  3123. };
  3124. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3125. var _this = this;
  3126. if (this.isSupported) {
  3127. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3128. var generateBlobUrl = function () {
  3129. var blobTextureURL;
  3130. if (blob) {
  3131. var URL = window.URL || window.webkitURL;
  3132. try {
  3133. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3134. }
  3135. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3136. catch (ex) {
  3137. blobTextureURL = URL.createObjectURL(blob);
  3138. }
  3139. }
  3140. image.src = blobTextureURL;
  3141. };
  3142. if (Database.IsUASupportingBlobStorage) {
  3143. var xhr = new XMLHttpRequest(), blob;
  3144. xhr.open("GET", url, true);
  3145. xhr.responseType = "blob";
  3146. xhr.addEventListener("load", function () {
  3147. if (xhr.status === 200) {
  3148. // Blob as response (XHR2)
  3149. blob = xhr.response;
  3150. var transaction = _this.db.transaction(["textures"], "readwrite");
  3151. // the transaction could abort because of a QuotaExceededError error
  3152. transaction.onabort = function (event) {
  3153. try {
  3154. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3155. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3156. this.hasReachedQuota = true;
  3157. }
  3158. }
  3159. catch (ex) { }
  3160. generateBlobUrl();
  3161. };
  3162. transaction.oncomplete = function (event) {
  3163. generateBlobUrl();
  3164. };
  3165. var newTexture = { textureUrl: url, data: blob };
  3166. try {
  3167. // Put the blob into the dabase
  3168. var addRequest = transaction.objectStore("textures").put(newTexture);
  3169. addRequest.onsuccess = function (event) {
  3170. };
  3171. addRequest.onerror = function (event) {
  3172. generateBlobUrl();
  3173. };
  3174. }
  3175. catch (ex) {
  3176. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3177. if (ex.code === 25) {
  3178. Database.IsUASupportingBlobStorage = false;
  3179. }
  3180. image.src = url;
  3181. }
  3182. }
  3183. else {
  3184. image.src = url;
  3185. }
  3186. }, false);
  3187. xhr.addEventListener("error", function (event) {
  3188. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3189. image.src = url;
  3190. }, false);
  3191. xhr.send();
  3192. }
  3193. else {
  3194. image.src = url;
  3195. }
  3196. }
  3197. else {
  3198. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3199. image.src = url;
  3200. }
  3201. };
  3202. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3203. var _this = this;
  3204. var updateVersion = function (event) {
  3205. // the version is not yet in the DB or we need to update it
  3206. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3207. };
  3208. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3209. };
  3210. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3211. var _this = this;
  3212. if (this.isSupported) {
  3213. var version;
  3214. try {
  3215. var transaction = this.db.transaction(["versions"]);
  3216. transaction.oncomplete = function (event) {
  3217. if (version) {
  3218. // If the version in the JSON file is > than the version in DB
  3219. if (_this.manifestVersionFound > version.data) {
  3220. _this.mustUpdateRessources = true;
  3221. updateInDBCallback();
  3222. }
  3223. else {
  3224. callback(version.data);
  3225. }
  3226. }
  3227. else {
  3228. _this.mustUpdateRessources = true;
  3229. updateInDBCallback();
  3230. }
  3231. };
  3232. transaction.onabort = function (event) {
  3233. callback(-1);
  3234. };
  3235. var getRequest = transaction.objectStore("versions").get(url);
  3236. getRequest.onsuccess = function (event) {
  3237. version = (event.target).result;
  3238. };
  3239. getRequest.onerror = function (event) {
  3240. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3241. callback(-1);
  3242. };
  3243. }
  3244. catch (ex) {
  3245. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3246. callback(-1);
  3247. }
  3248. }
  3249. else {
  3250. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3251. callback(-1);
  3252. }
  3253. };
  3254. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3255. var _this = this;
  3256. if (this.isSupported && !this.hasReachedQuota) {
  3257. try {
  3258. // Open a transaction to the database
  3259. var transaction = this.db.transaction(["versions"], "readwrite");
  3260. // the transaction could abort because of a QuotaExceededError error
  3261. transaction.onabort = function (event) {
  3262. try {
  3263. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3264. _this.hasReachedQuota = true;
  3265. }
  3266. }
  3267. catch (ex) { }
  3268. callback(-1);
  3269. };
  3270. transaction.oncomplete = function (event) {
  3271. callback(_this.manifestVersionFound);
  3272. };
  3273. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3274. // Put the scene into the database
  3275. var addRequest = transaction.objectStore("versions").put(newVersion);
  3276. addRequest.onsuccess = function (event) {
  3277. };
  3278. addRequest.onerror = function (event) {
  3279. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3280. };
  3281. }
  3282. catch (ex) {
  3283. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3284. callback(-1);
  3285. }
  3286. }
  3287. else {
  3288. callback(-1);
  3289. }
  3290. };
  3291. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3292. var _this = this;
  3293. var completeUrl = Database.ReturnFullUrlLocation(url);
  3294. var saveAndLoadFile = function (event) {
  3295. // the scene is not yet in the DB, let's try to save it
  3296. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3297. };
  3298. this._checkVersionFromDB(completeUrl, function (version) {
  3299. if (version !== -1) {
  3300. if (!_this.mustUpdateRessources) {
  3301. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3302. }
  3303. else {
  3304. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3305. }
  3306. }
  3307. else {
  3308. errorCallback();
  3309. }
  3310. });
  3311. };
  3312. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3313. if (this.isSupported) {
  3314. var targetStore;
  3315. if (url.indexOf(".babylon") !== -1) {
  3316. targetStore = "scenes";
  3317. }
  3318. else {
  3319. targetStore = "textures";
  3320. }
  3321. var file;
  3322. var transaction = this.db.transaction([targetStore]);
  3323. transaction.oncomplete = function (event) {
  3324. if (file) {
  3325. callback(file.data);
  3326. }
  3327. else {
  3328. notInDBCallback();
  3329. }
  3330. };
  3331. transaction.onabort = function (event) {
  3332. notInDBCallback();
  3333. };
  3334. var getRequest = transaction.objectStore(targetStore).get(url);
  3335. getRequest.onsuccess = function (event) {
  3336. file = (event.target).result;
  3337. };
  3338. getRequest.onerror = function (event) {
  3339. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3340. notInDBCallback();
  3341. };
  3342. }
  3343. else {
  3344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3345. callback();
  3346. }
  3347. };
  3348. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3349. var _this = this;
  3350. if (this.isSupported) {
  3351. var targetStore;
  3352. if (url.indexOf(".babylon") !== -1) {
  3353. targetStore = "scenes";
  3354. }
  3355. else {
  3356. targetStore = "textures";
  3357. }
  3358. // Create XHR
  3359. var xhr = new XMLHttpRequest(), fileData;
  3360. xhr.open("GET", url, true);
  3361. if (useArrayBuffer) {
  3362. xhr.responseType = "arraybuffer";
  3363. }
  3364. xhr.onprogress = progressCallback;
  3365. xhr.addEventListener("load", function () {
  3366. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3367. // Blob as response (XHR2)
  3368. //fileData = xhr.responseText;
  3369. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3370. if (!_this.hasReachedQuota) {
  3371. // Open a transaction to the database
  3372. var transaction = _this.db.transaction([targetStore], "readwrite");
  3373. // the transaction could abort because of a QuotaExceededError error
  3374. transaction.onabort = function (event) {
  3375. try {
  3376. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3377. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3378. this.hasReachedQuota = true;
  3379. }
  3380. }
  3381. catch (ex) { }
  3382. callback(fileData);
  3383. };
  3384. transaction.oncomplete = function (event) {
  3385. callback(fileData);
  3386. };
  3387. var newFile;
  3388. if (targetStore === "scenes") {
  3389. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3390. }
  3391. else {
  3392. newFile = { textureUrl: url, data: fileData };
  3393. }
  3394. try {
  3395. // Put the scene into the database
  3396. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3397. addRequest.onsuccess = function (event) {
  3398. };
  3399. addRequest.onerror = function (event) {
  3400. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3401. };
  3402. }
  3403. catch (ex) {
  3404. callback(fileData);
  3405. }
  3406. }
  3407. else {
  3408. callback(fileData);
  3409. }
  3410. }
  3411. else {
  3412. callback();
  3413. }
  3414. }, false);
  3415. xhr.addEventListener("error", function (event) {
  3416. BABYLON.Tools.Error("error on XHR request.");
  3417. callback();
  3418. }, false);
  3419. xhr.send();
  3420. }
  3421. else {
  3422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3423. callback();
  3424. }
  3425. };
  3426. Database.IsUASupportingBlobStorage = true;
  3427. Database.IDBStorageEnabled = true;
  3428. Database.parseURL = function (url) {
  3429. var a = document.createElement('a');
  3430. a.href = url;
  3431. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3432. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3433. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3434. return absLocation;
  3435. };
  3436. Database.ReturnFullUrlLocation = function (url) {
  3437. if (url.indexOf("http:/") === -1) {
  3438. return (Database.parseURL(window.location.href) + url);
  3439. }
  3440. else {
  3441. return url;
  3442. }
  3443. };
  3444. return Database;
  3445. })();
  3446. BABYLON.Database = Database;
  3447. })(BABYLON || (BABYLON = {}));
  3448. var BABYLON;
  3449. (function (BABYLON) {
  3450. var Internals;
  3451. (function (Internals) {
  3452. /*
  3453. * Based on jsTGALoader - Javascript loader for TGA file
  3454. * By Vincent Thibault
  3455. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3456. */
  3457. var TGATools = (function () {
  3458. function TGATools() {
  3459. }
  3460. TGATools.GetTGAHeader = function (data) {
  3461. var offset = 0;
  3462. var header = {
  3463. id_length: data[offset++],
  3464. colormap_type: data[offset++],
  3465. image_type: data[offset++],
  3466. colormap_index: data[offset++] | data[offset++] << 8,
  3467. colormap_length: data[offset++] | data[offset++] << 8,
  3468. colormap_size: data[offset++],
  3469. origin: [
  3470. data[offset++] | data[offset++] << 8,
  3471. data[offset++] | data[offset++] << 8
  3472. ],
  3473. width: data[offset++] | data[offset++] << 8,
  3474. height: data[offset++] | data[offset++] << 8,
  3475. pixel_size: data[offset++],
  3476. flags: data[offset++]
  3477. };
  3478. return header;
  3479. };
  3480. TGATools.UploadContent = function (gl, data) {
  3481. // Not enough data to contain header ?
  3482. if (data.length < 19) {
  3483. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3484. return;
  3485. }
  3486. // Read Header
  3487. var offset = 18;
  3488. var header = TGATools.GetTGAHeader(data);
  3489. // Assume it's a valid Targa file.
  3490. if (header.id_length + offset > data.length) {
  3491. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3492. return;
  3493. }
  3494. // Skip not needed data
  3495. offset += header.id_length;
  3496. var use_rle = false;
  3497. var use_pal = false;
  3498. var use_rgb = false;
  3499. var use_grey = false;
  3500. // Get some informations.
  3501. switch (header.image_type) {
  3502. case TGATools._TYPE_RLE_INDEXED:
  3503. use_rle = true;
  3504. case TGATools._TYPE_INDEXED:
  3505. use_pal = true;
  3506. break;
  3507. case TGATools._TYPE_RLE_RGB:
  3508. use_rle = true;
  3509. case TGATools._TYPE_RGB:
  3510. use_rgb = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_GREY:
  3513. use_rle = true;
  3514. case TGATools._TYPE_GREY:
  3515. use_grey = true;
  3516. break;
  3517. }
  3518. var pixel_data;
  3519. var numAlphaBits = header.flags & 0xf;
  3520. var pixel_size = header.pixel_size >> 3;
  3521. var pixel_total = header.width * header.height * pixel_size;
  3522. // Read palettes
  3523. var palettes;
  3524. if (use_pal) {
  3525. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3526. }
  3527. // Read LRE
  3528. if (use_rle) {
  3529. pixel_data = new Uint8Array(pixel_total);
  3530. var c, count, i;
  3531. var localOffset = 0;
  3532. var pixels = new Uint8Array(pixel_size);
  3533. while (offset < pixel_total && localOffset < pixel_total) {
  3534. c = data[offset++];
  3535. count = (c & 0x7f) + 1;
  3536. // RLE pixels
  3537. if (c & 0x80) {
  3538. // Bind pixel tmp array
  3539. for (i = 0; i < pixel_size; ++i) {
  3540. pixels[i] = data[offset++];
  3541. }
  3542. // Copy pixel array
  3543. for (i = 0; i < count; ++i) {
  3544. pixel_data.set(pixels, localOffset + i * pixel_size);
  3545. }
  3546. localOffset += pixel_size * count;
  3547. }
  3548. else {
  3549. count *= pixel_size;
  3550. for (i = 0; i < count; ++i) {
  3551. pixel_data[localOffset + i] = data[offset++];
  3552. }
  3553. localOffset += count;
  3554. }
  3555. }
  3556. }
  3557. else {
  3558. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3559. }
  3560. // Load to texture
  3561. var x_start, y_start, x_step, y_step, y_end, x_end;
  3562. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3563. default:
  3564. case TGATools._ORIGIN_UL:
  3565. x_start = 0;
  3566. x_step = 1;
  3567. x_end = header.width;
  3568. y_start = 0;
  3569. y_step = 1;
  3570. y_end = header.height;
  3571. break;
  3572. case TGATools._ORIGIN_BL:
  3573. x_start = 0;
  3574. x_step = 1;
  3575. x_end = header.width;
  3576. y_start = header.height - 1;
  3577. y_step = -1;
  3578. y_end = -1;
  3579. break;
  3580. case TGATools._ORIGIN_UR:
  3581. x_start = header.width - 1;
  3582. x_step = -1;
  3583. x_end = -1;
  3584. y_start = 0;
  3585. y_step = 1;
  3586. y_end = header.height;
  3587. break;
  3588. case TGATools._ORIGIN_BR:
  3589. x_start = header.width - 1;
  3590. x_step = -1;
  3591. x_end = -1;
  3592. y_start = header.height - 1;
  3593. y_step = -1;
  3594. y_end = -1;
  3595. break;
  3596. }
  3597. // Load the specify method
  3598. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3599. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3600. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3601. };
  3602. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3603. var image = pixel_data, colormap = palettes;
  3604. var width = header.width, height = header.height;
  3605. var color, i = 0, x, y;
  3606. var imageData = new Uint8Array(width * height * 4);
  3607. for (y = y_start; y !== y_end; y += y_step) {
  3608. for (x = x_start; x !== x_end; x += x_step, i++) {
  3609. color = image[i];
  3610. imageData[(x + width * y) * 4 + 3] = 255;
  3611. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3612. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3613. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3614. }
  3615. }
  3616. return imageData;
  3617. };
  3618. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3619. var image = pixel_data;
  3620. var width = header.width, height = header.height;
  3621. var color, i = 0, x, y;
  3622. var imageData = new Uint8Array(width * height * 4);
  3623. for (y = y_start; y !== y_end; y += y_step) {
  3624. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3625. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3626. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3627. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3628. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3629. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3630. }
  3631. }
  3632. return imageData;
  3633. };
  3634. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3635. var image = pixel_data;
  3636. var width = header.width, height = header.height;
  3637. var i = 0, x, y;
  3638. var imageData = new Uint8Array(width * height * 4);
  3639. for (y = y_start; y !== y_end; y += y_step) {
  3640. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3641. imageData[(x + width * y) * 4 + 3] = 255;
  3642. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3643. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3644. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3645. }
  3646. }
  3647. return imageData;
  3648. };
  3649. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3650. var image = pixel_data;
  3651. var width = header.width, height = header.height;
  3652. var i = 0, x, y;
  3653. var imageData = new Uint8Array(width * height * 4);
  3654. for (y = y_start; y !== y_end; y += y_step) {
  3655. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3657. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3658. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3659. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3660. }
  3661. }
  3662. return imageData;
  3663. };
  3664. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3665. var image = pixel_data;
  3666. var width = header.width, height = header.height;
  3667. var color, i = 0, x, y;
  3668. var imageData = new Uint8Array(width * height * 4);
  3669. for (y = y_start; y !== y_end; y += y_step) {
  3670. for (x = x_start; x !== x_end; x += x_step, i++) {
  3671. color = image[i];
  3672. imageData[(x + width * y) * 4 + 0] = color;
  3673. imageData[(x + width * y) * 4 + 1] = color;
  3674. imageData[(x + width * y) * 4 + 2] = color;
  3675. imageData[(x + width * y) * 4 + 3] = 255;
  3676. }
  3677. }
  3678. return imageData;
  3679. };
  3680. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3681. var image = pixel_data;
  3682. var width = header.width, height = header.height;
  3683. var i = 0, x, y;
  3684. var imageData = new Uint8Array(width * height * 4);
  3685. for (y = y_start; y !== y_end; y += y_step) {
  3686. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3687. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3688. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3689. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3690. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._TYPE_NO_DATA = 0;
  3696. TGATools._TYPE_INDEXED = 1;
  3697. TGATools._TYPE_RGB = 2;
  3698. TGATools._TYPE_GREY = 3;
  3699. TGATools._TYPE_RLE_INDEXED = 9;
  3700. TGATools._TYPE_RLE_RGB = 10;
  3701. TGATools._TYPE_RLE_GREY = 11;
  3702. TGATools._ORIGIN_MASK = 0x30;
  3703. TGATools._ORIGIN_SHIFT = 0x04;
  3704. TGATools._ORIGIN_BL = 0x00;
  3705. TGATools._ORIGIN_BR = 0x01;
  3706. TGATools._ORIGIN_UL = 0x02;
  3707. TGATools._ORIGIN_UR = 0x03;
  3708. return TGATools;
  3709. })();
  3710. Internals.TGATools = TGATools;
  3711. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3712. })(BABYLON || (BABYLON = {}));
  3713. var BABYLON;
  3714. (function (BABYLON) {
  3715. var SmartArray = (function () {
  3716. function SmartArray(capacity) {
  3717. this.length = 0;
  3718. this._duplicateId = 0;
  3719. this.data = new Array(capacity);
  3720. this._id = SmartArray._GlobalId++;
  3721. }
  3722. SmartArray.prototype.push = function (value) {
  3723. this.data[this.length++] = value;
  3724. if (this.length > this.data.length) {
  3725. this.data.length *= 2;
  3726. }
  3727. if (!value.__smartArrayFlags) {
  3728. value.__smartArrayFlags = {};
  3729. }
  3730. value.__smartArrayFlags[this._id] = this._duplicateId;
  3731. };
  3732. SmartArray.prototype.pushNoDuplicate = function (value) {
  3733. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3734. return;
  3735. }
  3736. this.push(value);
  3737. };
  3738. SmartArray.prototype.sort = function (compareFn) {
  3739. this.data.sort(compareFn);
  3740. };
  3741. SmartArray.prototype.reset = function () {
  3742. this.length = 0;
  3743. this._duplicateId++;
  3744. };
  3745. SmartArray.prototype.concat = function (array) {
  3746. if (array.length === 0) {
  3747. return;
  3748. }
  3749. if (this.length + array.length > this.data.length) {
  3750. this.data.length = (this.length + array.length) * 2;
  3751. }
  3752. for (var index = 0; index < array.length; index++) {
  3753. this.data[this.length++] = (array.data || array)[index];
  3754. }
  3755. };
  3756. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3757. if (array.length === 0) {
  3758. return;
  3759. }
  3760. if (this.length + array.length > this.data.length) {
  3761. this.data.length = (this.length + array.length) * 2;
  3762. }
  3763. for (var index = 0; index < array.length; index++) {
  3764. var item = (array.data || array)[index];
  3765. this.pushNoDuplicate(item);
  3766. }
  3767. };
  3768. SmartArray.prototype.indexOf = function (value) {
  3769. var position = this.data.indexOf(value);
  3770. if (position >= this.length) {
  3771. return -1;
  3772. }
  3773. return position;
  3774. };
  3775. // Statics
  3776. SmartArray._GlobalId = 0;
  3777. return SmartArray;
  3778. })();
  3779. BABYLON.SmartArray = SmartArray;
  3780. })(BABYLON || (BABYLON = {}));
  3781. var BABYLON;
  3782. (function (BABYLON) {
  3783. var SmartCollection = (function () {
  3784. function SmartCollection(capacity) {
  3785. if (capacity === void 0) { capacity = 10; }
  3786. this.count = 0;
  3787. this._initialCapacity = capacity;
  3788. this.items = {};
  3789. this._keys = new Array(this._initialCapacity);
  3790. }
  3791. SmartCollection.prototype.add = function (key, item) {
  3792. if (this.items[key] != undefined) {
  3793. return -1;
  3794. }
  3795. this.items[key] = item;
  3796. //literal keys are always strings, but we keep source type of key in _keys array
  3797. this._keys[this.count++] = key;
  3798. if (this.count > this._keys.length) {
  3799. this._keys.length *= 2;
  3800. }
  3801. return this.count;
  3802. };
  3803. SmartCollection.prototype.remove = function (key) {
  3804. if (this.items[key] == undefined) {
  3805. return -1;
  3806. }
  3807. return this.removeItemOfIndex(this.indexOf(key));
  3808. };
  3809. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3810. if (index < this.count && index > -1) {
  3811. delete this.items[this._keys[index]];
  3812. //here, shifting by hand is better optimised than .splice
  3813. while (index < this.count) {
  3814. this._keys[index] = this._keys[index + 1];
  3815. index++;
  3816. }
  3817. }
  3818. else {
  3819. return -1;
  3820. }
  3821. return --this.count;
  3822. };
  3823. SmartCollection.prototype.indexOf = function (key) {
  3824. for (var i = 0; i !== this.count; i++) {
  3825. if (this._keys[i] === key) {
  3826. return i;
  3827. }
  3828. }
  3829. return -1;
  3830. };
  3831. SmartCollection.prototype.item = function (key) {
  3832. return this.items[key];
  3833. };
  3834. SmartCollection.prototype.getAllKeys = function () {
  3835. if (this.count > 0) {
  3836. var keys = new Array(this.count);
  3837. for (var i = 0; i < this.count; i++) {
  3838. keys[i] = this._keys[i];
  3839. }
  3840. return keys;
  3841. }
  3842. else {
  3843. return undefined;
  3844. }
  3845. };
  3846. SmartCollection.prototype.getKeyByIndex = function (index) {
  3847. if (index < this.count && index > -1) {
  3848. return this._keys[index];
  3849. }
  3850. else {
  3851. return undefined;
  3852. }
  3853. };
  3854. SmartCollection.prototype.getItemByIndex = function (index) {
  3855. if (index < this.count && index > -1) {
  3856. return this.items[this._keys[index]];
  3857. }
  3858. else {
  3859. return undefined;
  3860. }
  3861. };
  3862. SmartCollection.prototype.empty = function () {
  3863. if (this.count > 0) {
  3864. this.count = 0;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. };
  3869. SmartCollection.prototype.forEach = function (block) {
  3870. var key;
  3871. for (key in this.items) {
  3872. if (this.items.hasOwnProperty(key)) {
  3873. block(this.items[key]);
  3874. }
  3875. }
  3876. };
  3877. return SmartCollection;
  3878. })();
  3879. BABYLON.SmartCollection = SmartCollection;
  3880. })(BABYLON || (BABYLON = {}));
  3881. var BABYLON;
  3882. (function (BABYLON) {
  3883. // Screenshots
  3884. var screenshotCanvas;
  3885. var cloneValue = function (source, destinationObject) {
  3886. if (!source)
  3887. return null;
  3888. if (source instanceof BABYLON.Mesh) {
  3889. return null;
  3890. }
  3891. if (source instanceof BABYLON.SubMesh) {
  3892. return source.clone(destinationObject);
  3893. }
  3894. else if (source.clone) {
  3895. return source.clone();
  3896. }
  3897. return null;
  3898. };
  3899. var Tools = (function () {
  3900. function Tools() {
  3901. }
  3902. Tools.Instantiate = function (className) {
  3903. var arr = className.split(".");
  3904. var fn = (window || this);
  3905. for (var i = 0, len = arr.length; i < len; i++) {
  3906. fn = fn[arr[i]];
  3907. }
  3908. if (typeof fn !== "function") {
  3909. return null;
  3910. }
  3911. return fn;
  3912. };
  3913. Tools.GetConstructorName = function (obj) {
  3914. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3915. var cname = str.match(/function\s(\w*)/)[1];
  3916. var aliases = ["", "anonymous", "Anonymous"];
  3917. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3918. };
  3919. Tools.ToHex = function (i) {
  3920. var str = i.toString(16);
  3921. if (i <= 15) {
  3922. return ("0" + str).toUpperCase();
  3923. }
  3924. return str.toUpperCase();
  3925. };
  3926. Tools.SetImmediate = function (action) {
  3927. if (window.setImmediate) {
  3928. window.setImmediate(action);
  3929. }
  3930. else {
  3931. setTimeout(action, 1);
  3932. }
  3933. };
  3934. Tools.IsExponentOfTwo = function (value) {
  3935. var count = 1;
  3936. do {
  3937. count *= 2;
  3938. } while (count < value);
  3939. return count === value;
  3940. };
  3941. Tools.GetExponentOfTwo = function (value, max) {
  3942. var count = 1;
  3943. do {
  3944. count *= 2;
  3945. } while (count < value);
  3946. if (count > max)
  3947. count = max;
  3948. return count;
  3949. };
  3950. Tools.GetFilename = function (path) {
  3951. var index = path.lastIndexOf("/");
  3952. if (index < 0)
  3953. return path;
  3954. return path.substring(index + 1);
  3955. };
  3956. Tools.GetDOMTextContent = function (element) {
  3957. var result = "";
  3958. var child = element.firstChild;
  3959. while (child) {
  3960. if (child.nodeType === 3) {
  3961. result += child.textContent;
  3962. }
  3963. child = child.nextSibling;
  3964. }
  3965. return result;
  3966. };
  3967. Tools.ToDegrees = function (angle) {
  3968. return angle * 180 / Math.PI;
  3969. };
  3970. Tools.ToRadians = function (angle) {
  3971. return angle * Math.PI / 180;
  3972. };
  3973. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3974. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3975. var output = "";
  3976. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3977. var i = 0;
  3978. var bytes = new Uint8Array(buffer);
  3979. while (i < bytes.length) {
  3980. chr1 = bytes[i++];
  3981. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3982. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3983. enc1 = chr1 >> 2;
  3984. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3985. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3986. enc4 = chr3 & 63;
  3987. if (isNaN(chr2)) {
  3988. enc3 = enc4 = 64;
  3989. }
  3990. else if (isNaN(chr3)) {
  3991. enc4 = 64;
  3992. }
  3993. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3994. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3995. }
  3996. return "data:image/png;base64," + output;
  3997. };
  3998. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3999. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4000. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4001. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4002. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4003. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4004. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4005. }
  4006. return {
  4007. minimum: minimum,
  4008. maximum: maximum
  4009. };
  4010. };
  4011. Tools.ExtractMinAndMax = function (positions, start, count) {
  4012. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4013. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4014. for (var index = start; index < start + count; index++) {
  4015. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4016. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4017. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4018. }
  4019. return {
  4020. minimum: minimum,
  4021. maximum: maximum
  4022. };
  4023. };
  4024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4026. return undefined;
  4027. return Array.isArray(obj) ? obj : [obj];
  4028. };
  4029. // Misc.
  4030. Tools.GetPointerPrefix = function () {
  4031. var eventPrefix = "pointer";
  4032. // Check if pointer events are supported
  4033. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4034. eventPrefix = "mouse";
  4035. }
  4036. return eventPrefix;
  4037. };
  4038. Tools.QueueNewFrame = function (func) {
  4039. if (window.requestAnimationFrame)
  4040. window.requestAnimationFrame(func);
  4041. else if (window.msRequestAnimationFrame)
  4042. window.msRequestAnimationFrame(func);
  4043. else if (window.webkitRequestAnimationFrame)
  4044. window.webkitRequestAnimationFrame(func);
  4045. else if (window.mozRequestAnimationFrame)
  4046. window.mozRequestAnimationFrame(func);
  4047. else if (window.oRequestAnimationFrame)
  4048. window.oRequestAnimationFrame(func);
  4049. else {
  4050. window.setTimeout(func, 16);
  4051. }
  4052. };
  4053. Tools.RequestFullscreen = function (element) {
  4054. if (element.requestFullscreen)
  4055. element.requestFullscreen();
  4056. else if (element.msRequestFullscreen)
  4057. element.msRequestFullscreen();
  4058. else if (element.webkitRequestFullscreen)
  4059. element.webkitRequestFullscreen();
  4060. else if (element.mozRequestFullScreen)
  4061. element.mozRequestFullScreen();
  4062. };
  4063. Tools.ExitFullscreen = function () {
  4064. if (document.exitFullscreen) {
  4065. document.exitFullscreen();
  4066. }
  4067. else if (document.mozCancelFullScreen) {
  4068. document.mozCancelFullScreen();
  4069. }
  4070. else if (document.webkitCancelFullScreen) {
  4071. document.webkitCancelFullScreen();
  4072. }
  4073. else if (document.msCancelFullScreen) {
  4074. document.msCancelFullScreen();
  4075. }
  4076. };
  4077. // External files
  4078. Tools.CleanUrl = function (url) {
  4079. url = url.replace(/#/mg, "%23");
  4080. return url;
  4081. };
  4082. Tools.LoadImage = function (url, onload, onerror, database) {
  4083. if (url instanceof ArrayBuffer) {
  4084. url = Tools.EncodeArrayBufferTobase64(url);
  4085. }
  4086. url = Tools.CleanUrl(url);
  4087. var img = new Image();
  4088. if (url.substr(0, 5) !== "data:") {
  4089. if (Tools.CorsBehavior) {
  4090. switch (typeof (Tools.CorsBehavior)) {
  4091. case "function":
  4092. var result = Tools.CorsBehavior(url);
  4093. if (result) {
  4094. img.crossOrigin = result;
  4095. }
  4096. break;
  4097. case "string":
  4098. default:
  4099. img.crossOrigin = Tools.CorsBehavior;
  4100. break;
  4101. }
  4102. }
  4103. }
  4104. img.onload = function () {
  4105. onload(img);
  4106. };
  4107. img.onerror = function (err) {
  4108. Tools.Error("Error while trying to load texture: " + url);
  4109. 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";
  4110. onload(img);
  4111. };
  4112. var noIndexedDB = function () {
  4113. img.src = url;
  4114. };
  4115. var loadFromIndexedDB = function () {
  4116. database.loadImageFromDB(url, img);
  4117. };
  4118. //ANY database to do!
  4119. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4120. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4121. }
  4122. else {
  4123. if (url.indexOf("file:") === -1) {
  4124. noIndexedDB();
  4125. }
  4126. else {
  4127. try {
  4128. var textureName = url.substring(5);
  4129. var blobURL;
  4130. try {
  4131. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4132. }
  4133. catch (ex) {
  4134. // Chrome doesn't support oneTimeOnly parameter
  4135. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4136. }
  4137. img.src = blobURL;
  4138. }
  4139. catch (e) {
  4140. img.src = null;
  4141. }
  4142. }
  4143. }
  4144. return img;
  4145. };
  4146. //ANY
  4147. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4148. url = Tools.CleanUrl(url);
  4149. var noIndexedDB = function () {
  4150. var request = new XMLHttpRequest();
  4151. var loadUrl = Tools.BaseUrl + url;
  4152. request.open('GET', loadUrl, true);
  4153. if (useArrayBuffer) {
  4154. request.responseType = "arraybuffer";
  4155. }
  4156. request.onprogress = progressCallBack;
  4157. request.onreadystatechange = function () {
  4158. if (request.readyState === 4) {
  4159. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4160. callback(!useArrayBuffer ? request.responseText : request.response);
  4161. }
  4162. else {
  4163. if (onError) {
  4164. onError();
  4165. }
  4166. else {
  4167. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4168. }
  4169. }
  4170. }
  4171. };
  4172. request.send(null);
  4173. };
  4174. var loadFromIndexedDB = function () {
  4175. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4176. };
  4177. if (url.indexOf("file:") !== -1) {
  4178. var fileName = url.substring(5);
  4179. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4180. }
  4181. else {
  4182. // Caching all files
  4183. if (database && database.enableSceneOffline) {
  4184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4185. }
  4186. else {
  4187. noIndexedDB();
  4188. }
  4189. }
  4190. };
  4191. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4192. var reader = new FileReader();
  4193. reader.onload = function (e) {
  4194. //target doesn't have result from ts 1.3
  4195. callback(e.target['result']);
  4196. };
  4197. reader.onprogress = progressCallback;
  4198. reader.readAsDataURL(fileToLoad);
  4199. };
  4200. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4201. var reader = new FileReader();
  4202. reader.onerror = function (e) {
  4203. Tools.Log("Error while reading file: " + fileToLoad.name);
  4204. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4205. };
  4206. reader.onload = function (e) {
  4207. //target doesn't have result from ts 1.3
  4208. callback(e.target['result']);
  4209. };
  4210. reader.onprogress = progressCallBack;
  4211. if (!useArrayBuffer) {
  4212. // Asynchronous read
  4213. reader.readAsText(fileToLoad);
  4214. }
  4215. else {
  4216. reader.readAsArrayBuffer(fileToLoad);
  4217. }
  4218. };
  4219. //returns a downloadable url to a file content.
  4220. Tools.FileAsURL = function (content) {
  4221. var fileBlob = new Blob([content]);
  4222. var url = window.URL || window.webkitURL;
  4223. var link = url.createObjectURL(fileBlob);
  4224. return link;
  4225. };
  4226. // Misc.
  4227. Tools.Clamp = function (value, min, max) {
  4228. if (min === void 0) { min = 0; }
  4229. if (max === void 0) { max = 1; }
  4230. return Math.min(max, Math.max(min, value));
  4231. };
  4232. // Returns -1 when value is a negative number and
  4233. // +1 when value is a positive number.
  4234. Tools.Sign = function (value) {
  4235. value = +value; // convert to a number
  4236. if (value === 0 || isNaN(value))
  4237. return value;
  4238. return value > 0 ? 1 : -1;
  4239. };
  4240. Tools.Format = function (value, decimals) {
  4241. if (decimals === void 0) { decimals = 2; }
  4242. return value.toFixed(decimals);
  4243. };
  4244. Tools.CheckExtends = function (v, min, max) {
  4245. if (v.x < min.x)
  4246. min.x = v.x;
  4247. if (v.y < min.y)
  4248. min.y = v.y;
  4249. if (v.z < min.z)
  4250. min.z = v.z;
  4251. if (v.x > max.x)
  4252. max.x = v.x;
  4253. if (v.y > max.y)
  4254. max.y = v.y;
  4255. if (v.z > max.z)
  4256. max.z = v.z;
  4257. };
  4258. Tools.WithinEpsilon = function (a, b, epsilon) {
  4259. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4260. var num = a - b;
  4261. return -epsilon <= num && num <= epsilon;
  4262. };
  4263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4264. for (var prop in source) {
  4265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4266. continue;
  4267. }
  4268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4269. continue;
  4270. }
  4271. var sourceValue = source[prop];
  4272. var typeOfSourceValue = typeof sourceValue;
  4273. if (typeOfSourceValue === "function") {
  4274. continue;
  4275. }
  4276. if (typeOfSourceValue === "object") {
  4277. if (sourceValue instanceof Array) {
  4278. destination[prop] = [];
  4279. if (sourceValue.length > 0) {
  4280. if (typeof sourceValue[0] == "object") {
  4281. for (var index = 0; index < sourceValue.length; index++) {
  4282. var clonedValue = cloneValue(sourceValue[index], destination);
  4283. if (destination[prop].indexOf(clonedValue) === -1) {
  4284. destination[prop].push(clonedValue);
  4285. }
  4286. }
  4287. }
  4288. else {
  4289. destination[prop] = sourceValue.slice(0);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = cloneValue(sourceValue, destination);
  4295. }
  4296. }
  4297. else {
  4298. destination[prop] = sourceValue;
  4299. }
  4300. }
  4301. };
  4302. Tools.IsEmpty = function (obj) {
  4303. for (var i in obj) {
  4304. return false;
  4305. }
  4306. return true;
  4307. };
  4308. Tools.RegisterTopRootEvents = function (events) {
  4309. for (var index = 0; index < events.length; index++) {
  4310. var event = events[index];
  4311. window.addEventListener(event.name, event.handler, false);
  4312. try {
  4313. if (window.parent) {
  4314. window.parent.addEventListener(event.name, event.handler, false);
  4315. }
  4316. }
  4317. catch (e) {
  4318. }
  4319. }
  4320. };
  4321. Tools.UnregisterTopRootEvents = function (events) {
  4322. for (var index = 0; index < events.length; index++) {
  4323. var event = events[index];
  4324. window.removeEventListener(event.name, event.handler);
  4325. try {
  4326. if (window.parent) {
  4327. window.parent.removeEventListener(event.name, event.handler);
  4328. }
  4329. }
  4330. catch (e) {
  4331. }
  4332. }
  4333. };
  4334. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4335. // Read the contents of the framebuffer
  4336. var numberOfChannelsByLine = width * 4;
  4337. var halfHeight = height / 2;
  4338. //Reading datas from WebGL
  4339. var data = engine.readPixels(0, 0, width, height);
  4340. //To flip image on Y axis.
  4341. for (var i = 0; i < halfHeight; i++) {
  4342. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4343. var currentCell = j + i * numberOfChannelsByLine;
  4344. var targetLine = height - i - 1;
  4345. var targetCell = j + targetLine * numberOfChannelsByLine;
  4346. var temp = data[currentCell];
  4347. data[currentCell] = data[targetCell];
  4348. data[targetCell] = temp;
  4349. }
  4350. }
  4351. // Create a 2D canvas to store the result
  4352. if (!screenshotCanvas) {
  4353. screenshotCanvas = document.createElement('canvas');
  4354. }
  4355. screenshotCanvas.width = width;
  4356. screenshotCanvas.height = height;
  4357. var context = screenshotCanvas.getContext('2d');
  4358. // Copy the pixels to a 2D canvas
  4359. var imageData = context.createImageData(width, height);
  4360. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4361. var castData = imageData.data;
  4362. castData.set(data);
  4363. context.putImageData(imageData, 0, 0);
  4364. var base64Image = screenshotCanvas.toDataURL();
  4365. if (successCallback) {
  4366. successCallback(base64Image);
  4367. }
  4368. else {
  4369. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4370. if (("download" in document.createElement("a"))) {
  4371. var a = window.document.createElement("a");
  4372. a.href = base64Image;
  4373. var date = new Date();
  4374. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4375. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4376. window.document.body.appendChild(a);
  4377. a.addEventListener("click", function () {
  4378. a.parentElement.removeChild(a);
  4379. });
  4380. a.click();
  4381. }
  4382. else {
  4383. var newWindow = window.open("");
  4384. var img = newWindow.document.createElement("img");
  4385. img.src = base64Image;
  4386. newWindow.document.body.appendChild(img);
  4387. }
  4388. }
  4389. };
  4390. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4391. var width;
  4392. var height;
  4393. //If a precision value is specified
  4394. if (size.precision) {
  4395. width = Math.round(engine.getRenderWidth() * size.precision);
  4396. height = Math.round(width / engine.getAspectRatio(camera));
  4397. size = { width: width, height: height };
  4398. }
  4399. else if (size.width && size.height) {
  4400. width = size.width;
  4401. height = size.height;
  4402. }
  4403. else if (size.width && !size.height) {
  4404. width = size.width;
  4405. height = Math.round(width / engine.getAspectRatio(camera));
  4406. size = { width: width, height: height };
  4407. }
  4408. else if (size.height && !size.width) {
  4409. height = size.height;
  4410. width = Math.round(height * engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (!isNaN(size)) {
  4414. height = size;
  4415. width = size;
  4416. }
  4417. else {
  4418. Tools.Error("Invalid 'size' parameter !");
  4419. return;
  4420. }
  4421. var scene = camera.getScene();
  4422. var previousCamera = null;
  4423. if (scene.activeCamera !== camera) {
  4424. previousCamera = scene.activeCamera;
  4425. scene.activeCamera = camera;
  4426. }
  4427. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4428. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4429. texture.renderList = scene.meshes;
  4430. texture.onAfterRender = function () {
  4431. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4432. };
  4433. scene.incrementRenderId();
  4434. texture.render(true);
  4435. texture.dispose();
  4436. if (previousCamera) {
  4437. scene.activeCamera = previousCamera;
  4438. }
  4439. };
  4440. // XHR response validator for local file scenario
  4441. Tools.ValidateXHRData = function (xhr, dataType) {
  4442. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4443. if (dataType === void 0) { dataType = 7; }
  4444. try {
  4445. if (dataType & 1) {
  4446. if (xhr.responseText && xhr.responseText.length > 0) {
  4447. return true;
  4448. }
  4449. else if (dataType === 1) {
  4450. return false;
  4451. }
  4452. }
  4453. if (dataType & 2) {
  4454. // Check header width and height since there is no "TGA" magic number
  4455. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4456. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4457. return true;
  4458. }
  4459. else if (dataType === 2) {
  4460. return false;
  4461. }
  4462. }
  4463. if (dataType & 4) {
  4464. // Check for the "DDS" magic number
  4465. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4466. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4467. return true;
  4468. }
  4469. else {
  4470. return false;
  4471. }
  4472. }
  4473. }
  4474. catch (e) {
  4475. }
  4476. return false;
  4477. };
  4478. Object.defineProperty(Tools, "NoneLogLevel", {
  4479. get: function () {
  4480. return Tools._NoneLogLevel;
  4481. },
  4482. enumerable: true,
  4483. configurable: true
  4484. });
  4485. Object.defineProperty(Tools, "MessageLogLevel", {
  4486. get: function () {
  4487. return Tools._MessageLogLevel;
  4488. },
  4489. enumerable: true,
  4490. configurable: true
  4491. });
  4492. Object.defineProperty(Tools, "WarningLogLevel", {
  4493. get: function () {
  4494. return Tools._WarningLogLevel;
  4495. },
  4496. enumerable: true,
  4497. configurable: true
  4498. });
  4499. Object.defineProperty(Tools, "ErrorLogLevel", {
  4500. get: function () {
  4501. return Tools._ErrorLogLevel;
  4502. },
  4503. enumerable: true,
  4504. configurable: true
  4505. });
  4506. Object.defineProperty(Tools, "AllLogLevel", {
  4507. get: function () {
  4508. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. Tools._AddLogEntry = function (entry) {
  4514. Tools._LogCache = entry + Tools._LogCache;
  4515. if (Tools.OnNewCacheEntry) {
  4516. Tools.OnNewCacheEntry(entry);
  4517. }
  4518. };
  4519. Tools._FormatMessage = function (message) {
  4520. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4521. var date = new Date();
  4522. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4523. };
  4524. Tools._LogDisabled = function (message) {
  4525. // nothing to do
  4526. };
  4527. Tools._LogEnabled = function (message) {
  4528. var formattedMessage = Tools._FormatMessage(message);
  4529. console.log("BJS - " + formattedMessage);
  4530. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4531. Tools._AddLogEntry(entry);
  4532. };
  4533. Tools._WarnDisabled = function (message) {
  4534. // nothing to do
  4535. };
  4536. Tools._WarnEnabled = function (message) {
  4537. var formattedMessage = Tools._FormatMessage(message);
  4538. console.warn("BJS - " + formattedMessage);
  4539. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4540. Tools._AddLogEntry(entry);
  4541. };
  4542. Tools._ErrorDisabled = function (message) {
  4543. // nothing to do
  4544. };
  4545. Tools._ErrorEnabled = function (message) {
  4546. Tools.errorsCount++;
  4547. var formattedMessage = Tools._FormatMessage(message);
  4548. console.error("BJS - " + formattedMessage);
  4549. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4550. Tools._AddLogEntry(entry);
  4551. };
  4552. Object.defineProperty(Tools, "LogCache", {
  4553. get: function () {
  4554. return Tools._LogCache;
  4555. },
  4556. enumerable: true,
  4557. configurable: true
  4558. });
  4559. Tools.ClearLogCache = function () {
  4560. Tools._LogCache = "";
  4561. Tools.errorsCount = 0;
  4562. };
  4563. Object.defineProperty(Tools, "LogLevels", {
  4564. set: function (level) {
  4565. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4566. Tools.Log = Tools._LogEnabled;
  4567. }
  4568. else {
  4569. Tools.Log = Tools._LogDisabled;
  4570. }
  4571. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4572. Tools.Warn = Tools._WarnEnabled;
  4573. }
  4574. else {
  4575. Tools.Warn = Tools._WarnDisabled;
  4576. }
  4577. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4578. Tools.Error = Tools._ErrorEnabled;
  4579. }
  4580. else {
  4581. Tools.Error = Tools._ErrorDisabled;
  4582. }
  4583. },
  4584. enumerable: true,
  4585. configurable: true
  4586. });
  4587. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4588. get: function () {
  4589. return Tools._PerformanceNoneLogLevel;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4595. get: function () {
  4596. return Tools._PerformanceUserMarkLogLevel;
  4597. },
  4598. enumerable: true,
  4599. configurable: true
  4600. });
  4601. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4602. get: function () {
  4603. return Tools._PerformanceConsoleLogLevel;
  4604. },
  4605. enumerable: true,
  4606. configurable: true
  4607. });
  4608. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4609. set: function (level) {
  4610. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4611. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4612. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4613. return;
  4614. }
  4615. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4616. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4617. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4618. return;
  4619. }
  4620. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4621. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4622. },
  4623. enumerable: true,
  4624. configurable: true
  4625. });
  4626. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4627. };
  4628. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4629. };
  4630. Tools._StartUserMark = function (counterName, condition) {
  4631. if (condition === void 0) { condition = true; }
  4632. if (!condition || !Tools._performance.mark) {
  4633. return;
  4634. }
  4635. Tools._performance.mark(counterName + "-Begin");
  4636. };
  4637. Tools._EndUserMark = function (counterName, condition) {
  4638. if (condition === void 0) { condition = true; }
  4639. if (!condition || !Tools._performance.mark) {
  4640. return;
  4641. }
  4642. Tools._performance.mark(counterName + "-End");
  4643. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4644. };
  4645. Tools._StartPerformanceConsole = function (counterName, condition) {
  4646. if (condition === void 0) { condition = true; }
  4647. if (!condition) {
  4648. return;
  4649. }
  4650. Tools._StartUserMark(counterName, condition);
  4651. if (console.time) {
  4652. console.time(counterName);
  4653. }
  4654. };
  4655. Tools._EndPerformanceConsole = function (counterName, condition) {
  4656. if (condition === void 0) { condition = true; }
  4657. if (!condition) {
  4658. return;
  4659. }
  4660. Tools._EndUserMark(counterName, condition);
  4661. if (console.time) {
  4662. console.timeEnd(counterName);
  4663. }
  4664. };
  4665. Object.defineProperty(Tools, "Now", {
  4666. get: function () {
  4667. if (window.performance && window.performance.now) {
  4668. return window.performance.now();
  4669. }
  4670. return new Date().getTime();
  4671. },
  4672. enumerable: true,
  4673. configurable: true
  4674. });
  4675. Tools.BaseUrl = "";
  4676. Tools.CorsBehavior = "anonymous";
  4677. // Logs
  4678. Tools._NoneLogLevel = 0;
  4679. Tools._MessageLogLevel = 1;
  4680. Tools._WarningLogLevel = 2;
  4681. Tools._ErrorLogLevel = 4;
  4682. Tools._LogCache = "";
  4683. Tools.errorsCount = 0;
  4684. Tools.Log = Tools._LogEnabled;
  4685. Tools.Warn = Tools._WarnEnabled;
  4686. Tools.Error = Tools._ErrorEnabled;
  4687. // Performances
  4688. Tools._PerformanceNoneLogLevel = 0;
  4689. Tools._PerformanceUserMarkLogLevel = 1;
  4690. Tools._PerformanceConsoleLogLevel = 2;
  4691. Tools._performance = window.performance;
  4692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4694. return Tools;
  4695. })();
  4696. BABYLON.Tools = Tools;
  4697. /**
  4698. * An implementation of a loop for asynchronous functions.
  4699. */
  4700. var AsyncLoop = (function () {
  4701. /**
  4702. * Constroctor.
  4703. * @param iterations the number of iterations.
  4704. * @param _fn the function to run each iteration
  4705. * @param _successCallback the callback that will be called upon succesful execution
  4706. * @param offset starting offset.
  4707. */
  4708. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4709. if (offset === void 0) { offset = 0; }
  4710. this.iterations = iterations;
  4711. this._fn = _fn;
  4712. this._successCallback = _successCallback;
  4713. this.index = offset - 1;
  4714. this._done = false;
  4715. }
  4716. /**
  4717. * Execute the next iteration. Must be called after the last iteration was finished.
  4718. */
  4719. AsyncLoop.prototype.executeNext = function () {
  4720. if (!this._done) {
  4721. if (this.index + 1 < this.iterations) {
  4722. ++this.index;
  4723. this._fn(this);
  4724. }
  4725. else {
  4726. this.breakLoop();
  4727. }
  4728. }
  4729. };
  4730. /**
  4731. * Break the loop and run the success callback.
  4732. */
  4733. AsyncLoop.prototype.breakLoop = function () {
  4734. this._done = true;
  4735. this._successCallback();
  4736. };
  4737. /**
  4738. * Helper function
  4739. */
  4740. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4741. if (offset === void 0) { offset = 0; }
  4742. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4743. loop.executeNext();
  4744. return loop;
  4745. };
  4746. /**
  4747. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4748. * @param iterations total number of iterations
  4749. * @param syncedIterations number of synchronous iterations in each async iteration.
  4750. * @param fn the function to call each iteration.
  4751. * @param callback a success call back that will be called when iterating stops.
  4752. * @param breakFunction a break condition (optional)
  4753. * @param timeout timeout settings for the setTimeout function. default - 0.
  4754. * @constructor
  4755. */
  4756. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4757. if (timeout === void 0) { timeout = 0; }
  4758. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4759. if (breakFunction && breakFunction())
  4760. loop.breakLoop();
  4761. else {
  4762. setTimeout(function () {
  4763. for (var i = 0; i < syncedIterations; ++i) {
  4764. var iteration = (loop.index * syncedIterations) + i;
  4765. if (iteration >= iterations)
  4766. break;
  4767. fn(iteration);
  4768. if (breakFunction && breakFunction()) {
  4769. loop.breakLoop();
  4770. break;
  4771. }
  4772. }
  4773. loop.executeNext();
  4774. }, timeout);
  4775. }
  4776. }, callback);
  4777. };
  4778. return AsyncLoop;
  4779. })();
  4780. BABYLON.AsyncLoop = AsyncLoop;
  4781. })(BABYLON || (BABYLON = {}));
  4782. var BABYLON;
  4783. (function (BABYLON) {
  4784. var _DepthCullingState = (function () {
  4785. function _DepthCullingState() {
  4786. this._isDepthTestDirty = false;
  4787. this._isDepthMaskDirty = false;
  4788. this._isDepthFuncDirty = false;
  4789. this._isCullFaceDirty = false;
  4790. this._isCullDirty = false;
  4791. this._isZOffsetDirty = false;
  4792. }
  4793. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4794. get: function () {
  4795. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4801. get: function () {
  4802. return this._zOffset;
  4803. },
  4804. set: function (value) {
  4805. if (this._zOffset === value) {
  4806. return;
  4807. }
  4808. this._zOffset = value;
  4809. this._isZOffsetDirty = true;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4815. get: function () {
  4816. return this._cullFace;
  4817. },
  4818. set: function (value) {
  4819. if (this._cullFace === value) {
  4820. return;
  4821. }
  4822. this._cullFace = value;
  4823. this._isCullFaceDirty = true;
  4824. },
  4825. enumerable: true,
  4826. configurable: true
  4827. });
  4828. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4829. get: function () {
  4830. return this._cull;
  4831. },
  4832. set: function (value) {
  4833. if (this._cull === value) {
  4834. return;
  4835. }
  4836. this._cull = value;
  4837. this._isCullDirty = true;
  4838. },
  4839. enumerable: true,
  4840. configurable: true
  4841. });
  4842. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4843. get: function () {
  4844. return this._depthFunc;
  4845. },
  4846. set: function (value) {
  4847. if (this._depthFunc === value) {
  4848. return;
  4849. }
  4850. this._depthFunc = value;
  4851. this._isDepthFuncDirty = true;
  4852. },
  4853. enumerable: true,
  4854. configurable: true
  4855. });
  4856. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4857. get: function () {
  4858. return this._depthMask;
  4859. },
  4860. set: function (value) {
  4861. if (this._depthMask === value) {
  4862. return;
  4863. }
  4864. this._depthMask = value;
  4865. this._isDepthMaskDirty = true;
  4866. },
  4867. enumerable: true,
  4868. configurable: true
  4869. });
  4870. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4871. get: function () {
  4872. return this._depthTest;
  4873. },
  4874. set: function (value) {
  4875. if (this._depthTest === value) {
  4876. return;
  4877. }
  4878. this._depthTest = value;
  4879. this._isDepthTestDirty = true;
  4880. },
  4881. enumerable: true,
  4882. configurable: true
  4883. });
  4884. _DepthCullingState.prototype.reset = function () {
  4885. this._depthMask = true;
  4886. this._depthTest = true;
  4887. this._depthFunc = null;
  4888. this._cull = null;
  4889. this._cullFace = null;
  4890. this._zOffset = 0;
  4891. this._isDepthTestDirty = true;
  4892. this._isDepthMaskDirty = true;
  4893. this._isDepthFuncDirty = false;
  4894. this._isCullFaceDirty = false;
  4895. this._isCullDirty = false;
  4896. this._isZOffsetDirty = false;
  4897. };
  4898. _DepthCullingState.prototype.apply = function (gl) {
  4899. if (!this.isDirty) {
  4900. return;
  4901. }
  4902. // Cull
  4903. if (this._isCullDirty) {
  4904. if (this.cull) {
  4905. gl.enable(gl.CULL_FACE);
  4906. }
  4907. else {
  4908. gl.disable(gl.CULL_FACE);
  4909. }
  4910. this._isCullDirty = false;
  4911. }
  4912. // Cull face
  4913. if (this._isCullFaceDirty) {
  4914. gl.cullFace(this.cullFace);
  4915. this._isCullFaceDirty = false;
  4916. }
  4917. // Depth mask
  4918. if (this._isDepthMaskDirty) {
  4919. gl.depthMask(this.depthMask);
  4920. this._isDepthMaskDirty = false;
  4921. }
  4922. // Depth test
  4923. if (this._isDepthTestDirty) {
  4924. if (this.depthTest) {
  4925. gl.enable(gl.DEPTH_TEST);
  4926. }
  4927. else {
  4928. gl.disable(gl.DEPTH_TEST);
  4929. }
  4930. this._isDepthTestDirty = false;
  4931. }
  4932. // Depth func
  4933. if (this._isDepthFuncDirty) {
  4934. gl.depthFunc(this.depthFunc);
  4935. this._isDepthFuncDirty = false;
  4936. }
  4937. // zOffset
  4938. if (this._isZOffsetDirty) {
  4939. if (this.zOffset) {
  4940. gl.enable(gl.POLYGON_OFFSET_FILL);
  4941. gl.polygonOffset(this.zOffset, 0);
  4942. }
  4943. else {
  4944. gl.disable(gl.POLYGON_OFFSET_FILL);
  4945. }
  4946. this._isZOffsetDirty = false;
  4947. }
  4948. };
  4949. return _DepthCullingState;
  4950. })();
  4951. BABYLON._DepthCullingState = _DepthCullingState;
  4952. var _AlphaState = (function () {
  4953. function _AlphaState() {
  4954. this._isAlphaBlendDirty = false;
  4955. this._isBlendFunctionParametersDirty = false;
  4956. this._alphaBlend = false;
  4957. this._blendFunctionParameters = new Array(4);
  4958. }
  4959. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4960. get: function () {
  4961. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4967. get: function () {
  4968. return this._alphaBlend;
  4969. },
  4970. set: function (value) {
  4971. if (this._alphaBlend === value) {
  4972. return;
  4973. }
  4974. this._alphaBlend = value;
  4975. this._isAlphaBlendDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4981. if (this._blendFunctionParameters[0] === value0 &&
  4982. this._blendFunctionParameters[1] === value1 &&
  4983. this._blendFunctionParameters[2] === value2 &&
  4984. this._blendFunctionParameters[3] === value3) {
  4985. return;
  4986. }
  4987. this._blendFunctionParameters[0] = value0;
  4988. this._blendFunctionParameters[1] = value1;
  4989. this._blendFunctionParameters[2] = value2;
  4990. this._blendFunctionParameters[3] = value3;
  4991. this._isBlendFunctionParametersDirty = true;
  4992. };
  4993. _AlphaState.prototype.reset = function () {
  4994. this._alphaBlend = false;
  4995. this._blendFunctionParameters[0] = null;
  4996. this._blendFunctionParameters[1] = null;
  4997. this._blendFunctionParameters[2] = null;
  4998. this._blendFunctionParameters[3] = null;
  4999. this._isAlphaBlendDirty = true;
  5000. this._isBlendFunctionParametersDirty = false;
  5001. };
  5002. _AlphaState.prototype.apply = function (gl) {
  5003. if (!this.isDirty) {
  5004. return;
  5005. }
  5006. // Alpha blend
  5007. if (this._isAlphaBlendDirty) {
  5008. if (this._alphaBlend) {
  5009. gl.enable(gl.BLEND);
  5010. }
  5011. else {
  5012. gl.disable(gl.BLEND);
  5013. }
  5014. this._isAlphaBlendDirty = false;
  5015. }
  5016. // Alpha function
  5017. if (this._isBlendFunctionParametersDirty) {
  5018. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5019. this._isBlendFunctionParametersDirty = false;
  5020. }
  5021. };
  5022. return _AlphaState;
  5023. })();
  5024. BABYLON._AlphaState = _AlphaState;
  5025. var compileShader = function (gl, source, type, defines) {
  5026. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5027. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5028. gl.compileShader(shader);
  5029. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5030. throw new Error(gl.getShaderInfoLog(shader));
  5031. }
  5032. return shader;
  5033. };
  5034. var getWebGLTextureType = function (gl, type) {
  5035. var textureType = gl.UNSIGNED_BYTE;
  5036. if (type === Engine.TEXTURETYPE_FLOAT)
  5037. textureType = gl.FLOAT;
  5038. return textureType;
  5039. };
  5040. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5041. var magFilter = gl.NEAREST;
  5042. var minFilter = gl.NEAREST;
  5043. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5044. magFilter = gl.LINEAR;
  5045. if (generateMipMaps) {
  5046. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5047. }
  5048. else {
  5049. minFilter = gl.LINEAR;
  5050. }
  5051. }
  5052. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5053. magFilter = gl.LINEAR;
  5054. if (generateMipMaps) {
  5055. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5056. }
  5057. else {
  5058. minFilter = gl.LINEAR;
  5059. }
  5060. }
  5061. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5062. magFilter = gl.NEAREST;
  5063. if (generateMipMaps) {
  5064. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5065. }
  5066. else {
  5067. minFilter = gl.NEAREST;
  5068. }
  5069. }
  5070. return {
  5071. min: minFilter,
  5072. mag: magFilter
  5073. };
  5074. };
  5075. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5077. var engine = scene.getEngine();
  5078. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5079. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5080. gl.bindTexture(gl.TEXTURE_2D, texture);
  5081. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5082. texture._baseWidth = width;
  5083. texture._baseHeight = height;
  5084. texture._width = potWidth;
  5085. texture._height = potHeight;
  5086. texture.isReady = true;
  5087. processFunction(potWidth, potHeight);
  5088. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5091. if (!noMipmap && !isCompressed) {
  5092. gl.generateMipmap(gl.TEXTURE_2D);
  5093. }
  5094. gl.bindTexture(gl.TEXTURE_2D, null);
  5095. engine.resetTextureCache();
  5096. scene._removePendingData(texture);
  5097. };
  5098. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5099. var img;
  5100. var onload = function () {
  5101. loadedImages[index] = img;
  5102. loadedImages._internalCount++;
  5103. scene._removePendingData(img);
  5104. if (loadedImages._internalCount === 6) {
  5105. onfinish(loadedImages);
  5106. }
  5107. };
  5108. var onerror = function () {
  5109. scene._removePendingData(img);
  5110. };
  5111. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5112. scene._addPendingData(img);
  5113. };
  5114. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5115. var loadedImages = [];
  5116. loadedImages._internalCount = 0;
  5117. for (var index = 0; index < 6; index++) {
  5118. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5119. }
  5120. };
  5121. var EngineCapabilities = (function () {
  5122. function EngineCapabilities() {
  5123. }
  5124. return EngineCapabilities;
  5125. })();
  5126. BABYLON.EngineCapabilities = EngineCapabilities;
  5127. /**
  5128. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5129. */
  5130. var Engine = (function () {
  5131. /**
  5132. * @constructor
  5133. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5134. * @param {boolean} [antialias] - enable antialias
  5135. * @param options - further options to be sent to the getContext function
  5136. */
  5137. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5138. var _this = this;
  5139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5140. // Public members
  5141. this.isFullscreen = false;
  5142. this.isPointerLock = false;
  5143. this.cullBackFaces = true;
  5144. this.renderEvenInBackground = true;
  5145. // To enable/disable IDB support and avoid XHR on .manifest
  5146. this.enableOfflineSupport = true;
  5147. this.scenes = new Array();
  5148. this._windowIsBackground = false;
  5149. this._drawCalls = 0;
  5150. this._renderingQueueLaunched = false;
  5151. this._activeRenderLoops = [];
  5152. // FPS
  5153. this.fpsRange = 60;
  5154. this.previousFramesDuration = [];
  5155. this.fps = 60;
  5156. this.deltaTime = 0;
  5157. // States
  5158. this._depthCullingState = new _DepthCullingState();
  5159. this._alphaState = new _AlphaState();
  5160. this._alphaMode = Engine.ALPHA_DISABLE;
  5161. // Cache
  5162. this._loadedTexturesCache = new Array();
  5163. this._maxTextureChannels = 16;
  5164. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5165. this._compiledEffects = {};
  5166. this._uintIndicesCurrentlySet = false;
  5167. this._renderingCanvas = canvas;
  5168. options = options || {};
  5169. options.antialias = antialias;
  5170. if (options.preserveDrawingBuffer === undefined) {
  5171. options.preserveDrawingBuffer = false;
  5172. }
  5173. // GL
  5174. try {
  5175. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5176. }
  5177. catch (e) {
  5178. throw new Error("WebGL not supported");
  5179. }
  5180. if (!this._gl) {
  5181. throw new Error("WebGL not supported");
  5182. }
  5183. this._onBlur = function () {
  5184. _this._windowIsBackground = true;
  5185. };
  5186. this._onFocus = function () {
  5187. _this._windowIsBackground = false;
  5188. };
  5189. window.addEventListener("blur", this._onBlur);
  5190. window.addEventListener("focus", this._onFocus);
  5191. // Viewport
  5192. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5193. this.resize();
  5194. // Caps
  5195. this._caps = new EngineCapabilities();
  5196. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5197. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5198. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5199. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5200. // Infos
  5201. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5202. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5203. if (rendererInfo != null) {
  5204. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5205. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5206. }
  5207. if (!this._glVendor) {
  5208. this._glVendor = "Unknown vendor";
  5209. }
  5210. if (!this._glRenderer) {
  5211. this._glRenderer = "Unknown renderer";
  5212. }
  5213. // Extensions
  5214. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5215. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5216. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5217. 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');
  5218. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5219. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5220. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5221. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5222. this._caps.highPrecisionShaderSupported = true;
  5223. if (this._gl.getShaderPrecisionFormat) {
  5224. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5225. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5226. }
  5227. // Depth buffer
  5228. this.setDepthBuffer(true);
  5229. this.setDepthFunctionToLessOrEqual();
  5230. this.setDepthWrite(true);
  5231. // Fullscreen
  5232. this._onFullscreenChange = function () {
  5233. if (document.fullscreen !== undefined) {
  5234. _this.isFullscreen = document.fullscreen;
  5235. }
  5236. else if (document.mozFullScreen !== undefined) {
  5237. _this.isFullscreen = document.mozFullScreen;
  5238. }
  5239. else if (document.webkitIsFullScreen !== undefined) {
  5240. _this.isFullscreen = document.webkitIsFullScreen;
  5241. }
  5242. else if (document.msIsFullScreen !== undefined) {
  5243. _this.isFullscreen = document.msIsFullScreen;
  5244. }
  5245. // Pointer lock
  5246. if (_this.isFullscreen && _this._pointerLockRequested) {
  5247. canvas.requestPointerLock = canvas.requestPointerLock ||
  5248. canvas.msRequestPointerLock ||
  5249. canvas.mozRequestPointerLock ||
  5250. canvas.webkitRequestPointerLock;
  5251. if (canvas.requestPointerLock) {
  5252. canvas.requestPointerLock();
  5253. }
  5254. }
  5255. };
  5256. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5257. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5258. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5259. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5260. // Pointer lock
  5261. this._onPointerLockChange = function () {
  5262. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5263. document.webkitPointerLockElement === canvas ||
  5264. document.msPointerLockElement === canvas ||
  5265. document.pointerLockElement === canvas);
  5266. };
  5267. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5268. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5269. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5270. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5271. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5272. Engine.audioEngine = new BABYLON.AudioEngine();
  5273. }
  5274. //default loading screen
  5275. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5276. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5277. }
  5278. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5279. get: function () {
  5280. return Engine._ALPHA_DISABLE;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5286. get: function () {
  5287. return Engine._ALPHA_ONEONE;
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Object.defineProperty(Engine, "ALPHA_ADD", {
  5293. get: function () {
  5294. return Engine._ALPHA_ADD;
  5295. },
  5296. enumerable: true,
  5297. configurable: true
  5298. });
  5299. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5300. get: function () {
  5301. return Engine._ALPHA_COMBINE;
  5302. },
  5303. enumerable: true,
  5304. configurable: true
  5305. });
  5306. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5307. get: function () {
  5308. return Engine._ALPHA_SUBTRACT;
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5314. get: function () {
  5315. return Engine._ALPHA_MULTIPLY;
  5316. },
  5317. enumerable: true,
  5318. configurable: true
  5319. });
  5320. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5321. get: function () {
  5322. return Engine._ALPHA_MAXIMIZED;
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5328. get: function () {
  5329. return Engine._DELAYLOADSTATE_NONE;
  5330. },
  5331. enumerable: true,
  5332. configurable: true
  5333. });
  5334. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5335. get: function () {
  5336. return Engine._DELAYLOADSTATE_LOADED;
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5342. get: function () {
  5343. return Engine._DELAYLOADSTATE_LOADING;
  5344. },
  5345. enumerable: true,
  5346. configurable: true
  5347. });
  5348. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5349. get: function () {
  5350. return Engine._DELAYLOADSTATE_NOTLOADED;
  5351. },
  5352. enumerable: true,
  5353. configurable: true
  5354. });
  5355. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5356. get: function () {
  5357. return Engine._TEXTUREFORMAT_ALPHA;
  5358. },
  5359. enumerable: true,
  5360. configurable: true
  5361. });
  5362. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5363. get: function () {
  5364. return Engine._TEXTUREFORMAT_LUMINANCE;
  5365. },
  5366. enumerable: true,
  5367. configurable: true
  5368. });
  5369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5370. get: function () {
  5371. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5372. },
  5373. enumerable: true,
  5374. configurable: true
  5375. });
  5376. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5377. get: function () {
  5378. return Engine._TEXTUREFORMAT_RGB;
  5379. },
  5380. enumerable: true,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5384. get: function () {
  5385. return Engine._TEXTUREFORMAT_RGBA;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5391. get: function () {
  5392. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5398. get: function () {
  5399. return Engine._TEXTURETYPE_FLOAT;
  5400. },
  5401. enumerable: true,
  5402. configurable: true
  5403. });
  5404. Object.defineProperty(Engine, "Version", {
  5405. get: function () {
  5406. return "2.3.0-alpha";
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Engine.prototype._prepareWorkingCanvas = function () {
  5412. if (this._workingCanvas) {
  5413. return;
  5414. }
  5415. this._workingCanvas = document.createElement("canvas");
  5416. this._workingContext = this._workingCanvas.getContext("2d");
  5417. };
  5418. Engine.prototype.resetTextureCache = function () {
  5419. for (var index = 0; index < this._maxTextureChannels; index++) {
  5420. this._activeTexturesCache[index] = null;
  5421. }
  5422. };
  5423. Engine.prototype.getGlInfo = function () {
  5424. return {
  5425. vendor: this._glVendor,
  5426. renderer: this._glRenderer,
  5427. version: this._glVersion
  5428. };
  5429. };
  5430. Engine.prototype.getAspectRatio = function (camera) {
  5431. var viewport = camera.viewport;
  5432. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5433. };
  5434. Engine.prototype.getRenderWidth = function () {
  5435. if (this._currentRenderTarget) {
  5436. return this._currentRenderTarget._width;
  5437. }
  5438. return this._renderingCanvas.width;
  5439. };
  5440. Engine.prototype.getRenderHeight = function () {
  5441. if (this._currentRenderTarget) {
  5442. return this._currentRenderTarget._height;
  5443. }
  5444. return this._renderingCanvas.height;
  5445. };
  5446. Engine.prototype.getRenderingCanvas = function () {
  5447. return this._renderingCanvas;
  5448. };
  5449. Engine.prototype.getRenderingCanvasClientRect = function () {
  5450. return this._renderingCanvas.getBoundingClientRect();
  5451. };
  5452. Engine.prototype.setHardwareScalingLevel = function (level) {
  5453. this._hardwareScalingLevel = level;
  5454. this.resize();
  5455. };
  5456. Engine.prototype.getHardwareScalingLevel = function () {
  5457. return this._hardwareScalingLevel;
  5458. };
  5459. Engine.prototype.getLoadedTexturesCache = function () {
  5460. return this._loadedTexturesCache;
  5461. };
  5462. Engine.prototype.getCaps = function () {
  5463. return this._caps;
  5464. };
  5465. Object.defineProperty(Engine.prototype, "drawCalls", {
  5466. get: function () {
  5467. return this._drawCalls;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. // Methods
  5473. Engine.prototype.resetDrawCalls = function () {
  5474. this._drawCalls = 0;
  5475. };
  5476. Engine.prototype.setDepthFunctionToGreater = function () {
  5477. this._depthCullingState.depthFunc = this._gl.GREATER;
  5478. };
  5479. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5480. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5481. };
  5482. Engine.prototype.setDepthFunctionToLess = function () {
  5483. this._depthCullingState.depthFunc = this._gl.LESS;
  5484. };
  5485. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5486. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5487. };
  5488. /**
  5489. * stop executing a render loop function and remove it from the execution array
  5490. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5491. */
  5492. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5493. if (!renderFunction) {
  5494. this._activeRenderLoops = [];
  5495. return;
  5496. }
  5497. var index = this._activeRenderLoops.indexOf(renderFunction);
  5498. if (index >= 0) {
  5499. this._activeRenderLoops.splice(index, 1);
  5500. }
  5501. };
  5502. Engine.prototype._renderLoop = function () {
  5503. var shouldRender = true;
  5504. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5505. shouldRender = false;
  5506. }
  5507. if (shouldRender) {
  5508. // Start new frame
  5509. this.beginFrame();
  5510. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5511. var renderFunction = this._activeRenderLoops[index];
  5512. renderFunction();
  5513. }
  5514. // Present
  5515. this.endFrame();
  5516. }
  5517. if (this._activeRenderLoops.length > 0) {
  5518. // Register new frame
  5519. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5520. }
  5521. else {
  5522. this._renderingQueueLaunched = false;
  5523. }
  5524. };
  5525. /**
  5526. * Register and execute a render loop. The engine can have more than one render function.
  5527. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5528. * @example
  5529. * engine.runRenderLoop(function () {
  5530. * scene.render()
  5531. * })
  5532. */
  5533. Engine.prototype.runRenderLoop = function (renderFunction) {
  5534. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5535. return;
  5536. }
  5537. this._activeRenderLoops.push(renderFunction);
  5538. if (!this._renderingQueueLaunched) {
  5539. this._renderingQueueLaunched = true;
  5540. this._bindedRenderFunction = this._renderLoop.bind(this);
  5541. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5542. }
  5543. };
  5544. /**
  5545. * Toggle full screen mode.
  5546. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5547. */
  5548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5549. if (this.isFullscreen) {
  5550. BABYLON.Tools.ExitFullscreen();
  5551. }
  5552. else {
  5553. this._pointerLockRequested = requestPointerLock;
  5554. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5555. }
  5556. };
  5557. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5558. this.applyStates();
  5559. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5560. if (this._depthCullingState.depthMask) {
  5561. this._gl.clearDepth(1.0);
  5562. }
  5563. var mode = 0;
  5564. if (backBuffer)
  5565. mode |= this._gl.COLOR_BUFFER_BIT;
  5566. if (depthStencil && this._depthCullingState.depthMask)
  5567. mode |= this._gl.DEPTH_BUFFER_BIT;
  5568. this._gl.clear(mode);
  5569. };
  5570. /**
  5571. * Set the WebGL's viewport
  5572. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5573. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5574. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5575. */
  5576. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5577. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5578. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5579. var x = viewport.x || 0;
  5580. var y = viewport.y || 0;
  5581. this._cachedViewport = viewport;
  5582. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5583. };
  5584. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5585. this._cachedViewport = null;
  5586. this._gl.viewport(x, y, width, height);
  5587. };
  5588. Engine.prototype.beginFrame = function () {
  5589. this._measureFps();
  5590. };
  5591. Engine.prototype.endFrame = function () {
  5592. //this.flushFramebuffer();
  5593. };
  5594. /**
  5595. * resize the view according to the canvas' size.
  5596. * @example
  5597. * window.addEventListener("resize", function () {
  5598. * engine.resize();
  5599. * });
  5600. */
  5601. Engine.prototype.resize = function () {
  5602. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5603. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5604. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5605. for (var index = 0; index < this.scenes.length; index++) {
  5606. var scene = this.scenes[index];
  5607. if (scene.debugLayer.isVisible()) {
  5608. scene.debugLayer._syncPositions();
  5609. }
  5610. }
  5611. };
  5612. /**
  5613. * force a specific size of the canvas
  5614. * @param {number} width - the new canvas' width
  5615. * @param {number} height - the new canvas' height
  5616. */
  5617. Engine.prototype.setSize = function (width, height) {
  5618. this._renderingCanvas.width = width;
  5619. this._renderingCanvas.height = height;
  5620. for (var index = 0; index < this.scenes.length; index++) {
  5621. var scene = this.scenes[index];
  5622. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5623. var cam = scene.cameras[camIndex];
  5624. cam._currentRenderId = 0;
  5625. }
  5626. }
  5627. };
  5628. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5629. this._currentRenderTarget = texture;
  5630. var gl = this._gl;
  5631. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5632. if (texture.isCube) {
  5633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5634. }
  5635. else {
  5636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5637. }
  5638. this._gl.viewport(0, 0, texture._width, texture._height);
  5639. this.wipeCaches();
  5640. };
  5641. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5642. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5643. this._currentRenderTarget = null;
  5644. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5645. var gl = this._gl;
  5646. gl.bindTexture(gl.TEXTURE_2D, texture);
  5647. gl.generateMipmap(gl.TEXTURE_2D);
  5648. gl.bindTexture(gl.TEXTURE_2D, null);
  5649. }
  5650. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5651. };
  5652. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5653. if (texture.generateMipMaps) {
  5654. var gl = this._gl;
  5655. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5657. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5658. }
  5659. };
  5660. Engine.prototype.flushFramebuffer = function () {
  5661. this._gl.flush();
  5662. };
  5663. Engine.prototype.restoreDefaultFramebuffer = function () {
  5664. this._currentRenderTarget = null;
  5665. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5666. this.setViewport(this._cachedViewport);
  5667. this.wipeCaches();
  5668. };
  5669. // VBOs
  5670. Engine.prototype._resetVertexBufferBinding = function () {
  5671. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5672. this._cachedVertexBuffers = null;
  5673. };
  5674. Engine.prototype.createVertexBuffer = function (vertices) {
  5675. var vbo = this._gl.createBuffer();
  5676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5677. if (vertices instanceof Float32Array) {
  5678. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5679. }
  5680. else {
  5681. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5682. }
  5683. this._resetVertexBufferBinding();
  5684. vbo.references = 1;
  5685. return vbo;
  5686. };
  5687. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5688. var vbo = this._gl.createBuffer();
  5689. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5690. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5691. this._resetVertexBufferBinding();
  5692. vbo.references = 1;
  5693. return vbo;
  5694. };
  5695. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5696. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5697. if (offset === undefined) {
  5698. offset = 0;
  5699. }
  5700. if (vertices instanceof Float32Array) {
  5701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5702. }
  5703. else {
  5704. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5705. }
  5706. this._resetVertexBufferBinding();
  5707. };
  5708. Engine.prototype._resetIndexBufferBinding = function () {
  5709. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5710. this._cachedIndexBuffer = null;
  5711. };
  5712. Engine.prototype.createIndexBuffer = function (indices) {
  5713. var vbo = this._gl.createBuffer();
  5714. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5715. // Check for 32 bits indices
  5716. var arrayBuffer;
  5717. var need32Bits = false;
  5718. if (this._caps.uintIndices) {
  5719. for (var index = 0; index < indices.length; index++) {
  5720. if (indices[index] > 65535) {
  5721. need32Bits = true;
  5722. break;
  5723. }
  5724. }
  5725. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5726. }
  5727. else {
  5728. arrayBuffer = new Uint16Array(indices);
  5729. }
  5730. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5731. this._resetIndexBufferBinding();
  5732. vbo.references = 1;
  5733. vbo.is32Bits = need32Bits;
  5734. return vbo;
  5735. };
  5736. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5737. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5738. this._cachedVertexBuffers = vertexBuffer;
  5739. this._cachedEffectForVertexBuffers = effect;
  5740. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5741. var offset = 0;
  5742. for (var index = 0; index < vertexDeclaration.length; index++) {
  5743. var order = effect.getAttributeLocation(index);
  5744. if (order >= 0) {
  5745. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5746. }
  5747. offset += vertexDeclaration[index] * 4;
  5748. }
  5749. }
  5750. if (this._cachedIndexBuffer !== indexBuffer) {
  5751. this._cachedIndexBuffer = indexBuffer;
  5752. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5753. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5754. }
  5755. };
  5756. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5757. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5758. this._cachedVertexBuffers = vertexBuffers;
  5759. this._cachedEffectForVertexBuffers = effect;
  5760. var attributes = effect.getAttributesNames();
  5761. for (var index = 0; index < attributes.length; index++) {
  5762. var order = effect.getAttributeLocation(index);
  5763. if (order >= 0) {
  5764. var vertexBuffer = vertexBuffers[attributes[index]];
  5765. if (!vertexBuffer) {
  5766. continue;
  5767. }
  5768. var stride = vertexBuffer.getStrideSize();
  5769. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5770. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5771. }
  5772. }
  5773. }
  5774. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5775. this._cachedIndexBuffer = indexBuffer;
  5776. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5777. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5778. }
  5779. };
  5780. Engine.prototype._releaseBuffer = function (buffer) {
  5781. buffer.references--;
  5782. if (buffer.references === 0) {
  5783. this._gl.deleteBuffer(buffer);
  5784. return true;
  5785. }
  5786. return false;
  5787. };
  5788. Engine.prototype.createInstancesBuffer = function (capacity) {
  5789. var buffer = this._gl.createBuffer();
  5790. buffer.capacity = capacity;
  5791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5792. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5793. return buffer;
  5794. };
  5795. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5796. this._gl.deleteBuffer(buffer);
  5797. };
  5798. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5799. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5801. for (var index = 0; index < 4; index++) {
  5802. var offsetLocation = offsetLocations[index];
  5803. this._gl.enableVertexAttribArray(offsetLocation);
  5804. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5805. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5806. }
  5807. };
  5808. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5809. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5810. for (var index = 0; index < 4; index++) {
  5811. var offsetLocation = offsetLocations[index];
  5812. this._gl.disableVertexAttribArray(offsetLocation);
  5813. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5814. }
  5815. };
  5816. Engine.prototype.applyStates = function () {
  5817. this._depthCullingState.apply(this._gl);
  5818. this._alphaState.apply(this._gl);
  5819. };
  5820. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5821. // Apply states
  5822. this.applyStates();
  5823. this._drawCalls++;
  5824. // Render
  5825. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5826. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5827. if (instancesCount) {
  5828. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5829. return;
  5830. }
  5831. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5832. };
  5833. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5834. // Apply states
  5835. this.applyStates();
  5836. this._drawCalls++;
  5837. if (instancesCount) {
  5838. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5839. return;
  5840. }
  5841. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5842. };
  5843. // Shaders
  5844. Engine.prototype._releaseEffect = function (effect) {
  5845. if (this._compiledEffects[effect._key]) {
  5846. delete this._compiledEffects[effect._key];
  5847. if (effect.getProgram()) {
  5848. this._gl.deleteProgram(effect.getProgram());
  5849. }
  5850. }
  5851. };
  5852. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5853. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5854. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5855. var name = vertex + "+" + fragment + "@" + defines;
  5856. if (this._compiledEffects[name]) {
  5857. return this._compiledEffects[name];
  5858. }
  5859. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5860. effect._key = name;
  5861. this._compiledEffects[name] = effect;
  5862. return effect;
  5863. };
  5864. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5865. if (uniformsNames === void 0) { uniformsNames = []; }
  5866. if (samplers === void 0) { samplers = []; }
  5867. if (defines === void 0) { defines = ""; }
  5868. return this.createEffect({
  5869. vertex: "particles",
  5870. fragmentElement: fragmentName
  5871. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5872. };
  5873. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5874. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5875. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5876. var shaderProgram = this._gl.createProgram();
  5877. this._gl.attachShader(shaderProgram, vertexShader);
  5878. this._gl.attachShader(shaderProgram, fragmentShader);
  5879. this._gl.linkProgram(shaderProgram);
  5880. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5881. if (!linked) {
  5882. var error = this._gl.getProgramInfoLog(shaderProgram);
  5883. if (error) {
  5884. throw new Error(error);
  5885. }
  5886. }
  5887. this._gl.deleteShader(vertexShader);
  5888. this._gl.deleteShader(fragmentShader);
  5889. return shaderProgram;
  5890. };
  5891. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5892. var results = [];
  5893. for (var index = 0; index < uniformsNames.length; index++) {
  5894. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5895. }
  5896. return results;
  5897. };
  5898. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5899. var results = [];
  5900. for (var index = 0; index < attributesNames.length; index++) {
  5901. try {
  5902. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5903. }
  5904. catch (e) {
  5905. results.push(-1);
  5906. }
  5907. }
  5908. return results;
  5909. };
  5910. Engine.prototype.enableEffect = function (effect) {
  5911. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5912. if (effect && effect.onBind) {
  5913. effect.onBind(effect);
  5914. }
  5915. return;
  5916. }
  5917. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5918. // Use program
  5919. this._gl.useProgram(effect.getProgram());
  5920. for (var i in this._vertexAttribArrays) {
  5921. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5922. continue;
  5923. }
  5924. this._vertexAttribArrays[i] = false;
  5925. this._gl.disableVertexAttribArray(i);
  5926. }
  5927. var attributesCount = effect.getAttributesCount();
  5928. for (var index = 0; index < attributesCount; index++) {
  5929. // Attributes
  5930. var order = effect.getAttributeLocation(index);
  5931. if (order >= 0) {
  5932. this._vertexAttribArrays[order] = true;
  5933. this._gl.enableVertexAttribArray(order);
  5934. }
  5935. }
  5936. this._currentEffect = effect;
  5937. if (effect.onBind) {
  5938. effect.onBind(effect);
  5939. }
  5940. };
  5941. Engine.prototype.setArray = function (uniform, array) {
  5942. if (!uniform)
  5943. return;
  5944. this._gl.uniform1fv(uniform, array);
  5945. };
  5946. Engine.prototype.setArray2 = function (uniform, array) {
  5947. if (!uniform || array.length % 2 !== 0)
  5948. return;
  5949. this._gl.uniform2fv(uniform, array);
  5950. };
  5951. Engine.prototype.setArray3 = function (uniform, array) {
  5952. if (!uniform || array.length % 3 !== 0)
  5953. return;
  5954. this._gl.uniform3fv(uniform, array);
  5955. };
  5956. Engine.prototype.setArray4 = function (uniform, array) {
  5957. if (!uniform || array.length % 4 !== 0)
  5958. return;
  5959. this._gl.uniform4fv(uniform, array);
  5960. };
  5961. Engine.prototype.setMatrices = function (uniform, matrices) {
  5962. if (!uniform)
  5963. return;
  5964. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5965. };
  5966. Engine.prototype.setMatrix = function (uniform, matrix) {
  5967. if (!uniform)
  5968. return;
  5969. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5970. };
  5971. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5972. if (!uniform)
  5973. return;
  5974. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5975. };
  5976. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5977. if (!uniform)
  5978. return;
  5979. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5980. };
  5981. Engine.prototype.setFloat = function (uniform, value) {
  5982. if (!uniform)
  5983. return;
  5984. this._gl.uniform1f(uniform, value);
  5985. };
  5986. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5987. if (!uniform)
  5988. return;
  5989. this._gl.uniform2f(uniform, x, y);
  5990. };
  5991. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5992. if (!uniform)
  5993. return;
  5994. this._gl.uniform3f(uniform, x, y, z);
  5995. };
  5996. Engine.prototype.setBool = function (uniform, bool) {
  5997. if (!uniform)
  5998. return;
  5999. this._gl.uniform1i(uniform, bool);
  6000. };
  6001. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6002. if (!uniform)
  6003. return;
  6004. this._gl.uniform4f(uniform, x, y, z, w);
  6005. };
  6006. Engine.prototype.setColor3 = function (uniform, color3) {
  6007. if (!uniform)
  6008. return;
  6009. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6010. };
  6011. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6012. if (!uniform)
  6013. return;
  6014. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6015. };
  6016. // States
  6017. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6018. if (zOffset === void 0) { zOffset = 0; }
  6019. if (reverseSide === void 0) { reverseSide = false; }
  6020. // Culling
  6021. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6022. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6023. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6024. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6025. if (culling) {
  6026. this._depthCullingState.cullFace = cullFace;
  6027. this._depthCullingState.cull = true;
  6028. }
  6029. else {
  6030. this._depthCullingState.cull = false;
  6031. }
  6032. }
  6033. // Z offset
  6034. this._depthCullingState.zOffset = zOffset;
  6035. };
  6036. Engine.prototype.setDepthBuffer = function (enable) {
  6037. this._depthCullingState.depthTest = enable;
  6038. };
  6039. Engine.prototype.getDepthWrite = function () {
  6040. return this._depthCullingState.depthMask;
  6041. };
  6042. Engine.prototype.setDepthWrite = function (enable) {
  6043. this._depthCullingState.depthMask = enable;
  6044. };
  6045. Engine.prototype.setColorWrite = function (enable) {
  6046. this._gl.colorMask(enable, enable, enable, enable);
  6047. };
  6048. Engine.prototype.setAlphaMode = function (mode) {
  6049. if (this._alphaMode === mode) {
  6050. return;
  6051. }
  6052. switch (mode) {
  6053. case Engine.ALPHA_DISABLE:
  6054. this.setDepthWrite(true);
  6055. this._alphaState.alphaBlend = false;
  6056. break;
  6057. case Engine.ALPHA_COMBINE:
  6058. this.setDepthWrite(false);
  6059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6060. this._alphaState.alphaBlend = true;
  6061. break;
  6062. case Engine.ALPHA_ONEONE:
  6063. this.setDepthWrite(false);
  6064. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6065. this._alphaState.alphaBlend = true;
  6066. break;
  6067. case Engine.ALPHA_ADD:
  6068. this.setDepthWrite(false);
  6069. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6070. this._alphaState.alphaBlend = true;
  6071. break;
  6072. case Engine.ALPHA_SUBTRACT:
  6073. this.setDepthWrite(false);
  6074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6075. this._alphaState.alphaBlend = true;
  6076. break;
  6077. case Engine.ALPHA_MULTIPLY:
  6078. this.setDepthWrite(false);
  6079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6080. this._alphaState.alphaBlend = true;
  6081. break;
  6082. case Engine.ALPHA_MAXIMIZED:
  6083. this.setDepthWrite(false);
  6084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6085. this._alphaState.alphaBlend = true;
  6086. break;
  6087. }
  6088. this._alphaMode = mode;
  6089. };
  6090. Engine.prototype.getAlphaMode = function () {
  6091. return this._alphaMode;
  6092. };
  6093. Engine.prototype.setAlphaTesting = function (enable) {
  6094. this._alphaTest = enable;
  6095. };
  6096. Engine.prototype.getAlphaTesting = function () {
  6097. return this._alphaTest;
  6098. };
  6099. // Textures
  6100. Engine.prototype.wipeCaches = function () {
  6101. this.resetTextureCache();
  6102. this._currentEffect = null;
  6103. this._depthCullingState.reset();
  6104. this._alphaState.reset();
  6105. this._cachedVertexBuffers = null;
  6106. this._cachedIndexBuffer = null;
  6107. this._cachedEffectForVertexBuffers = null;
  6108. };
  6109. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6110. var gl = this._gl;
  6111. gl.bindTexture(gl.TEXTURE_2D, texture);
  6112. var magFilter = gl.NEAREST;
  6113. var minFilter = gl.NEAREST;
  6114. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6115. magFilter = gl.LINEAR;
  6116. minFilter = gl.LINEAR;
  6117. }
  6118. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6119. magFilter = gl.LINEAR;
  6120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6121. }
  6122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6124. gl.bindTexture(gl.TEXTURE_2D, null);
  6125. texture.samplingMode = samplingMode;
  6126. };
  6127. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6128. var _this = this;
  6129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6130. if (onLoad === void 0) { onLoad = null; }
  6131. if (onError === void 0) { onError = null; }
  6132. if (buffer === void 0) { buffer = null; }
  6133. var texture = this._gl.createTexture();
  6134. var extension;
  6135. var fromData = false;
  6136. if (url.substr(0, 5) === "data:") {
  6137. fromData = true;
  6138. }
  6139. if (!fromData)
  6140. extension = url.substr(url.length - 4, 4).toLowerCase();
  6141. else {
  6142. var oldUrl = url;
  6143. fromData = oldUrl.split(':');
  6144. url = oldUrl;
  6145. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6146. }
  6147. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6148. var isTGA = (extension === ".tga");
  6149. scene._addPendingData(texture);
  6150. texture.url = url;
  6151. texture.noMipmap = noMipmap;
  6152. texture.references = 1;
  6153. texture.samplingMode = samplingMode;
  6154. this._loadedTexturesCache.push(texture);
  6155. var onerror = function () {
  6156. scene._removePendingData(texture);
  6157. if (onError) {
  6158. onError();
  6159. }
  6160. };
  6161. var callback;
  6162. if (isTGA) {
  6163. callback = function (arrayBuffer) {
  6164. var data = new Uint8Array(arrayBuffer);
  6165. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6166. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6167. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6168. if (onLoad) {
  6169. onLoad();
  6170. }
  6171. }, samplingMode);
  6172. };
  6173. if (!(fromData instanceof Array))
  6174. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6175. callback(arrayBuffer);
  6176. }, onerror, scene.database, true);
  6177. else
  6178. callback(buffer);
  6179. }
  6180. else if (isDDS) {
  6181. callback = function (data) {
  6182. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6183. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6184. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6185. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6186. if (onLoad) {
  6187. onLoad();
  6188. }
  6189. }, samplingMode);
  6190. };
  6191. if (!(fromData instanceof Array))
  6192. BABYLON.Tools.LoadFile(url, function (data) {
  6193. callback(data);
  6194. }, onerror, scene.database, true);
  6195. else
  6196. callback(buffer);
  6197. }
  6198. else {
  6199. var onload = function (img) {
  6200. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6201. var isPot = (img.width === potWidth && img.height === potHeight);
  6202. if (!isPot) {
  6203. _this._prepareWorkingCanvas();
  6204. _this._workingCanvas.width = potWidth;
  6205. _this._workingCanvas.height = potHeight;
  6206. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6207. _this._workingContext.imageSmoothingEnabled = false;
  6208. _this._workingContext.mozImageSmoothingEnabled = false;
  6209. _this._workingContext.oImageSmoothingEnabled = false;
  6210. _this._workingContext.webkitImageSmoothingEnabled = false;
  6211. _this._workingContext.msImageSmoothingEnabled = false;
  6212. }
  6213. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6214. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6215. _this._workingContext.imageSmoothingEnabled = true;
  6216. _this._workingContext.mozImageSmoothingEnabled = true;
  6217. _this._workingContext.oImageSmoothingEnabled = true;
  6218. _this._workingContext.webkitImageSmoothingEnabled = true;
  6219. _this._workingContext.msImageSmoothingEnabled = true;
  6220. }
  6221. }
  6222. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6223. if (onLoad) {
  6224. onLoad();
  6225. }
  6226. }, samplingMode);
  6227. };
  6228. if (!(fromData instanceof Array))
  6229. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6230. else
  6231. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6232. }
  6233. return texture;
  6234. };
  6235. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6236. if (compression === void 0) { compression = null; }
  6237. var internalFormat = this._gl.RGBA;
  6238. switch (format) {
  6239. case Engine.TEXTUREFORMAT_ALPHA:
  6240. internalFormat = this._gl.ALPHA;
  6241. break;
  6242. case Engine.TEXTUREFORMAT_LUMINANCE:
  6243. internalFormat = this._gl.LUMINANCE;
  6244. break;
  6245. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6246. internalFormat = this._gl.LUMINANCE_ALPHA;
  6247. break;
  6248. case Engine.TEXTUREFORMAT_RGB:
  6249. internalFormat = this._gl.RGB;
  6250. break;
  6251. case Engine.TEXTUREFORMAT_RGBA:
  6252. internalFormat = this._gl.RGBA;
  6253. break;
  6254. }
  6255. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6256. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6257. if (compression) {
  6258. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6259. }
  6260. else {
  6261. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6262. }
  6263. if (texture.generateMipMaps) {
  6264. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6265. }
  6266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6267. this.resetTextureCache();
  6268. texture.isReady = true;
  6269. };
  6270. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6271. if (compression === void 0) { compression = null; }
  6272. var texture = this._gl.createTexture();
  6273. texture._baseWidth = width;
  6274. texture._baseHeight = height;
  6275. texture._width = width;
  6276. texture._height = height;
  6277. texture.references = 1;
  6278. this.updateRawTexture(texture, data, format, invertY, compression);
  6279. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6280. // Filters
  6281. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6282. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6285. texture.samplingMode = samplingMode;
  6286. this._loadedTexturesCache.push(texture);
  6287. return texture;
  6288. };
  6289. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6290. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6291. var texture = this._gl.createTexture();
  6292. texture._baseWidth = width;
  6293. texture._baseHeight = height;
  6294. if (forceExponantOfTwo) {
  6295. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6296. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6297. }
  6298. this.resetTextureCache();
  6299. texture._width = width;
  6300. texture._height = height;
  6301. texture.isReady = false;
  6302. texture.generateMipMaps = generateMipMaps;
  6303. texture.references = 1;
  6304. texture.samplingMode = samplingMode;
  6305. this.updateTextureSamplingMode(samplingMode, texture);
  6306. this._loadedTexturesCache.push(texture);
  6307. return texture;
  6308. };
  6309. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6310. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6311. if (texture.isCube) {
  6312. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6315. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6316. }
  6317. else {
  6318. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6322. }
  6323. };
  6324. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6325. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6326. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6328. if (texture.generateMipMaps) {
  6329. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6330. }
  6331. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6332. this.resetTextureCache();
  6333. texture.isReady = true;
  6334. };
  6335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6336. if (texture._isDisabled) {
  6337. return;
  6338. }
  6339. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6341. try {
  6342. // Testing video texture support
  6343. if (this._videoTextureSupported === undefined) {
  6344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6345. if (this._gl.getError() !== 0) {
  6346. this._videoTextureSupported = false;
  6347. }
  6348. else {
  6349. this._videoTextureSupported = true;
  6350. }
  6351. }
  6352. // Copy video through the current working canvas if video texture is not supported
  6353. if (!this._videoTextureSupported) {
  6354. if (!texture._workingCanvas) {
  6355. texture._workingCanvas = document.createElement("canvas");
  6356. texture._workingContext = texture._workingCanvas.getContext("2d");
  6357. texture._workingCanvas.width = texture._width;
  6358. texture._workingCanvas.height = texture._height;
  6359. }
  6360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6362. }
  6363. else {
  6364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6365. }
  6366. if (texture.generateMipMaps) {
  6367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6368. }
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. this.resetTextureCache();
  6371. texture.isReady = true;
  6372. }
  6373. catch (ex) {
  6374. // Something unexpected
  6375. // Let's disable the texture
  6376. texture._isDisabled = true;
  6377. }
  6378. };
  6379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6380. // old version had a "generateMipMaps" arg instead of options.
  6381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6382. // in the same way, generateDepthBuffer is defaulted to true
  6383. var generateMipMaps = false;
  6384. var generateDepthBuffer = true;
  6385. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6386. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6387. if (options !== undefined) {
  6388. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6389. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6390. type = options.type === undefined ? type : options.type;
  6391. if (options.samplingMode !== undefined) {
  6392. samplingMode = options.samplingMode;
  6393. }
  6394. if (type === Engine.TEXTURETYPE_FLOAT) {
  6395. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6396. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6397. }
  6398. }
  6399. var gl = this._gl;
  6400. var texture = gl.createTexture();
  6401. gl.bindTexture(gl.TEXTURE_2D, texture);
  6402. var width = size.width || size;
  6403. var height = size.height || size;
  6404. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6405. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6406. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6407. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6408. }
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6414. var depthBuffer;
  6415. // Create the depth buffer
  6416. if (generateDepthBuffer) {
  6417. depthBuffer = gl.createRenderbuffer();
  6418. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6419. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6420. }
  6421. // Create the framebuffer
  6422. var framebuffer = gl.createFramebuffer();
  6423. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6424. if (generateDepthBuffer) {
  6425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6426. }
  6427. if (generateMipMaps) {
  6428. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6429. }
  6430. // Unbind
  6431. gl.bindTexture(gl.TEXTURE_2D, null);
  6432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6433. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6434. texture._framebuffer = framebuffer;
  6435. if (generateDepthBuffer) {
  6436. texture._depthBuffer = depthBuffer;
  6437. }
  6438. texture._width = width;
  6439. texture._height = height;
  6440. texture.isReady = true;
  6441. texture.generateMipMaps = generateMipMaps;
  6442. texture.references = 1;
  6443. texture.samplingMode = samplingMode;
  6444. this.resetTextureCache();
  6445. this._loadedTexturesCache.push(texture);
  6446. return texture;
  6447. };
  6448. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6449. var gl = this._gl;
  6450. var texture = gl.createTexture();
  6451. var generateMipMaps = true;
  6452. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6453. if (options !== undefined) {
  6454. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6455. if (options.samplingMode !== undefined) {
  6456. samplingMode = options.samplingMode;
  6457. }
  6458. }
  6459. texture.isCube = true;
  6460. texture.references = 1;
  6461. texture.generateMipMaps = generateMipMaps;
  6462. texture.references = 1;
  6463. texture.samplingMode = samplingMode;
  6464. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6465. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6466. for (var face = 0; face < 6; face++) {
  6467. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6468. }
  6469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6473. // Create the depth buffer
  6474. var depthBuffer = gl.createRenderbuffer();
  6475. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6476. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6477. // Create the framebuffer
  6478. var framebuffer = gl.createFramebuffer();
  6479. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6480. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6481. // mipmaps
  6482. if (texture.generateMipMaps) {
  6483. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6484. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6485. }
  6486. // Unbind
  6487. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6489. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6490. texture._framebuffer = framebuffer;
  6491. texture._depthBuffer = depthBuffer;
  6492. this.resetTextureCache();
  6493. texture._width = size;
  6494. texture._height = size;
  6495. texture.isReady = true;
  6496. return texture;
  6497. };
  6498. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6499. var _this = this;
  6500. var gl = this._gl;
  6501. var texture = gl.createTexture();
  6502. texture.isCube = true;
  6503. texture.url = rootUrl;
  6504. texture.references = 1;
  6505. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6506. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6507. if (isDDS) {
  6508. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6509. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6510. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6511. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6512. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6513. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6514. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6515. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6516. }
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6522. _this.resetTextureCache();
  6523. texture._width = info.width;
  6524. texture._height = info.height;
  6525. texture.isReady = true;
  6526. }, null, null, true);
  6527. }
  6528. else {
  6529. cascadeLoad(rootUrl, scene, function (imgs) {
  6530. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6531. var height = width;
  6532. _this._prepareWorkingCanvas();
  6533. _this._workingCanvas.width = width;
  6534. _this._workingCanvas.height = height;
  6535. var faces = [
  6536. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6537. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6538. ];
  6539. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6540. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6541. for (var index = 0; index < faces.length; index++) {
  6542. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6543. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6544. }
  6545. if (!noMipmap) {
  6546. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6547. }
  6548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6552. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6553. _this.resetTextureCache();
  6554. texture._width = width;
  6555. texture._height = height;
  6556. texture.isReady = true;
  6557. }, extensions);
  6558. }
  6559. return texture;
  6560. };
  6561. Engine.prototype._releaseTexture = function (texture) {
  6562. var gl = this._gl;
  6563. if (texture._framebuffer) {
  6564. gl.deleteFramebuffer(texture._framebuffer);
  6565. }
  6566. if (texture._depthBuffer) {
  6567. gl.deleteRenderbuffer(texture._depthBuffer);
  6568. }
  6569. gl.deleteTexture(texture);
  6570. // Unbind channels
  6571. this.unbindAllTextures();
  6572. var index = this._loadedTexturesCache.indexOf(texture);
  6573. if (index !== -1) {
  6574. this._loadedTexturesCache.splice(index, 1);
  6575. }
  6576. };
  6577. Engine.prototype.bindSamplers = function (effect) {
  6578. this._gl.useProgram(effect.getProgram());
  6579. var samplers = effect.getSamplers();
  6580. for (var index = 0; index < samplers.length; index++) {
  6581. var uniform = effect.getUniform(samplers[index]);
  6582. this._gl.uniform1i(uniform, index);
  6583. }
  6584. this._currentEffect = null;
  6585. };
  6586. Engine.prototype._bindTexture = function (channel, texture) {
  6587. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6588. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6589. this._activeTexturesCache[channel] = null;
  6590. };
  6591. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6592. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6593. };
  6594. Engine.prototype.unbindAllTextures = function () {
  6595. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6596. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6598. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6599. this._activeTexturesCache[channel] = null;
  6600. }
  6601. };
  6602. Engine.prototype.setTexture = function (channel, texture) {
  6603. if (channel < 0) {
  6604. return;
  6605. }
  6606. // Not ready?
  6607. if (!texture || !texture.isReady()) {
  6608. if (this._activeTexturesCache[channel] != null) {
  6609. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6610. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6611. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6612. this._activeTexturesCache[channel] = null;
  6613. }
  6614. return;
  6615. }
  6616. // Video
  6617. var alreadyActivated = false;
  6618. if (texture instanceof BABYLON.VideoTexture) {
  6619. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6620. alreadyActivated = true;
  6621. texture.update();
  6622. }
  6623. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6624. texture.delayLoad();
  6625. return;
  6626. }
  6627. if (this._activeTexturesCache[channel] === texture) {
  6628. return;
  6629. }
  6630. this._activeTexturesCache[channel] = texture;
  6631. var internalTexture = texture.getInternalTexture();
  6632. if (!alreadyActivated) {
  6633. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6634. }
  6635. if (internalTexture.isCube) {
  6636. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6637. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6638. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6639. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6640. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6641. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6642. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6643. }
  6644. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6645. }
  6646. else {
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6648. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6649. internalTexture._cachedWrapU = texture.wrapU;
  6650. switch (texture.wrapU) {
  6651. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6653. break;
  6654. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6655. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6656. break;
  6657. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6658. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6659. break;
  6660. }
  6661. }
  6662. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6663. internalTexture._cachedWrapV = texture.wrapV;
  6664. switch (texture.wrapV) {
  6665. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6667. break;
  6668. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6670. break;
  6671. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6673. break;
  6674. }
  6675. }
  6676. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6677. }
  6678. };
  6679. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6681. var value = texture.anisotropicFilteringLevel;
  6682. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6683. value = 1;
  6684. }
  6685. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6686. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6687. texture._cachedAnisotropicFilteringLevel = value;
  6688. }
  6689. };
  6690. Engine.prototype.readPixels = function (x, y, width, height) {
  6691. var data = new Uint8Array(height * width * 4);
  6692. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6693. return data;
  6694. };
  6695. Engine.prototype.releaseInternalTexture = function (texture) {
  6696. if (!texture) {
  6697. return;
  6698. }
  6699. texture.references--;
  6700. // Final reference ?
  6701. if (texture.references === 0) {
  6702. var texturesCache = this.getLoadedTexturesCache();
  6703. var index = texturesCache.indexOf(texture);
  6704. if (index > -1) {
  6705. texturesCache.splice(index, 1);
  6706. }
  6707. this._releaseTexture(texture);
  6708. }
  6709. };
  6710. // Dispose
  6711. Engine.prototype.dispose = function () {
  6712. this.hideLoadingUI();
  6713. this.stopRenderLoop();
  6714. // Release scenes
  6715. while (this.scenes.length) {
  6716. this.scenes[0].dispose();
  6717. }
  6718. // Release audio engine
  6719. Engine.audioEngine.dispose();
  6720. // Release effects
  6721. for (var name in this._compiledEffects) {
  6722. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6723. }
  6724. // Unbind
  6725. for (var i in this._vertexAttribArrays) {
  6726. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6727. continue;
  6728. }
  6729. this._gl.disableVertexAttribArray(i);
  6730. }
  6731. this._gl = null;
  6732. // Events
  6733. window.removeEventListener("blur", this._onBlur);
  6734. window.removeEventListener("focus", this._onFocus);
  6735. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6736. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6737. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6738. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6739. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6740. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6741. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6742. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6743. };
  6744. // Loading screen
  6745. Engine.prototype.displayLoadingUI = function () {
  6746. this._loadingScreen.displayLoadingUI();
  6747. };
  6748. Engine.prototype.hideLoadingUI = function () {
  6749. this._loadingScreen.hideLoadingUI();
  6750. };
  6751. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6752. get: function () {
  6753. return this._loadingScreen;
  6754. },
  6755. set: function (loadingScreen) {
  6756. this._loadingScreen = loadingScreen;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6762. set: function (text) {
  6763. this._loadingScreen.loadingUIText = text;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6769. set: function (color) {
  6770. this._loadingScreen.loadingUIBackgroundColor = color;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. // FPS
  6776. Engine.prototype.getFps = function () {
  6777. return this.fps;
  6778. };
  6779. Engine.prototype.getDeltaTime = function () {
  6780. return this.deltaTime;
  6781. };
  6782. Engine.prototype._measureFps = function () {
  6783. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6784. var length = this.previousFramesDuration.length;
  6785. if (length >= 2) {
  6786. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6787. }
  6788. if (length >= this.fpsRange) {
  6789. if (length > this.fpsRange) {
  6790. this.previousFramesDuration.splice(0, 1);
  6791. length = this.previousFramesDuration.length;
  6792. }
  6793. var sum = 0;
  6794. for (var id = 0; id < length - 1; id++) {
  6795. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6796. }
  6797. this.fps = 1000.0 / (sum / (length - 1));
  6798. }
  6799. };
  6800. // Statics
  6801. Engine.isSupported = function () {
  6802. try {
  6803. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6804. if (navigator.isCocoonJS) {
  6805. return true;
  6806. }
  6807. var tempcanvas = document.createElement("canvas");
  6808. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6809. return gl != null && !!window.WebGLRenderingContext;
  6810. }
  6811. catch (e) {
  6812. return false;
  6813. }
  6814. };
  6815. // Const statics
  6816. Engine._ALPHA_DISABLE = 0;
  6817. Engine._ALPHA_ADD = 1;
  6818. Engine._ALPHA_COMBINE = 2;
  6819. Engine._ALPHA_SUBTRACT = 3;
  6820. Engine._ALPHA_MULTIPLY = 4;
  6821. Engine._ALPHA_MAXIMIZED = 5;
  6822. Engine._ALPHA_ONEONE = 6;
  6823. Engine._DELAYLOADSTATE_NONE = 0;
  6824. Engine._DELAYLOADSTATE_LOADED = 1;
  6825. Engine._DELAYLOADSTATE_LOADING = 2;
  6826. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6827. Engine._TEXTUREFORMAT_ALPHA = 0;
  6828. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6829. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6830. Engine._TEXTUREFORMAT_RGB = 4;
  6831. Engine._TEXTUREFORMAT_RGBA = 5;
  6832. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6833. Engine._TEXTURETYPE_FLOAT = 1;
  6834. // Updatable statics so stick with vars here
  6835. Engine.Epsilon = 0.001;
  6836. Engine.CollisionsEpsilon = 0.001;
  6837. Engine.CodeRepository = "src/";
  6838. Engine.ShadersRepository = "src/Shaders/";
  6839. return Engine;
  6840. })();
  6841. BABYLON.Engine = Engine;
  6842. })(BABYLON || (BABYLON = {}));
  6843. var BABYLON;
  6844. (function (BABYLON) {
  6845. /**
  6846. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6847. */
  6848. var Node = (function () {
  6849. /**
  6850. * @constructor
  6851. * @param {string} name - the name and id to be given to this node
  6852. * @param {BABYLON.Scene} the scene this node will be added to
  6853. */
  6854. function Node(name, scene) {
  6855. this.state = "";
  6856. this.animations = new Array();
  6857. this._childrenFlag = -1;
  6858. this._isEnabled = true;
  6859. this._isReady = true;
  6860. this._currentRenderId = -1;
  6861. this._parentRenderId = -1;
  6862. this.name = name;
  6863. this.id = name;
  6864. this._scene = scene;
  6865. this._initCache();
  6866. }
  6867. Node.prototype.getScene = function () {
  6868. return this._scene;
  6869. };
  6870. Node.prototype.getEngine = function () {
  6871. return this._scene.getEngine();
  6872. };
  6873. // override it in derived class
  6874. Node.prototype.getWorldMatrix = function () {
  6875. return BABYLON.Matrix.Identity();
  6876. };
  6877. // override it in derived class if you add new variables to the cache
  6878. // and call the parent class method
  6879. Node.prototype._initCache = function () {
  6880. this._cache = {};
  6881. this._cache.parent = undefined;
  6882. };
  6883. Node.prototype.updateCache = function (force) {
  6884. if (!force && this.isSynchronized())
  6885. return;
  6886. this._cache.parent = this.parent;
  6887. this._updateCache();
  6888. };
  6889. // override it in derived class if you add new variables to the cache
  6890. // and call the parent class method if !ignoreParentClass
  6891. Node.prototype._updateCache = function (ignoreParentClass) {
  6892. };
  6893. // override it in derived class if you add new variables to the cache
  6894. Node.prototype._isSynchronized = function () {
  6895. return true;
  6896. };
  6897. Node.prototype._markSyncedWithParent = function () {
  6898. this._parentRenderId = this.parent._currentRenderId;
  6899. };
  6900. Node.prototype.isSynchronizedWithParent = function () {
  6901. if (!this.parent) {
  6902. return true;
  6903. }
  6904. if (this._parentRenderId !== this.parent._currentRenderId) {
  6905. return false;
  6906. }
  6907. return this.parent.isSynchronized();
  6908. };
  6909. Node.prototype.isSynchronized = function (updateCache) {
  6910. var check = this.hasNewParent();
  6911. check = check || !this.isSynchronizedWithParent();
  6912. check = check || !this._isSynchronized();
  6913. if (updateCache)
  6914. this.updateCache(true);
  6915. return !check;
  6916. };
  6917. Node.prototype.hasNewParent = function (update) {
  6918. if (this._cache.parent === this.parent)
  6919. return false;
  6920. if (update)
  6921. this._cache.parent = this.parent;
  6922. return true;
  6923. };
  6924. /**
  6925. * Is this node ready to be used/rendered
  6926. * @return {boolean} is it ready
  6927. */
  6928. Node.prototype.isReady = function () {
  6929. return this._isReady;
  6930. };
  6931. /**
  6932. * Is this node enabled.
  6933. * If the node has a parent and is enabled, the parent will be inspected as well.
  6934. * @return {boolean} whether this node (and its parent) is enabled.
  6935. * @see setEnabled
  6936. */
  6937. Node.prototype.isEnabled = function () {
  6938. if (!this._isEnabled) {
  6939. return false;
  6940. }
  6941. if (this.parent) {
  6942. return this.parent.isEnabled();
  6943. }
  6944. return true;
  6945. };
  6946. /**
  6947. * Set the enabled state of this node.
  6948. * @param {boolean} value - the new enabled state
  6949. * @see isEnabled
  6950. */
  6951. Node.prototype.setEnabled = function (value) {
  6952. this._isEnabled = value;
  6953. };
  6954. /**
  6955. * Is this node a descendant of the given node.
  6956. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6957. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6958. * @see parent
  6959. */
  6960. Node.prototype.isDescendantOf = function (ancestor) {
  6961. if (this.parent) {
  6962. if (this.parent === ancestor) {
  6963. return true;
  6964. }
  6965. return this.parent.isDescendantOf(ancestor);
  6966. }
  6967. return false;
  6968. };
  6969. Node.prototype._getDescendants = function (list, results) {
  6970. for (var index = 0; index < list.length; index++) {
  6971. var item = list[index];
  6972. if (item.isDescendantOf(this)) {
  6973. results.push(item);
  6974. }
  6975. }
  6976. };
  6977. /**
  6978. * Will return all nodes that have this node as parent.
  6979. * @return {BABYLON.Node[]} all children nodes of all types.
  6980. */
  6981. Node.prototype.getDescendants = function () {
  6982. var results = [];
  6983. this._getDescendants(this._scene.meshes, results);
  6984. this._getDescendants(this._scene.lights, results);
  6985. this._getDescendants(this._scene.cameras, results);
  6986. return results;
  6987. };
  6988. Node.prototype._setReady = function (state) {
  6989. if (state === this._isReady) {
  6990. return;
  6991. }
  6992. if (!state) {
  6993. this._isReady = false;
  6994. return;
  6995. }
  6996. this._isReady = true;
  6997. if (this.onReady) {
  6998. this.onReady(this);
  6999. }
  7000. };
  7001. Node.prototype.getAnimationByName = function (name) {
  7002. for (var i = 0; i < this.animations.length; i++) {
  7003. var animation = this.animations[i];
  7004. if (animation.name === name) {
  7005. return animation;
  7006. }
  7007. }
  7008. return null;
  7009. };
  7010. return Node;
  7011. })();
  7012. BABYLON.Node = Node;
  7013. })(BABYLON || (BABYLON = {}));
  7014. var BABYLON;
  7015. (function (BABYLON) {
  7016. var FilesInput = (function () {
  7017. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7018. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7019. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7020. this._engine = p_engine;
  7021. this._canvas = p_canvas;
  7022. this._currentScene = p_scene;
  7023. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7024. this._progressCallback = p_progressCallback;
  7025. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7026. this._textureLoadingCallback = p_textureLoadingCallback;
  7027. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7028. }
  7029. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7030. var _this = this;
  7031. if (p_elementToMonitor) {
  7032. this._elementToMonitor = p_elementToMonitor;
  7033. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7034. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7035. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7036. }
  7037. };
  7038. FilesInput.prototype.renderFunction = function () {
  7039. if (this._additionnalRenderLoopLogicCallback) {
  7040. this._additionnalRenderLoopLogicCallback();
  7041. }
  7042. if (this._currentScene) {
  7043. if (this._textureLoadingCallback) {
  7044. var remaining = this._currentScene.getWaitingItemsCount();
  7045. if (remaining > 0) {
  7046. this._textureLoadingCallback(remaining);
  7047. }
  7048. }
  7049. this._currentScene.render();
  7050. }
  7051. };
  7052. FilesInput.prototype.drag = function (e) {
  7053. e.stopPropagation();
  7054. e.preventDefault();
  7055. };
  7056. FilesInput.prototype.drop = function (eventDrop) {
  7057. eventDrop.stopPropagation();
  7058. eventDrop.preventDefault();
  7059. this.loadFiles(eventDrop);
  7060. };
  7061. FilesInput.prototype.loadFiles = function (event) {
  7062. if (this._startingProcessingFilesCallback)
  7063. this._startingProcessingFilesCallback();
  7064. // Handling data transfer via drag'n'drop
  7065. if (event && event.dataTransfer && event.dataTransfer.files) {
  7066. this._filesToLoad = event.dataTransfer.files;
  7067. }
  7068. // Handling files from input files
  7069. if (event && event.target && event.target.files) {
  7070. this._filesToLoad = event.target.files;
  7071. }
  7072. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7073. for (var i = 0; i < this._filesToLoad.length; i++) {
  7074. switch (this._filesToLoad[i].type) {
  7075. case "image/jpeg":
  7076. case "image/png":
  7077. case "image/bmp":
  7078. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7079. break;
  7080. case "image/targa":
  7081. case "image/vnd.ms-dds":
  7082. case "audio/wav":
  7083. case "audio/x-wav":
  7084. case "audio/mp3":
  7085. case "audio/mpeg":
  7086. case "audio/mpeg3":
  7087. case "audio/x-mpeg-3":
  7088. case "audio/ogg":
  7089. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7090. break;
  7091. default:
  7092. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7093. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7094. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7095. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7096. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7097. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7098. this._sceneFileToLoad = this._filesToLoad[i];
  7099. }
  7100. break;
  7101. }
  7102. }
  7103. this.reload();
  7104. }
  7105. };
  7106. FilesInput.prototype.reload = function () {
  7107. var _this = this;
  7108. var that = this;
  7109. // If a ".babylon" file has been provided
  7110. if (this._sceneFileToLoad) {
  7111. if (this._currentScene) {
  7112. if (BABYLON.Tools.errorsCount > 0) {
  7113. BABYLON.Tools.ClearLogCache();
  7114. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7115. }
  7116. this._engine.stopRenderLoop();
  7117. this._currentScene.dispose();
  7118. }
  7119. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7120. that._currentScene = newScene;
  7121. // Wait for textures and shaders to be ready
  7122. that._currentScene.executeWhenReady(function () {
  7123. // Attach camera to canvas inputs
  7124. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7125. that._currentScene.createDefaultCameraOrLight();
  7126. }
  7127. that._currentScene.activeCamera.attachControl(that._canvas);
  7128. if (that._sceneLoadedCallback) {
  7129. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7130. }
  7131. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7132. });
  7133. }, function (progress) {
  7134. if (_this._progressCallback) {
  7135. _this._progressCallback(progress);
  7136. }
  7137. });
  7138. }
  7139. else {
  7140. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7141. }
  7142. };
  7143. FilesInput.FilesTextures = new Array();
  7144. FilesInput.FilesToLoad = new Array();
  7145. return FilesInput;
  7146. })();
  7147. BABYLON.FilesInput = FilesInput;
  7148. })(BABYLON || (BABYLON = {}));
  7149. var BABYLON;
  7150. (function (BABYLON) {
  7151. var IntersectionInfo = (function () {
  7152. function IntersectionInfo(bu, bv, distance) {
  7153. this.bu = bu;
  7154. this.bv = bv;
  7155. this.distance = distance;
  7156. this.faceId = 0;
  7157. this.subMeshId = 0;
  7158. }
  7159. return IntersectionInfo;
  7160. })();
  7161. BABYLON.IntersectionInfo = IntersectionInfo;
  7162. var PickingInfo = (function () {
  7163. function PickingInfo() {
  7164. this.hit = false;
  7165. this.distance = 0;
  7166. this.pickedPoint = null;
  7167. this.pickedMesh = null;
  7168. this.bu = 0;
  7169. this.bv = 0;
  7170. this.faceId = -1;
  7171. this.subMeshId = 0;
  7172. this.pickedSprite = null;
  7173. }
  7174. // Methods
  7175. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7176. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7177. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7178. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7179. return null;
  7180. }
  7181. var indices = this.pickedMesh.getIndices();
  7182. var result;
  7183. if (useVerticesNormals) {
  7184. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7185. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7186. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7187. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7188. normal0 = normal0.scale(this.bu);
  7189. normal1 = normal1.scale(this.bv);
  7190. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7191. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7192. }
  7193. else {
  7194. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7195. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7196. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7197. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7198. var p1p2 = vertex1.subtract(vertex2);
  7199. var p3p2 = vertex3.subtract(vertex2);
  7200. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7201. }
  7202. if (useWorldCoordinates) {
  7203. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7204. }
  7205. return BABYLON.Vector3.Normalize(result);
  7206. };
  7207. PickingInfo.prototype.getTextureCoordinates = function () {
  7208. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7209. return null;
  7210. }
  7211. var indices = this.pickedMesh.getIndices();
  7212. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7213. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7214. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7215. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7216. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7217. uv1 = uv1.scale(this.bu);
  7218. uv2 = uv2.scale(this.bv);
  7219. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7220. };
  7221. return PickingInfo;
  7222. })();
  7223. BABYLON.PickingInfo = PickingInfo;
  7224. })(BABYLON || (BABYLON = {}));
  7225. var BABYLON;
  7226. (function (BABYLON) {
  7227. var BoundingSphere = (function () {
  7228. function BoundingSphere(minimum, maximum) {
  7229. this.minimum = minimum;
  7230. this.maximum = maximum;
  7231. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7232. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7233. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7234. this.radius = distance * 0.5;
  7235. this.centerWorld = BABYLON.Vector3.Zero();
  7236. this._update(BABYLON.Matrix.Identity());
  7237. }
  7238. // Methods
  7239. BoundingSphere.prototype._update = function (world) {
  7240. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7241. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7242. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7243. };
  7244. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7245. for (var i = 0; i < 6; i++) {
  7246. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7247. return false;
  7248. }
  7249. return true;
  7250. };
  7251. BoundingSphere.prototype.intersectsPoint = function (point) {
  7252. var x = this.centerWorld.x - point.x;
  7253. var y = this.centerWorld.y - point.y;
  7254. var z = this.centerWorld.z - point.z;
  7255. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7256. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7257. return false;
  7258. return true;
  7259. };
  7260. // Statics
  7261. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7262. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7263. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7264. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7266. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7267. return false;
  7268. return true;
  7269. };
  7270. return BoundingSphere;
  7271. })();
  7272. BABYLON.BoundingSphere = BoundingSphere;
  7273. })(BABYLON || (BABYLON = {}));
  7274. var BABYLON;
  7275. (function (BABYLON) {
  7276. var BoundingBox = (function () {
  7277. function BoundingBox(minimum, maximum) {
  7278. this.minimum = minimum;
  7279. this.maximum = maximum;
  7280. this.vectors = new Array();
  7281. this.vectorsWorld = new Array();
  7282. // Bounding vectors
  7283. this.vectors.push(this.minimum.clone());
  7284. this.vectors.push(this.maximum.clone());
  7285. this.vectors.push(this.minimum.clone());
  7286. this.vectors[2].x = this.maximum.x;
  7287. this.vectors.push(this.minimum.clone());
  7288. this.vectors[3].y = this.maximum.y;
  7289. this.vectors.push(this.minimum.clone());
  7290. this.vectors[4].z = this.maximum.z;
  7291. this.vectors.push(this.maximum.clone());
  7292. this.vectors[5].z = this.minimum.z;
  7293. this.vectors.push(this.maximum.clone());
  7294. this.vectors[6].x = this.minimum.x;
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors[7].y = this.minimum.y;
  7297. // OBB
  7298. this.center = this.maximum.add(this.minimum).scale(0.5);
  7299. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7300. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7301. // World
  7302. for (var index = 0; index < this.vectors.length; index++) {
  7303. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7304. }
  7305. this.minimumWorld = BABYLON.Vector3.Zero();
  7306. this.maximumWorld = BABYLON.Vector3.Zero();
  7307. this._update(BABYLON.Matrix.Identity());
  7308. }
  7309. // Methods
  7310. BoundingBox.prototype.getWorldMatrix = function () {
  7311. return this._worldMatrix;
  7312. };
  7313. BoundingBox.prototype._update = function (world) {
  7314. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7315. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7316. for (var index = 0; index < this.vectors.length; index++) {
  7317. var v = this.vectorsWorld[index];
  7318. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7319. if (v.x < this.minimumWorld.x)
  7320. this.minimumWorld.x = v.x;
  7321. if (v.y < this.minimumWorld.y)
  7322. this.minimumWorld.y = v.y;
  7323. if (v.z < this.minimumWorld.z)
  7324. this.minimumWorld.z = v.z;
  7325. if (v.x > this.maximumWorld.x)
  7326. this.maximumWorld.x = v.x;
  7327. if (v.y > this.maximumWorld.y)
  7328. this.maximumWorld.y = v.y;
  7329. if (v.z > this.maximumWorld.z)
  7330. this.maximumWorld.z = v.z;
  7331. }
  7332. // OBB
  7333. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7334. this.center.scaleInPlace(0.5);
  7335. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7336. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7337. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7338. this._worldMatrix = world;
  7339. };
  7340. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7341. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7342. };
  7343. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7344. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7345. };
  7346. BoundingBox.prototype.intersectsPoint = function (point) {
  7347. var delta = -BABYLON.Engine.Epsilon;
  7348. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7349. return false;
  7350. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7351. return false;
  7352. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7353. return false;
  7354. return true;
  7355. };
  7356. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7357. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7358. };
  7359. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7360. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7361. return false;
  7362. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7363. return false;
  7364. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7365. return false;
  7366. return true;
  7367. };
  7368. // Statics
  7369. BoundingBox.Intersects = function (box0, box1) {
  7370. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7371. return false;
  7372. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7373. return false;
  7374. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7375. return false;
  7376. return true;
  7377. };
  7378. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7379. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7380. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7381. return (num <= (sphereRadius * sphereRadius));
  7382. };
  7383. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7384. for (var p = 0; p < 6; p++) {
  7385. for (var i = 0; i < 8; i++) {
  7386. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7387. return false;
  7388. }
  7389. }
  7390. }
  7391. return true;
  7392. };
  7393. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7394. for (var p = 0; p < 6; p++) {
  7395. var inCount = 8;
  7396. for (var i = 0; i < 8; i++) {
  7397. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7398. --inCount;
  7399. }
  7400. else {
  7401. break;
  7402. }
  7403. }
  7404. if (inCount === 0)
  7405. return false;
  7406. }
  7407. return true;
  7408. };
  7409. return BoundingBox;
  7410. })();
  7411. BABYLON.BoundingBox = BoundingBox;
  7412. })(BABYLON || (BABYLON = {}));
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var computeBoxExtents = function (axis, box) {
  7416. var p = BABYLON.Vector3.Dot(box.center, axis);
  7417. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7418. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7419. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7420. var r = r0 + r1 + r2;
  7421. return {
  7422. min: p - r,
  7423. max: p + r
  7424. };
  7425. };
  7426. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7427. var axisOverlap = function (axis, box0, box1) {
  7428. var result0 = computeBoxExtents(axis, box0);
  7429. var result1 = computeBoxExtents(axis, box1);
  7430. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7431. };
  7432. var BoundingInfo = (function () {
  7433. function BoundingInfo(minimum, maximum) {
  7434. this.minimum = minimum;
  7435. this.maximum = maximum;
  7436. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7437. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7438. }
  7439. // Methods
  7440. BoundingInfo.prototype._update = function (world) {
  7441. this.boundingBox._update(world);
  7442. this.boundingSphere._update(world);
  7443. };
  7444. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7445. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7446. return false;
  7447. return this.boundingBox.isInFrustum(frustumPlanes);
  7448. };
  7449. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7450. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7451. };
  7452. BoundingInfo.prototype._checkCollision = function (collider) {
  7453. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7454. };
  7455. BoundingInfo.prototype.intersectsPoint = function (point) {
  7456. if (!this.boundingSphere.centerWorld) {
  7457. return false;
  7458. }
  7459. if (!this.boundingSphere.intersectsPoint(point)) {
  7460. return false;
  7461. }
  7462. if (!this.boundingBox.intersectsPoint(point)) {
  7463. return false;
  7464. }
  7465. return true;
  7466. };
  7467. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7468. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7472. return false;
  7473. }
  7474. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7475. return false;
  7476. }
  7477. if (!precise) {
  7478. return true;
  7479. }
  7480. var box0 = this.boundingBox;
  7481. var box1 = boundingInfo.boundingBox;
  7482. if (!axisOverlap(box0.directions[0], box0, box1))
  7483. return false;
  7484. if (!axisOverlap(box0.directions[1], box0, box1))
  7485. return false;
  7486. if (!axisOverlap(box0.directions[2], box0, box1))
  7487. return false;
  7488. if (!axisOverlap(box1.directions[0], box0, box1))
  7489. return false;
  7490. if (!axisOverlap(box1.directions[1], box0, box1))
  7491. return false;
  7492. if (!axisOverlap(box1.directions[2], box0, box1))
  7493. return false;
  7494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7495. return false;
  7496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7497. return false;
  7498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7499. return false;
  7500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7501. return false;
  7502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7503. return false;
  7504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7511. return false;
  7512. return true;
  7513. };
  7514. return BoundingInfo;
  7515. })();
  7516. BABYLON.BoundingInfo = BoundingInfo;
  7517. })(BABYLON || (BABYLON = {}));
  7518. var BABYLON;
  7519. (function (BABYLON) {
  7520. var AbstractMesh = (function (_super) {
  7521. __extends(AbstractMesh, _super);
  7522. function AbstractMesh(name, scene) {
  7523. var _this = this;
  7524. _super.call(this, name, scene);
  7525. // Properties
  7526. this.definedFacingForward = true; // orientation for POV movement & rotation
  7527. this.position = new BABYLON.Vector3(0, 0, 0);
  7528. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7529. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7530. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7531. this.visibility = 1.0;
  7532. this.alphaIndex = Number.MAX_VALUE;
  7533. this.infiniteDistance = false;
  7534. this.isVisible = true;
  7535. this.isPickable = true;
  7536. this.showBoundingBox = false;
  7537. this.showSubMeshesBoundingBox = false;
  7538. this.onDispose = null;
  7539. this.isBlocker = false;
  7540. this.renderingGroupId = 0;
  7541. this.receiveShadows = false;
  7542. this.renderOutline = false;
  7543. this.outlineColor = BABYLON.Color3.Red();
  7544. this.outlineWidth = 0.02;
  7545. this.renderOverlay = false;
  7546. this.overlayColor = BABYLON.Color3.Red();
  7547. this.overlayAlpha = 0.5;
  7548. this.hasVertexAlpha = false;
  7549. this.useVertexColors = true;
  7550. this.applyFog = true;
  7551. this.computeBonesUsingShaders = true;
  7552. this.scalingDeterminant = 1;
  7553. this.numBoneInfluencers = 4;
  7554. this.useOctreeForRenderingSelection = true;
  7555. this.useOctreeForPicking = true;
  7556. this.useOctreeForCollisions = true;
  7557. this.layerMask = 0x0FFFFFFF;
  7558. this.alwaysSelectAsActiveMesh = false;
  7559. // Physics
  7560. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7561. // Collisions
  7562. this._checkCollisions = false;
  7563. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7564. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7565. this._collider = new BABYLON.Collider();
  7566. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7567. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7568. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7569. // Edges
  7570. this.edgesWidth = 1;
  7571. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7572. // Cache
  7573. this._localScaling = BABYLON.Matrix.Zero();
  7574. this._localRotation = BABYLON.Matrix.Zero();
  7575. this._localTranslation = BABYLON.Matrix.Zero();
  7576. this._localBillboard = BABYLON.Matrix.Zero();
  7577. this._localPivotScaling = BABYLON.Matrix.Zero();
  7578. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7579. this._localWorld = BABYLON.Matrix.Zero();
  7580. this._worldMatrix = BABYLON.Matrix.Zero();
  7581. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7582. this._absolutePosition = BABYLON.Vector3.Zero();
  7583. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7584. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7585. this._isDirty = false;
  7586. this._pivotMatrix = BABYLON.Matrix.Identity();
  7587. this._isDisposed = false;
  7588. this._renderId = 0;
  7589. this._intersectionsInProgress = new Array();
  7590. this._onAfterWorldMatrixUpdate = new Array();
  7591. this._isWorldMatrixFrozen = false;
  7592. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7593. if (collidedMesh === void 0) { collidedMesh = null; }
  7594. //TODO move this to the collision coordinator!
  7595. if (_this.getScene().workerCollisions)
  7596. newPosition.multiplyInPlace(_this._collider.radius);
  7597. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7598. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7599. _this.position.addInPlace(_this._diffPositionForCollisions);
  7600. }
  7601. if (_this.onCollide && collidedMesh) {
  7602. _this.onCollide(collidedMesh);
  7603. }
  7604. if (_this.onCollisionPositionChange) {
  7605. _this.onCollisionPositionChange(_this.position);
  7606. }
  7607. };
  7608. scene.addMesh(this);
  7609. }
  7610. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7611. get: function () {
  7612. return AbstractMesh._BILLBOARDMODE_NONE;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7618. get: function () {
  7619. return AbstractMesh._BILLBOARDMODE_X;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7625. get: function () {
  7626. return AbstractMesh._BILLBOARDMODE_Y;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7632. get: function () {
  7633. return AbstractMesh._BILLBOARDMODE_Z;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7639. get: function () {
  7640. return AbstractMesh._BILLBOARDMODE_ALL;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. // Methods
  7646. AbstractMesh.prototype.disableEdgesRendering = function () {
  7647. if (this._edgesRenderer !== undefined) {
  7648. this._edgesRenderer.dispose();
  7649. this._edgesRenderer = undefined;
  7650. }
  7651. };
  7652. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7653. if (epsilon === void 0) { epsilon = 0.95; }
  7654. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7655. this.disableEdgesRendering();
  7656. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7657. };
  7658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7659. get: function () {
  7660. return false;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. AbstractMesh.prototype.getLOD = function (camera) {
  7666. return this;
  7667. };
  7668. AbstractMesh.prototype.getTotalVertices = function () {
  7669. return 0;
  7670. };
  7671. AbstractMesh.prototype.getIndices = function () {
  7672. return null;
  7673. };
  7674. AbstractMesh.prototype.getVerticesData = function (kind) {
  7675. return null;
  7676. };
  7677. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7678. return false;
  7679. };
  7680. AbstractMesh.prototype.getBoundingInfo = function () {
  7681. if (this._masterMesh) {
  7682. return this._masterMesh.getBoundingInfo();
  7683. }
  7684. if (!this._boundingInfo) {
  7685. this._updateBoundingInfo();
  7686. }
  7687. return this._boundingInfo;
  7688. };
  7689. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7690. get: function () {
  7691. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. AbstractMesh.prototype._preActivate = function () {
  7697. };
  7698. AbstractMesh.prototype._activate = function (renderId) {
  7699. this._renderId = renderId;
  7700. };
  7701. AbstractMesh.prototype.getWorldMatrix = function () {
  7702. if (this._masterMesh) {
  7703. return this._masterMesh.getWorldMatrix();
  7704. }
  7705. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7706. this.computeWorldMatrix();
  7707. }
  7708. return this._worldMatrix;
  7709. };
  7710. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7711. get: function () {
  7712. return this._worldMatrix;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7718. get: function () {
  7719. return this._absolutePosition;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7725. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7726. this.computeWorldMatrix(true);
  7727. this._isWorldMatrixFrozen = true;
  7728. };
  7729. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7730. this._isWorldMatrixFrozen = false;
  7731. this.computeWorldMatrix(true);
  7732. };
  7733. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7734. get: function () {
  7735. return this._isWorldMatrixFrozen;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7741. axis.normalize();
  7742. if (!this.rotationQuaternion) {
  7743. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7744. this.rotation = BABYLON.Vector3.Zero();
  7745. }
  7746. var rotationQuaternion;
  7747. if (!space || space === BABYLON.Space.LOCAL) {
  7748. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7749. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7750. }
  7751. else {
  7752. if (this.parent) {
  7753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7754. invertParentWorldMatrix.invert();
  7755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7756. }
  7757. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7758. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7759. }
  7760. };
  7761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7762. var displacementVector = axis.scale(distance);
  7763. if (!space || space === BABYLON.Space.LOCAL) {
  7764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7765. this.setPositionWithLocalVector(tempV3);
  7766. }
  7767. else {
  7768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7769. }
  7770. };
  7771. AbstractMesh.prototype.getAbsolutePosition = function () {
  7772. this.computeWorldMatrix();
  7773. return this._absolutePosition;
  7774. };
  7775. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7776. if (!absolutePosition) {
  7777. return;
  7778. }
  7779. var absolutePositionX;
  7780. var absolutePositionY;
  7781. var absolutePositionZ;
  7782. if (absolutePosition.x === undefined) {
  7783. if (arguments.length < 3) {
  7784. return;
  7785. }
  7786. absolutePositionX = arguments[0];
  7787. absolutePositionY = arguments[1];
  7788. absolutePositionZ = arguments[2];
  7789. }
  7790. else {
  7791. absolutePositionX = absolutePosition.x;
  7792. absolutePositionY = absolutePosition.y;
  7793. absolutePositionZ = absolutePosition.z;
  7794. }
  7795. if (this.parent) {
  7796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7797. invertParentWorldMatrix.invert();
  7798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7800. }
  7801. else {
  7802. this.position.x = absolutePositionX;
  7803. this.position.y = absolutePositionY;
  7804. this.position.z = absolutePositionZ;
  7805. }
  7806. };
  7807. // ================================== Point of View Movement =================================
  7808. /**
  7809. * Perform relative position change from the point of view of behind the front of the mesh.
  7810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7811. * Supports definition of mesh facing forward or backward.
  7812. * @param {number} amountRight
  7813. * @param {number} amountUp
  7814. * @param {number} amountForward
  7815. */
  7816. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7817. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7818. };
  7819. /**
  7820. * Calculate relative position change from the point of view of behind the front of the mesh.
  7821. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7822. * Supports definition of mesh facing forward or backward.
  7823. * @param {number} amountRight
  7824. * @param {number} amountUp
  7825. * @param {number} amountForward
  7826. */
  7827. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7828. var rotMatrix = new BABYLON.Matrix();
  7829. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7830. rotQuaternion.toRotationMatrix(rotMatrix);
  7831. var translationDelta = BABYLON.Vector3.Zero();
  7832. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7834. return translationDelta;
  7835. };
  7836. // ================================== Point of View Rotation =================================
  7837. /**
  7838. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7839. * Supports definition of mesh facing forward or backward.
  7840. * @param {number} flipBack
  7841. * @param {number} twirlClockwise
  7842. * @param {number} tiltRight
  7843. */
  7844. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7845. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7846. };
  7847. /**
  7848. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7849. * Supports definition of mesh facing forward or backward.
  7850. * @param {number} flipBack
  7851. * @param {number} twirlClockwise
  7852. * @param {number} tiltRight
  7853. */
  7854. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7855. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7856. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7857. };
  7858. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7859. this._pivotMatrix = matrix;
  7860. this._cache.pivotMatrixUpdated = true;
  7861. };
  7862. AbstractMesh.prototype.getPivotMatrix = function () {
  7863. return this._pivotMatrix;
  7864. };
  7865. AbstractMesh.prototype._isSynchronized = function () {
  7866. if (this._isDirty) {
  7867. return false;
  7868. }
  7869. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7870. return false;
  7871. if (this._cache.pivotMatrixUpdated) {
  7872. return false;
  7873. }
  7874. if (this.infiniteDistance) {
  7875. return false;
  7876. }
  7877. if (!this._cache.position.equals(this.position))
  7878. return false;
  7879. if (this.rotationQuaternion) {
  7880. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7881. return false;
  7882. }
  7883. else {
  7884. if (!this._cache.rotation.equals(this.rotation))
  7885. return false;
  7886. }
  7887. if (!this._cache.scaling.equals(this.scaling))
  7888. return false;
  7889. return true;
  7890. };
  7891. AbstractMesh.prototype._initCache = function () {
  7892. _super.prototype._initCache.call(this);
  7893. this._cache.localMatrixUpdated = false;
  7894. this._cache.position = BABYLON.Vector3.Zero();
  7895. this._cache.scaling = BABYLON.Vector3.Zero();
  7896. this._cache.rotation = BABYLON.Vector3.Zero();
  7897. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7898. this._cache.billboardMode = -1;
  7899. };
  7900. AbstractMesh.prototype.markAsDirty = function (property) {
  7901. if (property === "rotation") {
  7902. this.rotationQuaternion = null;
  7903. }
  7904. this._currentRenderId = Number.MAX_VALUE;
  7905. this._isDirty = true;
  7906. };
  7907. AbstractMesh.prototype._updateBoundingInfo = function () {
  7908. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7909. this._boundingInfo._update(this.worldMatrixFromCache);
  7910. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7911. };
  7912. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7913. if (!this.subMeshes) {
  7914. return;
  7915. }
  7916. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7917. var subMesh = this.subMeshes[subIndex];
  7918. subMesh.updateBoundingInfo(matrix);
  7919. }
  7920. };
  7921. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7922. if (this._isWorldMatrixFrozen) {
  7923. return this._worldMatrix;
  7924. }
  7925. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7926. return this._worldMatrix;
  7927. }
  7928. this._cache.position.copyFrom(this.position);
  7929. this._cache.scaling.copyFrom(this.scaling);
  7930. this._cache.pivotMatrixUpdated = false;
  7931. this._cache.billboardMode = this.billboardMode;
  7932. this._currentRenderId = this.getScene().getRenderId();
  7933. this._isDirty = false;
  7934. // Scaling
  7935. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7936. // Rotation
  7937. if (this.rotationQuaternion) {
  7938. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7939. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7940. }
  7941. else {
  7942. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7943. this._cache.rotation.copyFrom(this.rotation);
  7944. }
  7945. // Translation
  7946. if (this.infiniteDistance && !this.parent) {
  7947. var camera = this.getScene().activeCamera;
  7948. if (camera) {
  7949. var cameraWorldMatrix = camera.getWorldMatrix();
  7950. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7951. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7952. }
  7953. }
  7954. else {
  7955. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7956. }
  7957. // Composing transformations
  7958. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7959. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7960. // Billboarding
  7961. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7962. var localPosition = this.position.clone();
  7963. var zero = this.getScene().activeCamera.globalPosition.clone();
  7964. if (this.parent && this.parent.position) {
  7965. localPosition.addInPlace(this.parent.position);
  7966. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7967. }
  7968. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7969. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7970. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7971. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7972. zero.y = localPosition.y + 0.001;
  7973. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7974. zero.z = localPosition.z + 0.001;
  7975. }
  7976. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7977. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7978. this._localBillboard.invert();
  7979. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7980. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7981. }
  7982. // Local world
  7983. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7984. // Parent
  7985. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7986. this._markSyncedWithParent();
  7987. if (this._meshToBoneReferal) {
  7988. if (!this._localMeshReferalTransform) {
  7989. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7990. }
  7991. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7992. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7993. }
  7994. else {
  7995. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7996. }
  7997. }
  7998. else {
  7999. this._worldMatrix.copyFrom(this._localWorld);
  8000. }
  8001. // Bounding info
  8002. this._updateBoundingInfo();
  8003. // Absolute position
  8004. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8005. // Callbacks
  8006. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8007. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8008. }
  8009. return this._worldMatrix;
  8010. };
  8011. /**
  8012. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8013. * @param func: callback function to add
  8014. */
  8015. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8016. this._onAfterWorldMatrixUpdate.push(func);
  8017. };
  8018. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8019. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8020. if (index > -1) {
  8021. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8022. }
  8023. };
  8024. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8025. this.computeWorldMatrix();
  8026. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8027. };
  8028. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8029. this.computeWorldMatrix();
  8030. var invLocalWorldMatrix = this._localWorld.clone();
  8031. invLocalWorldMatrix.invert();
  8032. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8033. };
  8034. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8035. this.computeWorldMatrix(true);
  8036. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8037. };
  8038. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8039. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8040. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8041. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8042. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8043. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8044. /// <returns>Mesh oriented towards targetMesh</returns>
  8045. yawCor = yawCor || 0; // default to zero if undefined
  8046. pitchCor = pitchCor || 0;
  8047. rollCor = rollCor || 0;
  8048. var dv = targetPoint.subtract(this.position);
  8049. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8050. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8051. var pitch = Math.atan2(dv.y, len);
  8052. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8053. };
  8054. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8055. this._meshToBoneReferal = affectedMesh;
  8056. this.parent = bone;
  8057. if (bone.getWorldMatrix().determinant() < 0) {
  8058. this.scalingDeterminant *= -1;
  8059. }
  8060. };
  8061. AbstractMesh.prototype.detachFromBone = function () {
  8062. if (this.parent.getWorldMatrix().determinant() < 0) {
  8063. this.scalingDeterminant *= -1;
  8064. }
  8065. this._meshToBoneReferal = null;
  8066. this.parent = null;
  8067. };
  8068. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8069. return this._boundingInfo.isInFrustum(frustumPlanes);
  8070. };
  8071. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8072. if (!camera) {
  8073. camera = this.getScene().activeCamera;
  8074. }
  8075. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8076. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8077. return false;
  8078. }
  8079. return true;
  8080. };
  8081. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8082. if (!this._boundingInfo || !mesh._boundingInfo) {
  8083. return false;
  8084. }
  8085. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8086. };
  8087. AbstractMesh.prototype.intersectsPoint = function (point) {
  8088. if (!this._boundingInfo) {
  8089. return false;
  8090. }
  8091. return this._boundingInfo.intersectsPoint(point);
  8092. };
  8093. // Physics
  8094. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8095. var physicsEngine = this.getScene().getPhysicsEngine();
  8096. if (!physicsEngine) {
  8097. return null;
  8098. }
  8099. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8100. if (impostor.impostor) {
  8101. // Old API
  8102. options = impostor;
  8103. impostor = impostor.impostor;
  8104. }
  8105. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8106. physicsEngine._unregisterMesh(this);
  8107. return null;
  8108. }
  8109. if (!options) {
  8110. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8111. }
  8112. else {
  8113. if (!options.mass && options.mass !== 0)
  8114. options.mass = 0;
  8115. if (!options.friction && options.friction !== 0)
  8116. options.friction = 0.2;
  8117. if (!options.restitution && options.restitution !== 0)
  8118. options.restitution = 0.2;
  8119. }
  8120. this._physicImpostor = impostor;
  8121. this._physicsMass = options.mass;
  8122. this._physicsFriction = options.friction;
  8123. this._physicRestitution = options.restitution;
  8124. return physicsEngine._registerMesh(this, impostor, options);
  8125. };
  8126. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8127. if (!this._physicImpostor) {
  8128. return BABYLON.PhysicsEngine.NoImpostor;
  8129. }
  8130. return this._physicImpostor;
  8131. };
  8132. AbstractMesh.prototype.getPhysicsMass = function () {
  8133. if (!this._physicsMass) {
  8134. return 0;
  8135. }
  8136. return this._physicsMass;
  8137. };
  8138. AbstractMesh.prototype.getPhysicsFriction = function () {
  8139. if (!this._physicsFriction) {
  8140. return 0;
  8141. }
  8142. return this._physicsFriction;
  8143. };
  8144. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8145. if (!this._physicRestitution) {
  8146. return 0;
  8147. }
  8148. return this._physicRestitution;
  8149. };
  8150. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8151. if (!camera) {
  8152. camera = this.getScene().activeCamera;
  8153. }
  8154. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8155. };
  8156. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8157. if (!camera) {
  8158. camera = this.getScene().activeCamera;
  8159. }
  8160. return this.absolutePosition.subtract(camera.position).length();
  8161. };
  8162. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8163. if (!this._physicImpostor) {
  8164. return;
  8165. }
  8166. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8167. };
  8168. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8169. if (!this._physicImpostor) {
  8170. return;
  8171. }
  8172. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8173. };
  8174. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8175. if (!this._physicImpostor) {
  8176. return;
  8177. }
  8178. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8179. };
  8180. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8181. // Collisions
  8182. get: function () {
  8183. return this._checkCollisions;
  8184. },
  8185. set: function (collisionEnabled) {
  8186. this._checkCollisions = collisionEnabled;
  8187. if (this.getScene().workerCollisions) {
  8188. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8189. }
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8195. var globalPosition = this.getAbsolutePosition();
  8196. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8197. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8198. this._collider.radius = this.ellipsoid;
  8199. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8200. };
  8201. // Submeshes octree
  8202. /**
  8203. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8204. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8205. */
  8206. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8207. if (maxCapacity === void 0) { maxCapacity = 64; }
  8208. if (maxDepth === void 0) { maxDepth = 2; }
  8209. if (!this._submeshesOctree) {
  8210. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8211. }
  8212. this.computeWorldMatrix(true);
  8213. // Update octree
  8214. var bbox = this.getBoundingInfo().boundingBox;
  8215. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8216. return this._submeshesOctree;
  8217. };
  8218. // Collisions
  8219. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8220. this._generatePointsArray();
  8221. // Transformation
  8222. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8223. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8224. subMesh._lastColliderWorldVertices = [];
  8225. subMesh._trianglePlanes = [];
  8226. var start = subMesh.verticesStart;
  8227. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8228. for (var i = start; i < end; i++) {
  8229. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8230. }
  8231. }
  8232. // Collide
  8233. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8234. if (collider.collisionFound) {
  8235. collider.collidedMesh = this;
  8236. }
  8237. };
  8238. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8239. var subMeshes;
  8240. var len;
  8241. // Octrees
  8242. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8243. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8244. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8245. len = intersections.length;
  8246. subMeshes = intersections.data;
  8247. }
  8248. else {
  8249. subMeshes = this.subMeshes;
  8250. len = subMeshes.length;
  8251. }
  8252. for (var index = 0; index < len; index++) {
  8253. var subMesh = subMeshes[index];
  8254. // Bounding test
  8255. if (len > 1 && !subMesh._checkCollision(collider))
  8256. continue;
  8257. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8258. }
  8259. };
  8260. AbstractMesh.prototype._checkCollision = function (collider) {
  8261. // Bounding box test
  8262. if (!this._boundingInfo._checkCollision(collider))
  8263. return;
  8264. // Transformation matrix
  8265. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8266. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8267. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8268. };
  8269. // Picking
  8270. AbstractMesh.prototype._generatePointsArray = function () {
  8271. return false;
  8272. };
  8273. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8274. var pickingInfo = new BABYLON.PickingInfo();
  8275. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8276. return pickingInfo;
  8277. }
  8278. if (!this._generatePointsArray()) {
  8279. return pickingInfo;
  8280. }
  8281. var intersectInfo = null;
  8282. // Octrees
  8283. var subMeshes;
  8284. var len;
  8285. if (this._submeshesOctree && this.useOctreeForPicking) {
  8286. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8287. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8288. len = intersections.length;
  8289. subMeshes = intersections.data;
  8290. }
  8291. else {
  8292. subMeshes = this.subMeshes;
  8293. len = subMeshes.length;
  8294. }
  8295. for (var index = 0; index < len; index++) {
  8296. var subMesh = subMeshes[index];
  8297. // Bounding test
  8298. if (len > 1 && !subMesh.canIntersects(ray))
  8299. continue;
  8300. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8301. if (currentIntersectInfo) {
  8302. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8303. intersectInfo = currentIntersectInfo;
  8304. intersectInfo.subMeshId = index;
  8305. if (fastCheck) {
  8306. break;
  8307. }
  8308. }
  8309. }
  8310. }
  8311. if (intersectInfo) {
  8312. // Get picked point
  8313. var world = this.getWorldMatrix();
  8314. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8315. var direction = ray.direction.clone();
  8316. direction = direction.scale(intersectInfo.distance);
  8317. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8318. var pickedPoint = worldOrigin.add(worldDirection);
  8319. // Return result
  8320. pickingInfo.hit = true;
  8321. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8322. pickingInfo.pickedPoint = pickedPoint;
  8323. pickingInfo.pickedMesh = this;
  8324. pickingInfo.bu = intersectInfo.bu;
  8325. pickingInfo.bv = intersectInfo.bv;
  8326. pickingInfo.faceId = intersectInfo.faceId;
  8327. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8328. return pickingInfo;
  8329. }
  8330. return pickingInfo;
  8331. };
  8332. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8333. return null;
  8334. };
  8335. AbstractMesh.prototype.releaseSubMeshes = function () {
  8336. if (this.subMeshes) {
  8337. while (this.subMeshes.length) {
  8338. this.subMeshes[0].dispose();
  8339. }
  8340. }
  8341. else {
  8342. this.subMeshes = new Array();
  8343. }
  8344. };
  8345. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8346. var index;
  8347. // Animations
  8348. this.getScene().stopAnimation(this);
  8349. // Physics
  8350. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8351. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8352. }
  8353. // Intersections in progress
  8354. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8355. var other = this._intersectionsInProgress[index];
  8356. var pos = other._intersectionsInProgress.indexOf(this);
  8357. other._intersectionsInProgress.splice(pos, 1);
  8358. }
  8359. this._intersectionsInProgress = [];
  8360. // Edges
  8361. if (this._edgesRenderer) {
  8362. this._edgesRenderer.dispose();
  8363. this._edgesRenderer = null;
  8364. }
  8365. // SubMeshes
  8366. this.releaseSubMeshes();
  8367. // Remove from scene
  8368. this.getScene().removeMesh(this);
  8369. if (!doNotRecurse) {
  8370. // Particles
  8371. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8372. if (this.getScene().particleSystems[index].emitter === this) {
  8373. this.getScene().particleSystems[index].dispose();
  8374. index--;
  8375. }
  8376. }
  8377. // Children
  8378. var objects = this.getScene().meshes.slice(0);
  8379. for (index = 0; index < objects.length; index++) {
  8380. if (objects[index].parent === this) {
  8381. objects[index].dispose();
  8382. }
  8383. }
  8384. }
  8385. else {
  8386. for (index = 0; index < this.getScene().meshes.length; index++) {
  8387. var obj = this.getScene().meshes[index];
  8388. if (obj.parent === this) {
  8389. obj.parent = null;
  8390. obj.computeWorldMatrix(true);
  8391. }
  8392. }
  8393. }
  8394. this._onAfterWorldMatrixUpdate = [];
  8395. this._isDisposed = true;
  8396. // Callback
  8397. if (this.onDispose) {
  8398. this.onDispose();
  8399. }
  8400. };
  8401. // Statics
  8402. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8403. AbstractMesh._BILLBOARDMODE_X = 1;
  8404. AbstractMesh._BILLBOARDMODE_Y = 2;
  8405. AbstractMesh._BILLBOARDMODE_Z = 4;
  8406. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8407. return AbstractMesh;
  8408. })(BABYLON.Node);
  8409. BABYLON.AbstractMesh = AbstractMesh;
  8410. })(BABYLON || (BABYLON = {}));
  8411. var BABYLON;
  8412. (function (BABYLON) {
  8413. var Light = (function (_super) {
  8414. __extends(Light, _super);
  8415. function Light(name, scene) {
  8416. _super.call(this, name, scene);
  8417. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8418. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8419. this.intensity = 1.0;
  8420. this.range = Number.MAX_VALUE;
  8421. this.includeOnlyWithLayerMask = 0;
  8422. this.includedOnlyMeshes = new Array();
  8423. this.excludedMeshes = new Array();
  8424. this.excludeWithLayerMask = 0;
  8425. this._excludedMeshesIds = new Array();
  8426. this._includedOnlyMeshesIds = new Array();
  8427. scene.addLight(this);
  8428. }
  8429. Light.prototype.getShadowGenerator = function () {
  8430. return this._shadowGenerator;
  8431. };
  8432. Light.prototype.getAbsolutePosition = function () {
  8433. return BABYLON.Vector3.Zero();
  8434. };
  8435. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8436. };
  8437. Light.prototype._getWorldMatrix = function () {
  8438. return BABYLON.Matrix.Identity();
  8439. };
  8440. Light.prototype.canAffectMesh = function (mesh) {
  8441. if (!mesh) {
  8442. return true;
  8443. }
  8444. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8445. return false;
  8446. }
  8447. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8448. return false;
  8449. }
  8450. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8451. return false;
  8452. }
  8453. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8454. return false;
  8455. }
  8456. return true;
  8457. };
  8458. Light.prototype.getWorldMatrix = function () {
  8459. this._currentRenderId = this.getScene().getRenderId();
  8460. var worldMatrix = this._getWorldMatrix();
  8461. if (this.parent && this.parent.getWorldMatrix) {
  8462. if (!this._parentedWorldMatrix) {
  8463. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8464. }
  8465. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8466. this._markSyncedWithParent();
  8467. return this._parentedWorldMatrix;
  8468. }
  8469. return worldMatrix;
  8470. };
  8471. Light.prototype.dispose = function () {
  8472. if (this._shadowGenerator) {
  8473. this._shadowGenerator.dispose();
  8474. this._shadowGenerator = null;
  8475. }
  8476. // Animations
  8477. this.getScene().stopAnimation(this);
  8478. // Remove from scene
  8479. this.getScene().removeLight(this);
  8480. };
  8481. Light.prototype.serialize = function () {
  8482. var serializationObject = {};
  8483. serializationObject.name = this.name;
  8484. serializationObject.id = this.id;
  8485. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8486. if (this.intensity) {
  8487. serializationObject.intensity = this.intensity;
  8488. }
  8489. serializationObject.range = this.range;
  8490. serializationObject.diffuse = this.diffuse.asArray();
  8491. serializationObject.specular = this.specular.asArray();
  8492. return serializationObject;
  8493. };
  8494. Light.Parse = function (parsedLight, scene) {
  8495. var light;
  8496. switch (parsedLight.type) {
  8497. case 0:
  8498. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8499. break;
  8500. case 1:
  8501. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8502. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8503. break;
  8504. case 2:
  8505. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8506. break;
  8507. case 3:
  8508. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8509. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8510. break;
  8511. }
  8512. light.id = parsedLight.id;
  8513. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8514. if (parsedLight.intensity !== undefined) {
  8515. light.intensity = parsedLight.intensity;
  8516. }
  8517. if (parsedLight.range) {
  8518. light.range = parsedLight.range;
  8519. }
  8520. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8521. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8522. if (parsedLight.excludedMeshesIds) {
  8523. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8524. }
  8525. // Parent
  8526. if (parsedLight.parentId) {
  8527. light._waitingParentId = parsedLight.parentId;
  8528. }
  8529. if (parsedLight.includedOnlyMeshesIds) {
  8530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8531. }
  8532. // Animations
  8533. if (parsedLight.animations) {
  8534. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8535. var parsedAnimation = parsedLight.animations[animationIndex];
  8536. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8537. }
  8538. }
  8539. if (parsedLight.autoAnimate) {
  8540. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8541. }
  8542. return light;
  8543. };
  8544. return Light;
  8545. })(BABYLON.Node);
  8546. BABYLON.Light = Light;
  8547. })(BABYLON || (BABYLON = {}));
  8548. var BABYLON;
  8549. (function (BABYLON) {
  8550. var PointLight = (function (_super) {
  8551. __extends(PointLight, _super);
  8552. function PointLight(name, position, scene) {
  8553. _super.call(this, name, scene);
  8554. this.position = position;
  8555. }
  8556. PointLight.prototype.getAbsolutePosition = function () {
  8557. return this.transformedPosition ? this.transformedPosition : this.position;
  8558. };
  8559. PointLight.prototype.computeTransformedPosition = function () {
  8560. if (this.parent && this.parent.getWorldMatrix) {
  8561. if (!this.transformedPosition) {
  8562. this.transformedPosition = BABYLON.Vector3.Zero();
  8563. }
  8564. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8565. return true;
  8566. }
  8567. return false;
  8568. };
  8569. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8570. if (this.parent && this.parent.getWorldMatrix) {
  8571. this.computeTransformedPosition();
  8572. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8573. return;
  8574. }
  8575. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8576. };
  8577. PointLight.prototype.needCube = function () {
  8578. return true;
  8579. };
  8580. PointLight.prototype.supportsVSM = function () {
  8581. return false;
  8582. };
  8583. PointLight.prototype.needRefreshPerFrame = function () {
  8584. return false;
  8585. };
  8586. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8587. switch (faceIndex) {
  8588. case 0:
  8589. return new BABYLON.Vector3(1, 0, 0);
  8590. case 1:
  8591. return new BABYLON.Vector3(-1, 0, 0);
  8592. case 2:
  8593. return new BABYLON.Vector3(0, -1, 0);
  8594. case 3:
  8595. return new BABYLON.Vector3(0, 1, 0);
  8596. case 4:
  8597. return new BABYLON.Vector3(0, 0, 1);
  8598. case 5:
  8599. return new BABYLON.Vector3(0, 0, -1);
  8600. }
  8601. return BABYLON.Vector3.Zero();
  8602. };
  8603. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8604. var activeCamera = this.getScene().activeCamera;
  8605. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8606. };
  8607. PointLight.prototype._getWorldMatrix = function () {
  8608. if (!this._worldMatrix) {
  8609. this._worldMatrix = BABYLON.Matrix.Identity();
  8610. }
  8611. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8612. return this._worldMatrix;
  8613. };
  8614. PointLight.prototype.serialize = function () {
  8615. var serializationObject = _super.prototype.serialize.call(this);
  8616. serializationObject.type = 0;
  8617. serializationObject.position = this.position.asArray();
  8618. return serializationObject;
  8619. };
  8620. return PointLight;
  8621. })(BABYLON.Light);
  8622. BABYLON.PointLight = PointLight;
  8623. })(BABYLON || (BABYLON = {}));
  8624. var BABYLON;
  8625. (function (BABYLON) {
  8626. var SpotLight = (function (_super) {
  8627. __extends(SpotLight, _super);
  8628. function SpotLight(name, position, direction, angle, exponent, scene) {
  8629. _super.call(this, name, scene);
  8630. this.position = position;
  8631. this.direction = direction;
  8632. this.angle = angle;
  8633. this.exponent = exponent;
  8634. }
  8635. SpotLight.prototype.getAbsolutePosition = function () {
  8636. return this.transformedPosition ? this.transformedPosition : this.position;
  8637. };
  8638. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8639. var activeCamera = this.getScene().activeCamera;
  8640. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8641. };
  8642. SpotLight.prototype.needCube = function () {
  8643. return false;
  8644. };
  8645. SpotLight.prototype.supportsVSM = function () {
  8646. return true;
  8647. };
  8648. SpotLight.prototype.needRefreshPerFrame = function () {
  8649. return false;
  8650. };
  8651. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8652. return this.direction;
  8653. };
  8654. SpotLight.prototype.setDirectionToTarget = function (target) {
  8655. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8656. return this.direction;
  8657. };
  8658. SpotLight.prototype.computeTransformedPosition = function () {
  8659. if (this.parent && this.parent.getWorldMatrix) {
  8660. if (!this.transformedPosition) {
  8661. this.transformedPosition = BABYLON.Vector3.Zero();
  8662. }
  8663. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8664. return true;
  8665. }
  8666. return false;
  8667. };
  8668. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8669. var normalizeDirection;
  8670. if (this.parent && this.parent.getWorldMatrix) {
  8671. if (!this._transformedDirection) {
  8672. this._transformedDirection = BABYLON.Vector3.Zero();
  8673. }
  8674. this.computeTransformedPosition();
  8675. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8676. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8677. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8678. }
  8679. else {
  8680. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8681. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8682. }
  8683. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8684. };
  8685. SpotLight.prototype._getWorldMatrix = function () {
  8686. if (!this._worldMatrix) {
  8687. this._worldMatrix = BABYLON.Matrix.Identity();
  8688. }
  8689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8690. return this._worldMatrix;
  8691. };
  8692. SpotLight.prototype.serialize = function () {
  8693. var serializationObject = _super.prototype.serialize.call(this);
  8694. serializationObject.type = 2;
  8695. serializationObject.position = this.position.asArray();
  8696. serializationObject.direction = this.position.asArray();
  8697. serializationObject.angle = this.angle;
  8698. serializationObject.exponent = this.exponent;
  8699. return serializationObject;
  8700. };
  8701. return SpotLight;
  8702. })(BABYLON.Light);
  8703. BABYLON.SpotLight = SpotLight;
  8704. })(BABYLON || (BABYLON = {}));
  8705. var BABYLON;
  8706. (function (BABYLON) {
  8707. var HemisphericLight = (function (_super) {
  8708. __extends(HemisphericLight, _super);
  8709. function HemisphericLight(name, direction, scene) {
  8710. _super.call(this, name, scene);
  8711. this.direction = direction;
  8712. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8713. }
  8714. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8715. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8716. return this.direction;
  8717. };
  8718. HemisphericLight.prototype.getShadowGenerator = function () {
  8719. return null;
  8720. };
  8721. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8722. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8723. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8724. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8725. };
  8726. HemisphericLight.prototype._getWorldMatrix = function () {
  8727. if (!this._worldMatrix) {
  8728. this._worldMatrix = BABYLON.Matrix.Identity();
  8729. }
  8730. return this._worldMatrix;
  8731. };
  8732. HemisphericLight.prototype.serialize = function () {
  8733. var serializationObject = _super.prototype.serialize.call(this);
  8734. serializationObject.type = 3;
  8735. serializationObject.direction = this.direction.asArray();
  8736. serializationObject.groundColor = this.groundColor.asArray();
  8737. return serializationObject;
  8738. };
  8739. return HemisphericLight;
  8740. })(BABYLON.Light);
  8741. BABYLON.HemisphericLight = HemisphericLight;
  8742. })(BABYLON || (BABYLON = {}));
  8743. var BABYLON;
  8744. (function (BABYLON) {
  8745. var DirectionalLight = (function (_super) {
  8746. __extends(DirectionalLight, _super);
  8747. function DirectionalLight(name, direction, scene) {
  8748. _super.call(this, name, scene);
  8749. this.direction = direction;
  8750. this.shadowOrthoScale = 0.5;
  8751. this.autoUpdateExtends = true;
  8752. // Cache
  8753. this._orthoLeft = Number.MAX_VALUE;
  8754. this._orthoRight = Number.MIN_VALUE;
  8755. this._orthoTop = Number.MIN_VALUE;
  8756. this._orthoBottom = Number.MAX_VALUE;
  8757. this.position = direction.scale(-1);
  8758. }
  8759. DirectionalLight.prototype.getAbsolutePosition = function () {
  8760. return this.transformedPosition ? this.transformedPosition : this.position;
  8761. };
  8762. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8763. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8764. return this.direction;
  8765. };
  8766. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8767. var activeCamera = this.getScene().activeCamera;
  8768. // Check extends
  8769. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8770. var tempVector3 = BABYLON.Vector3.Zero();
  8771. this._orthoLeft = Number.MAX_VALUE;
  8772. this._orthoRight = Number.MIN_VALUE;
  8773. this._orthoTop = Number.MIN_VALUE;
  8774. this._orthoBottom = Number.MAX_VALUE;
  8775. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8776. var mesh = renderList[meshIndex];
  8777. if (!mesh) {
  8778. continue;
  8779. }
  8780. var boundingInfo = mesh.getBoundingInfo();
  8781. if (!boundingInfo) {
  8782. continue;
  8783. }
  8784. var boundingBox = boundingInfo.boundingBox;
  8785. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8786. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8787. if (tempVector3.x < this._orthoLeft)
  8788. this._orthoLeft = tempVector3.x;
  8789. if (tempVector3.y < this._orthoBottom)
  8790. this._orthoBottom = tempVector3.y;
  8791. if (tempVector3.x > this._orthoRight)
  8792. this._orthoRight = tempVector3.x;
  8793. if (tempVector3.y > this._orthoTop)
  8794. this._orthoTop = tempVector3.y;
  8795. }
  8796. }
  8797. }
  8798. var xOffset = this._orthoRight - this._orthoLeft;
  8799. var yOffset = this._orthoTop - this._orthoBottom;
  8800. 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);
  8801. };
  8802. DirectionalLight.prototype.supportsVSM = function () {
  8803. return true;
  8804. };
  8805. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8806. return true;
  8807. };
  8808. DirectionalLight.prototype.needCube = function () {
  8809. return false;
  8810. };
  8811. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8812. return this.direction;
  8813. };
  8814. DirectionalLight.prototype.computeTransformedPosition = function () {
  8815. if (this.parent && this.parent.getWorldMatrix) {
  8816. if (!this.transformedPosition) {
  8817. this.transformedPosition = BABYLON.Vector3.Zero();
  8818. }
  8819. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8820. return true;
  8821. }
  8822. return false;
  8823. };
  8824. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8825. if (this.parent && this.parent.getWorldMatrix) {
  8826. if (!this._transformedDirection) {
  8827. this._transformedDirection = BABYLON.Vector3.Zero();
  8828. }
  8829. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8830. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8831. return;
  8832. }
  8833. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8834. };
  8835. DirectionalLight.prototype._getWorldMatrix = function () {
  8836. if (!this._worldMatrix) {
  8837. this._worldMatrix = BABYLON.Matrix.Identity();
  8838. }
  8839. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8840. return this._worldMatrix;
  8841. };
  8842. DirectionalLight.prototype.serialize = function () {
  8843. var serializationObject = _super.prototype.serialize.call(this);
  8844. serializationObject.type = 1;
  8845. serializationObject.position = this.position.asArray();
  8846. serializationObject.direction = this.direction.asArray();
  8847. return serializationObject;
  8848. };
  8849. return DirectionalLight;
  8850. })(BABYLON.Light);
  8851. BABYLON.DirectionalLight = DirectionalLight;
  8852. })(BABYLON || (BABYLON = {}));
  8853. var BABYLON;
  8854. (function (BABYLON) {
  8855. var ShadowGenerator = (function () {
  8856. function ShadowGenerator(mapSize, light) {
  8857. var _this = this;
  8858. // Members
  8859. this._filter = ShadowGenerator.FILTER_NONE;
  8860. this.blurScale = 2;
  8861. this._blurBoxOffset = 0;
  8862. this._bias = 0.00005;
  8863. this._lightDirection = BABYLON.Vector3.Zero();
  8864. this._darkness = 0;
  8865. this._transparencyShadow = false;
  8866. this._viewMatrix = BABYLON.Matrix.Zero();
  8867. this._projectionMatrix = BABYLON.Matrix.Zero();
  8868. this._transformMatrix = BABYLON.Matrix.Zero();
  8869. this._worldViewProjection = BABYLON.Matrix.Zero();
  8870. this._currentFaceIndex = 0;
  8871. this._currentFaceIndexCache = 0;
  8872. this._light = light;
  8873. this._scene = light.getScene();
  8874. this._mapSize = mapSize;
  8875. light._shadowGenerator = this;
  8876. // Render target
  8877. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8878. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8879. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8880. this._shadowMap.anisotropicFilteringLevel = 1;
  8881. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8882. this._shadowMap.renderParticles = false;
  8883. this._shadowMap.onBeforeRender = function (faceIndex) {
  8884. _this._currentFaceIndex = faceIndex;
  8885. };
  8886. this._shadowMap.onAfterUnbind = function () {
  8887. if (!_this.useBlurVarianceShadowMap) {
  8888. return;
  8889. }
  8890. if (!_this._shadowMap2) {
  8891. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8892. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8893. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8894. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8895. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8896. _this._downSamplePostprocess.onApply = function (effect) {
  8897. effect.setTexture("textureSampler", _this._shadowMap);
  8898. };
  8899. _this.blurBoxOffset = 1;
  8900. }
  8901. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8902. };
  8903. // Custom render function
  8904. var renderSubMesh = function (subMesh) {
  8905. var mesh = subMesh.getRenderingMesh();
  8906. var scene = _this._scene;
  8907. var engine = scene.getEngine();
  8908. // Culling
  8909. engine.setState(subMesh.getMaterial().backFaceCulling);
  8910. // Managing instances
  8911. var batch = mesh._getInstancesRenderList(subMesh._id);
  8912. if (batch.mustReturn) {
  8913. return;
  8914. }
  8915. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8916. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8917. engine.enableEffect(_this._effect);
  8918. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8919. var material = subMesh.getMaterial();
  8920. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8921. // Alpha test
  8922. if (material && material.needAlphaTesting()) {
  8923. var alphaTexture = material.getAlphaTestTexture();
  8924. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8925. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8926. }
  8927. // Bones
  8928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8929. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8930. }
  8931. // Draw
  8932. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8933. }
  8934. else {
  8935. // Need to reset refresh rate of the shadowMap
  8936. _this._shadowMap.resetRefreshCounter();
  8937. }
  8938. };
  8939. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8940. var index;
  8941. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8942. renderSubMesh(opaqueSubMeshes.data[index]);
  8943. }
  8944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8945. renderSubMesh(alphaTestSubMeshes.data[index]);
  8946. }
  8947. if (_this._transparencyShadow) {
  8948. for (index = 0; index < transparentSubMeshes.length; index++) {
  8949. renderSubMesh(transparentSubMeshes.data[index]);
  8950. }
  8951. }
  8952. };
  8953. this._shadowMap.onClear = function (engine) {
  8954. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8955. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8956. }
  8957. else {
  8958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8959. }
  8960. };
  8961. }
  8962. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8963. // Static
  8964. get: function () {
  8965. return ShadowGenerator._FILTER_NONE;
  8966. },
  8967. enumerable: true,
  8968. configurable: true
  8969. });
  8970. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8971. get: function () {
  8972. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8973. },
  8974. enumerable: true,
  8975. configurable: true
  8976. });
  8977. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8978. get: function () {
  8979. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8985. get: function () {
  8986. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8987. },
  8988. enumerable: true,
  8989. configurable: true
  8990. });
  8991. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8992. get: function () {
  8993. return this._bias;
  8994. },
  8995. set: function (bias) {
  8996. this._bias = bias;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9002. get: function () {
  9003. return this._blurBoxOffset;
  9004. },
  9005. set: function (value) {
  9006. var _this = this;
  9007. if (this._blurBoxOffset === value) {
  9008. return;
  9009. }
  9010. this._blurBoxOffset = value;
  9011. if (this._boxBlurPostprocess) {
  9012. this._boxBlurPostprocess.dispose();
  9013. }
  9014. 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);
  9015. this._boxBlurPostprocess.onApply = function (effect) {
  9016. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9017. };
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9023. get: function () {
  9024. return this._filter;
  9025. },
  9026. set: function (value) {
  9027. if (this._filter === value) {
  9028. return;
  9029. }
  9030. this._filter = value;
  9031. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9032. this._shadowMap.anisotropicFilteringLevel = 16;
  9033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9034. }
  9035. else {
  9036. this._shadowMap.anisotropicFilteringLevel = 1;
  9037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9038. }
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9044. get: function () {
  9045. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9046. },
  9047. set: function (value) {
  9048. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9049. },
  9050. enumerable: true,
  9051. configurable: true
  9052. });
  9053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9054. get: function () {
  9055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9056. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9057. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9058. },
  9059. set: function (value) {
  9060. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9066. get: function () {
  9067. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9068. },
  9069. set: function (value) {
  9070. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9076. var defines = [];
  9077. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9078. defines.push("#define VSM");
  9079. }
  9080. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9081. var mesh = subMesh.getMesh();
  9082. var material = subMesh.getMaterial();
  9083. // Alpha test
  9084. if (material && material.needAlphaTesting()) {
  9085. defines.push("#define ALPHATEST");
  9086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9087. attribs.push(BABYLON.VertexBuffer.UVKind);
  9088. defines.push("#define UV1");
  9089. }
  9090. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9092. defines.push("#define UV2");
  9093. }
  9094. }
  9095. // Bones
  9096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9097. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9098. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9099. if (mesh.numBoneInfluencers > 4) {
  9100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9102. }
  9103. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9104. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9105. }
  9106. else {
  9107. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9108. }
  9109. // Instances
  9110. if (useInstances) {
  9111. defines.push("#define INSTANCES");
  9112. attribs.push("world0");
  9113. attribs.push("world1");
  9114. attribs.push("world2");
  9115. attribs.push("world3");
  9116. }
  9117. // Get correct effect
  9118. var join = defines.join("\n");
  9119. if (this._cachedDefines !== join) {
  9120. this._cachedDefines = join;
  9121. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9122. }
  9123. return this._effect.isReady();
  9124. };
  9125. ShadowGenerator.prototype.getShadowMap = function () {
  9126. return this._shadowMap;
  9127. };
  9128. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9129. if (this._shadowMap2) {
  9130. return this._shadowMap2;
  9131. }
  9132. return this._shadowMap;
  9133. };
  9134. ShadowGenerator.prototype.getLight = function () {
  9135. return this._light;
  9136. };
  9137. // Methods
  9138. ShadowGenerator.prototype.getTransformMatrix = function () {
  9139. var scene = this._scene;
  9140. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9141. return this._transformMatrix;
  9142. }
  9143. this._currentRenderID = scene.getRenderId();
  9144. this._currentFaceIndexCache = this._currentFaceIndex;
  9145. var lightPosition = this._light.position;
  9146. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9147. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9148. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9149. }
  9150. if (this._light.computeTransformedPosition()) {
  9151. lightPosition = this._light.transformedPosition;
  9152. }
  9153. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9154. this._cachedPosition = lightPosition.clone();
  9155. this._cachedDirection = this._lightDirection.clone();
  9156. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9157. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9158. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9159. }
  9160. return this._transformMatrix;
  9161. };
  9162. ShadowGenerator.prototype.getDarkness = function () {
  9163. return this._darkness;
  9164. };
  9165. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9166. if (darkness >= 1.0)
  9167. this._darkness = 1.0;
  9168. else if (darkness <= 0.0)
  9169. this._darkness = 0.0;
  9170. else
  9171. this._darkness = darkness;
  9172. };
  9173. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9174. this._transparencyShadow = hasShadow;
  9175. };
  9176. ShadowGenerator.prototype._packHalf = function (depth) {
  9177. var scale = depth * 255.0;
  9178. var fract = scale - Math.floor(scale);
  9179. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9180. };
  9181. ShadowGenerator.prototype.dispose = function () {
  9182. this._shadowMap.dispose();
  9183. if (this._shadowMap2) {
  9184. this._shadowMap2.dispose();
  9185. }
  9186. if (this._downSamplePostprocess) {
  9187. this._downSamplePostprocess.dispose();
  9188. }
  9189. if (this._boxBlurPostprocess) {
  9190. this._boxBlurPostprocess.dispose();
  9191. }
  9192. };
  9193. ShadowGenerator.prototype.serialize = function () {
  9194. var serializationObject = {};
  9195. serializationObject.lightId = this._light.id;
  9196. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9197. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9198. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9199. serializationObject.renderList = [];
  9200. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9201. var mesh = this.getShadowMap().renderList[meshIndex];
  9202. serializationObject.renderList.push(mesh.id);
  9203. }
  9204. return serializationObject;
  9205. };
  9206. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9207. //casting to point light, as light is missing the position attr and typescript complains.
  9208. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9209. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9210. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9211. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9212. shadowGenerator.getShadowMap().renderList.push(mesh);
  9213. }
  9214. if (parsedShadowGenerator.usePoissonSampling) {
  9215. shadowGenerator.usePoissonSampling = true;
  9216. }
  9217. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9218. shadowGenerator.useVarianceShadowMap = true;
  9219. }
  9220. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9221. shadowGenerator.useBlurVarianceShadowMap = true;
  9222. if (parsedShadowGenerator.blurScale) {
  9223. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9224. }
  9225. if (parsedShadowGenerator.blurBoxOffset) {
  9226. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9227. }
  9228. }
  9229. if (parsedShadowGenerator.bias !== undefined) {
  9230. shadowGenerator.bias = parsedShadowGenerator.bias;
  9231. }
  9232. return shadowGenerator;
  9233. };
  9234. ShadowGenerator._FILTER_NONE = 0;
  9235. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9236. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9237. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9238. return ShadowGenerator;
  9239. })();
  9240. BABYLON.ShadowGenerator = ShadowGenerator;
  9241. })(BABYLON || (BABYLON = {}));
  9242. var BABYLON;
  9243. (function (BABYLON) {
  9244. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9245. if (boxMin.x > sphereCenter.x + sphereRadius)
  9246. return false;
  9247. if (sphereCenter.x - sphereRadius > boxMax.x)
  9248. return false;
  9249. if (boxMin.y > sphereCenter.y + sphereRadius)
  9250. return false;
  9251. if (sphereCenter.y - sphereRadius > boxMax.y)
  9252. return false;
  9253. if (boxMin.z > sphereCenter.z + sphereRadius)
  9254. return false;
  9255. if (sphereCenter.z - sphereRadius > boxMax.z)
  9256. return false;
  9257. return true;
  9258. };
  9259. var getLowestRoot = function (a, b, c, maxR) {
  9260. var determinant = b * b - 4.0 * a * c;
  9261. var result = { root: 0, found: false };
  9262. if (determinant < 0)
  9263. return result;
  9264. var sqrtD = Math.sqrt(determinant);
  9265. var r1 = (-b - sqrtD) / (2.0 * a);
  9266. var r2 = (-b + sqrtD) / (2.0 * a);
  9267. if (r1 > r2) {
  9268. var temp = r2;
  9269. r2 = r1;
  9270. r1 = temp;
  9271. }
  9272. if (r1 > 0 && r1 < maxR) {
  9273. result.root = r1;
  9274. result.found = true;
  9275. return result;
  9276. }
  9277. if (r2 > 0 && r2 < maxR) {
  9278. result.root = r2;
  9279. result.found = true;
  9280. return result;
  9281. }
  9282. return result;
  9283. };
  9284. var Collider = (function () {
  9285. function Collider() {
  9286. this.radius = new BABYLON.Vector3(1, 1, 1);
  9287. this.retry = 0;
  9288. this.basePointWorld = BABYLON.Vector3.Zero();
  9289. this.velocityWorld = BABYLON.Vector3.Zero();
  9290. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9291. this._collisionPoint = BABYLON.Vector3.Zero();
  9292. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9293. this._tempVector = BABYLON.Vector3.Zero();
  9294. this._tempVector2 = BABYLON.Vector3.Zero();
  9295. this._tempVector3 = BABYLON.Vector3.Zero();
  9296. this._tempVector4 = BABYLON.Vector3.Zero();
  9297. this._edge = BABYLON.Vector3.Zero();
  9298. this._baseToVertex = BABYLON.Vector3.Zero();
  9299. this._destinationPoint = BABYLON.Vector3.Zero();
  9300. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9301. this._displacementVector = BABYLON.Vector3.Zero();
  9302. }
  9303. // Methods
  9304. Collider.prototype._initialize = function (source, dir, e) {
  9305. this.velocity = dir;
  9306. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9307. this.basePoint = source;
  9308. source.multiplyToRef(this.radius, this.basePointWorld);
  9309. dir.multiplyToRef(this.radius, this.velocityWorld);
  9310. this.velocityWorldLength = this.velocityWorld.length();
  9311. this.epsilon = e;
  9312. this.collisionFound = false;
  9313. };
  9314. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9315. pa.subtractToRef(point, this._tempVector);
  9316. pb.subtractToRef(point, this._tempVector2);
  9317. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9318. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9319. if (d < 0)
  9320. return false;
  9321. pc.subtractToRef(point, this._tempVector3);
  9322. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9323. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9324. if (d < 0)
  9325. return false;
  9326. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9327. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9328. return d >= 0;
  9329. };
  9330. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9331. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9332. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9333. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9334. return false;
  9335. }
  9336. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9337. return false;
  9338. return true;
  9339. };
  9340. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9341. var t0;
  9342. var embeddedInPlane = false;
  9343. //defensive programming, actually not needed.
  9344. if (!trianglePlaneArray) {
  9345. trianglePlaneArray = [];
  9346. }
  9347. if (!trianglePlaneArray[faceIndex]) {
  9348. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9349. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9350. }
  9351. var trianglePlane = trianglePlaneArray[faceIndex];
  9352. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9353. return;
  9354. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9355. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9356. if (normalDotVelocity == 0) {
  9357. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9358. return;
  9359. embeddedInPlane = true;
  9360. t0 = 0;
  9361. }
  9362. else {
  9363. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9364. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9365. if (t0 > t1) {
  9366. var temp = t1;
  9367. t1 = t0;
  9368. t0 = temp;
  9369. }
  9370. if (t0 > 1.0 || t1 < 0.0)
  9371. return;
  9372. if (t0 < 0)
  9373. t0 = 0;
  9374. if (t0 > 1.0)
  9375. t0 = 1.0;
  9376. }
  9377. this._collisionPoint.copyFromFloats(0, 0, 0);
  9378. var found = false;
  9379. var t = 1.0;
  9380. if (!embeddedInPlane) {
  9381. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9382. this.velocity.scaleToRef(t0, this._tempVector);
  9383. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9384. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9385. found = true;
  9386. t = t0;
  9387. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9388. }
  9389. }
  9390. if (!found) {
  9391. var velocitySquaredLength = this.velocity.lengthSquared();
  9392. var a = velocitySquaredLength;
  9393. this.basePoint.subtractToRef(p1, this._tempVector);
  9394. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9395. var c = this._tempVector.lengthSquared() - 1.0;
  9396. var lowestRoot = getLowestRoot(a, b, c, t);
  9397. if (lowestRoot.found) {
  9398. t = lowestRoot.root;
  9399. found = true;
  9400. this._collisionPoint.copyFrom(p1);
  9401. }
  9402. this.basePoint.subtractToRef(p2, this._tempVector);
  9403. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9404. c = this._tempVector.lengthSquared() - 1.0;
  9405. lowestRoot = getLowestRoot(a, b, c, t);
  9406. if (lowestRoot.found) {
  9407. t = lowestRoot.root;
  9408. found = true;
  9409. this._collisionPoint.copyFrom(p2);
  9410. }
  9411. this.basePoint.subtractToRef(p3, this._tempVector);
  9412. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9413. c = this._tempVector.lengthSquared() - 1.0;
  9414. lowestRoot = getLowestRoot(a, b, c, t);
  9415. if (lowestRoot.found) {
  9416. t = lowestRoot.root;
  9417. found = true;
  9418. this._collisionPoint.copyFrom(p3);
  9419. }
  9420. p2.subtractToRef(p1, this._edge);
  9421. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9422. var edgeSquaredLength = this._edge.lengthSquared();
  9423. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9424. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9425. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9426. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9427. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9428. lowestRoot = getLowestRoot(a, b, c, t);
  9429. if (lowestRoot.found) {
  9430. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9431. if (f >= 0.0 && f <= 1.0) {
  9432. t = lowestRoot.root;
  9433. found = true;
  9434. this._edge.scaleInPlace(f);
  9435. p1.addToRef(this._edge, this._collisionPoint);
  9436. }
  9437. }
  9438. p3.subtractToRef(p2, this._edge);
  9439. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9440. edgeSquaredLength = this._edge.lengthSquared();
  9441. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9442. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9443. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9444. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9445. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9446. lowestRoot = getLowestRoot(a, b, c, t);
  9447. if (lowestRoot.found) {
  9448. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9449. if (f >= 0.0 && f <= 1.0) {
  9450. t = lowestRoot.root;
  9451. found = true;
  9452. this._edge.scaleInPlace(f);
  9453. p2.addToRef(this._edge, this._collisionPoint);
  9454. }
  9455. }
  9456. p1.subtractToRef(p3, this._edge);
  9457. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9458. edgeSquaredLength = this._edge.lengthSquared();
  9459. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9460. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9461. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9462. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9463. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9464. lowestRoot = getLowestRoot(a, b, c, t);
  9465. if (lowestRoot.found) {
  9466. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9467. if (f >= 0.0 && f <= 1.0) {
  9468. t = lowestRoot.root;
  9469. found = true;
  9470. this._edge.scaleInPlace(f);
  9471. p3.addToRef(this._edge, this._collisionPoint);
  9472. }
  9473. }
  9474. }
  9475. if (found) {
  9476. var distToCollision = t * this.velocity.length();
  9477. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9478. if (!this.intersectionPoint) {
  9479. this.intersectionPoint = this._collisionPoint.clone();
  9480. }
  9481. else {
  9482. this.intersectionPoint.copyFrom(this._collisionPoint);
  9483. }
  9484. this.nearestDistance = distToCollision;
  9485. this.collisionFound = true;
  9486. }
  9487. }
  9488. };
  9489. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9490. for (var i = indexStart; i < indexEnd; i += 3) {
  9491. var p1 = pts[indices[i] - decal];
  9492. var p2 = pts[indices[i + 1] - decal];
  9493. var p3 = pts[indices[i + 2] - decal];
  9494. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9495. }
  9496. };
  9497. Collider.prototype._getResponse = function (pos, vel) {
  9498. pos.addToRef(vel, this._destinationPoint);
  9499. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9500. this.basePoint.addToRef(vel, pos);
  9501. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9502. this._slidePlaneNormal.normalize();
  9503. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9504. pos.addInPlace(this._displacementVector);
  9505. this.intersectionPoint.addInPlace(this._displacementVector);
  9506. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9507. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9508. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9509. };
  9510. return Collider;
  9511. })();
  9512. BABYLON.Collider = Collider;
  9513. })(BABYLON || (BABYLON = {}));
  9514. var BABYLON;
  9515. (function (BABYLON) {
  9516. //WebWorker code will be inserted to this variable.
  9517. BABYLON.CollisionWorker = "";
  9518. (function (WorkerTaskType) {
  9519. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9520. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9521. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9522. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9523. var WorkerTaskType = BABYLON.WorkerTaskType;
  9524. (function (WorkerReplyType) {
  9525. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9526. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9527. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9528. var WorkerReplyType = BABYLON.WorkerReplyType;
  9529. var CollisionCoordinatorWorker = (function () {
  9530. function CollisionCoordinatorWorker() {
  9531. var _this = this;
  9532. this._scaledPosition = BABYLON.Vector3.Zero();
  9533. this._scaledVelocity = BABYLON.Vector3.Zero();
  9534. this.onMeshUpdated = function (mesh) {
  9535. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9536. };
  9537. this.onGeometryUpdated = function (geometry) {
  9538. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9539. };
  9540. this._afterRender = function () {
  9541. if (!_this._init)
  9542. return;
  9543. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9544. return;
  9545. }
  9546. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9547. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9548. if (_this._runningUpdated > 4) {
  9549. return;
  9550. }
  9551. ++_this._runningUpdated;
  9552. var payload = {
  9553. updatedMeshes: _this._addUpdateMeshesList,
  9554. updatedGeometries: _this._addUpdateGeometriesList,
  9555. removedGeometries: _this._toRemoveGeometryArray,
  9556. removedMeshes: _this._toRemoveMeshesArray
  9557. };
  9558. var message = {
  9559. payload: payload,
  9560. taskType: WorkerTaskType.UPDATE
  9561. };
  9562. var serializable = [];
  9563. for (var id in payload.updatedGeometries) {
  9564. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9565. //prepare transferables
  9566. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9567. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9568. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9569. }
  9570. }
  9571. _this._worker.postMessage(message, serializable);
  9572. _this._addUpdateMeshesList = {};
  9573. _this._addUpdateGeometriesList = {};
  9574. _this._toRemoveGeometryArray = [];
  9575. _this._toRemoveMeshesArray = [];
  9576. };
  9577. this._onMessageFromWorker = function (e) {
  9578. var returnData = e.data;
  9579. if (returnData.error != WorkerReplyType.SUCCESS) {
  9580. //TODO what errors can be returned from the worker?
  9581. BABYLON.Tools.Warn("error returned from worker!");
  9582. return;
  9583. }
  9584. switch (returnData.taskType) {
  9585. case WorkerTaskType.INIT:
  9586. _this._init = true;
  9587. //Update the worked with ALL of the scene's current state
  9588. _this._scene.meshes.forEach(function (mesh) {
  9589. _this.onMeshAdded(mesh);
  9590. });
  9591. _this._scene.getGeometries().forEach(function (geometry) {
  9592. _this.onGeometryAdded(geometry);
  9593. });
  9594. break;
  9595. case WorkerTaskType.UPDATE:
  9596. _this._runningUpdated--;
  9597. break;
  9598. case WorkerTaskType.COLLIDE:
  9599. _this._runningCollisionTask = false;
  9600. var returnPayload = returnData.payload;
  9601. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9602. return;
  9603. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9604. //cleanup
  9605. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9606. break;
  9607. }
  9608. };
  9609. this._collisionsCallbackArray = [];
  9610. this._init = false;
  9611. this._runningUpdated = 0;
  9612. this._runningCollisionTask = false;
  9613. this._addUpdateMeshesList = {};
  9614. this._addUpdateGeometriesList = {};
  9615. this._toRemoveGeometryArray = [];
  9616. this._toRemoveMeshesArray = [];
  9617. }
  9618. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9619. if (!this._init)
  9620. return;
  9621. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9622. return;
  9623. position.divideToRef(collider.radius, this._scaledPosition);
  9624. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9625. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9626. var payload = {
  9627. collider: {
  9628. position: this._scaledPosition.asArray(),
  9629. velocity: this._scaledVelocity.asArray(),
  9630. radius: collider.radius.asArray()
  9631. },
  9632. collisionId: collisionIndex,
  9633. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9634. maximumRetry: maximumRetry
  9635. };
  9636. var message = {
  9637. payload: payload,
  9638. taskType: WorkerTaskType.COLLIDE
  9639. };
  9640. this._worker.postMessage(message);
  9641. };
  9642. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9643. this._scene = scene;
  9644. this._scene.registerAfterRender(this._afterRender);
  9645. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9646. this._worker = new Worker(workerUrl);
  9647. this._worker.onmessage = this._onMessageFromWorker;
  9648. var message = {
  9649. payload: {},
  9650. taskType: WorkerTaskType.INIT
  9651. };
  9652. this._worker.postMessage(message);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.destroy = function () {
  9655. this._scene.unregisterAfterRender(this._afterRender);
  9656. this._worker.terminate();
  9657. };
  9658. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9659. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9660. this.onMeshUpdated(mesh);
  9661. };
  9662. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9663. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9664. };
  9665. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9666. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9667. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9668. this.onGeometryUpdated(geometry);
  9669. };
  9670. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9671. this._toRemoveGeometryArray.push(geometry.id);
  9672. };
  9673. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9674. var submeshes = [];
  9675. if (mesh.subMeshes) {
  9676. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9677. return {
  9678. position: idx,
  9679. verticesStart: sm.verticesStart,
  9680. verticesCount: sm.verticesCount,
  9681. indexStart: sm.indexStart,
  9682. indexCount: sm.indexCount,
  9683. hasMaterial: !!sm.getMaterial(),
  9684. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9685. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9686. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9687. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9688. };
  9689. });
  9690. }
  9691. var geometryId = null;
  9692. if (mesh instanceof BABYLON.Mesh) {
  9693. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9694. }
  9695. else if (mesh instanceof BABYLON.InstancedMesh) {
  9696. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9697. }
  9698. return {
  9699. uniqueId: mesh.uniqueId,
  9700. id: mesh.id,
  9701. name: mesh.name,
  9702. geometryId: geometryId,
  9703. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9704. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9705. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9706. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9707. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9708. subMeshes: submeshes,
  9709. checkCollisions: mesh.checkCollisions
  9710. };
  9711. };
  9712. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9713. return {
  9714. id: geometry.id,
  9715. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9716. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9717. indices: new Int32Array(geometry.getIndices() || []),
  9718. };
  9719. };
  9720. return CollisionCoordinatorWorker;
  9721. })();
  9722. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9723. var CollisionCoordinatorLegacy = (function () {
  9724. function CollisionCoordinatorLegacy() {
  9725. this._scaledPosition = BABYLON.Vector3.Zero();
  9726. this._scaledVelocity = BABYLON.Vector3.Zero();
  9727. this._finalPosition = BABYLON.Vector3.Zero();
  9728. }
  9729. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9730. position.divideToRef(collider.radius, this._scaledPosition);
  9731. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9732. collider.collidedMesh = null;
  9733. collider.retry = 0;
  9734. collider.initialVelocity = this._scaledVelocity;
  9735. collider.initialPosition = this._scaledPosition;
  9736. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9737. this._finalPosition.multiplyInPlace(collider.radius);
  9738. //run the callback
  9739. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9740. };
  9741. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9742. this._scene = scene;
  9743. };
  9744. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9745. //Legacy need no destruction method.
  9746. };
  9747. //No update in legacy mode
  9748. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9749. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9750. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9751. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9752. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9753. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9754. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9755. if (excludedMesh === void 0) { excludedMesh = null; }
  9756. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9757. if (collider.retry >= maximumRetry) {
  9758. finalPosition.copyFrom(position);
  9759. return;
  9760. }
  9761. collider._initialize(position, velocity, closeDistance);
  9762. // Check all meshes
  9763. for (var index = 0; index < this._scene.meshes.length; index++) {
  9764. var mesh = this._scene.meshes[index];
  9765. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9766. mesh._checkCollision(collider);
  9767. }
  9768. }
  9769. if (!collider.collisionFound) {
  9770. position.addToRef(velocity, finalPosition);
  9771. return;
  9772. }
  9773. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9774. collider._getResponse(position, velocity);
  9775. }
  9776. if (velocity.length() <= closeDistance) {
  9777. finalPosition.copyFrom(position);
  9778. return;
  9779. }
  9780. collider.retry++;
  9781. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9782. };
  9783. return CollisionCoordinatorLegacy;
  9784. })();
  9785. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9786. })(BABYLON || (BABYLON = {}));
  9787. var BABYLON;
  9788. (function (BABYLON) {
  9789. var VRCameraMetrics = (function () {
  9790. function VRCameraMetrics() {
  9791. this.compensateDistortion = true;
  9792. }
  9793. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9794. get: function () {
  9795. return this.hResolution / (2 * this.vResolution);
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9801. get: function () {
  9802. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9803. },
  9804. enumerable: true,
  9805. configurable: true
  9806. });
  9807. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9808. get: function () {
  9809. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9810. var h = (4 * meters) / this.hScreenSize;
  9811. return BABYLON.Matrix.Translation(h, 0, 0);
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9817. get: function () {
  9818. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9819. var h = (4 * meters) / this.hScreenSize;
  9820. return BABYLON.Matrix.Translation(-h, 0, 0);
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9826. get: function () {
  9827. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9833. get: function () {
  9834. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. VRCameraMetrics.GetDefault = function () {
  9840. var result = new VRCameraMetrics();
  9841. result.hResolution = 1280;
  9842. result.vResolution = 800;
  9843. result.hScreenSize = 0.149759993;
  9844. result.vScreenSize = 0.0935999975;
  9845. result.vScreenCenter = 0.0467999987,
  9846. result.eyeToScreenDistance = 0.0410000011;
  9847. result.lensSeparationDistance = 0.0635000020;
  9848. result.interpupillaryDistance = 0.0640000030;
  9849. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9850. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9851. result.postProcessScaleFactor = 1.714605507808412;
  9852. result.lensCenterOffset = 0.151976421;
  9853. return result;
  9854. };
  9855. return VRCameraMetrics;
  9856. })();
  9857. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9858. var Camera = (function (_super) {
  9859. __extends(Camera, _super);
  9860. function Camera(name, position, scene) {
  9861. _super.call(this, name, scene);
  9862. this.position = position;
  9863. // Members
  9864. this.upVector = BABYLON.Vector3.Up();
  9865. this.orthoLeft = null;
  9866. this.orthoRight = null;
  9867. this.orthoBottom = null;
  9868. this.orthoTop = null;
  9869. this.fov = 0.8;
  9870. this.minZ = 1.0;
  9871. this.maxZ = 10000.0;
  9872. this.inertia = 0.9;
  9873. this.mode = Camera.PERSPECTIVE_CAMERA;
  9874. this.isIntermediate = false;
  9875. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9876. this.layerMask = 0x0FFFFFFF;
  9877. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9878. // Camera rig members
  9879. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9880. this._rigCameras = new Array();
  9881. // Cache
  9882. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9883. this._projectionMatrix = new BABYLON.Matrix();
  9884. this._postProcesses = new Array();
  9885. this._postProcessesTakenIndices = [];
  9886. this._activeMeshes = new BABYLON.SmartArray(256);
  9887. this._globalPosition = BABYLON.Vector3.Zero();
  9888. scene.addCamera(this);
  9889. if (!scene.activeCamera) {
  9890. scene.activeCamera = this;
  9891. }
  9892. }
  9893. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9894. get: function () {
  9895. return Camera._PERSPECTIVE_CAMERA;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9901. get: function () {
  9902. return Camera._ORTHOGRAPHIC_CAMERA;
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9908. get: function () {
  9909. return Camera._FOVMODE_VERTICAL_FIXED;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9915. get: function () {
  9916. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9922. get: function () {
  9923. return Camera._RIG_MODE_NONE;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9929. get: function () {
  9930. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9936. get: function () {
  9937. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9943. get: function () {
  9944. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9950. get: function () {
  9951. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9957. get: function () {
  9958. return Camera._RIG_MODE_VR;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Object.defineProperty(Camera.prototype, "globalPosition", {
  9964. get: function () {
  9965. return this._globalPosition;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Camera.prototype.getActiveMeshes = function () {
  9971. return this._activeMeshes;
  9972. };
  9973. Camera.prototype.isActiveMesh = function (mesh) {
  9974. return (this._activeMeshes.indexOf(mesh) !== -1);
  9975. };
  9976. //Cache
  9977. Camera.prototype._initCache = function () {
  9978. _super.prototype._initCache.call(this);
  9979. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9980. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9981. this._cache.mode = undefined;
  9982. this._cache.minZ = undefined;
  9983. this._cache.maxZ = undefined;
  9984. this._cache.fov = undefined;
  9985. this._cache.aspectRatio = undefined;
  9986. this._cache.orthoLeft = undefined;
  9987. this._cache.orthoRight = undefined;
  9988. this._cache.orthoBottom = undefined;
  9989. this._cache.orthoTop = undefined;
  9990. this._cache.renderWidth = undefined;
  9991. this._cache.renderHeight = undefined;
  9992. };
  9993. Camera.prototype._updateCache = function (ignoreParentClass) {
  9994. if (!ignoreParentClass) {
  9995. _super.prototype._updateCache.call(this);
  9996. }
  9997. var engine = this.getEngine();
  9998. this._cache.position.copyFrom(this.position);
  9999. this._cache.upVector.copyFrom(this.upVector);
  10000. this._cache.mode = this.mode;
  10001. this._cache.minZ = this.minZ;
  10002. this._cache.maxZ = this.maxZ;
  10003. this._cache.fov = this.fov;
  10004. this._cache.aspectRatio = engine.getAspectRatio(this);
  10005. this._cache.orthoLeft = this.orthoLeft;
  10006. this._cache.orthoRight = this.orthoRight;
  10007. this._cache.orthoBottom = this.orthoBottom;
  10008. this._cache.orthoTop = this.orthoTop;
  10009. this._cache.renderWidth = engine.getRenderWidth();
  10010. this._cache.renderHeight = engine.getRenderHeight();
  10011. };
  10012. Camera.prototype._updateFromScene = function () {
  10013. this.updateCache();
  10014. this._update();
  10015. };
  10016. // Synchronized
  10017. Camera.prototype._isSynchronized = function () {
  10018. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10019. };
  10020. Camera.prototype._isSynchronizedViewMatrix = function () {
  10021. if (!_super.prototype._isSynchronized.call(this))
  10022. return false;
  10023. return this._cache.position.equals(this.position)
  10024. && this._cache.upVector.equals(this.upVector)
  10025. && this.isSynchronizedWithParent();
  10026. };
  10027. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10028. var check = this._cache.mode === this.mode
  10029. && this._cache.minZ === this.minZ
  10030. && this._cache.maxZ === this.maxZ;
  10031. if (!check) {
  10032. return false;
  10033. }
  10034. var engine = this.getEngine();
  10035. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10036. check = this._cache.fov === this.fov
  10037. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10038. }
  10039. else {
  10040. check = this._cache.orthoLeft === this.orthoLeft
  10041. && this._cache.orthoRight === this.orthoRight
  10042. && this._cache.orthoBottom === this.orthoBottom
  10043. && this._cache.orthoTop === this.orthoTop
  10044. && this._cache.renderWidth === engine.getRenderWidth()
  10045. && this._cache.renderHeight === engine.getRenderHeight();
  10046. }
  10047. return check;
  10048. };
  10049. // Controls
  10050. Camera.prototype.attachControl = function (element) {
  10051. };
  10052. Camera.prototype.detachControl = function (element) {
  10053. };
  10054. Camera.prototype._update = function () {
  10055. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10056. this._updateRigCameras();
  10057. }
  10058. this._checkInputs();
  10059. };
  10060. Camera.prototype._checkInputs = function () {
  10061. };
  10062. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10063. if (insertAt === void 0) { insertAt = null; }
  10064. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10065. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10066. return 0;
  10067. }
  10068. if (insertAt == null || insertAt < 0) {
  10069. this._postProcesses.push(postProcess);
  10070. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10071. return this._postProcesses.length - 1;
  10072. }
  10073. var add = 0;
  10074. var i;
  10075. var start;
  10076. if (this._postProcesses[insertAt]) {
  10077. start = this._postProcesses.length - 1;
  10078. for (i = start; i >= insertAt + 1; --i) {
  10079. this._postProcesses[i + 1] = this._postProcesses[i];
  10080. }
  10081. add = 1;
  10082. }
  10083. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10084. if (this._postProcessesTakenIndices[i] < insertAt) {
  10085. continue;
  10086. }
  10087. start = this._postProcessesTakenIndices.length - 1;
  10088. for (var j = start; j >= i; --j) {
  10089. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10090. }
  10091. this._postProcessesTakenIndices[i] = insertAt;
  10092. break;
  10093. }
  10094. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10095. this._postProcessesTakenIndices.push(insertAt);
  10096. }
  10097. var result = insertAt + add;
  10098. this._postProcesses[result] = postProcess;
  10099. return result;
  10100. };
  10101. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10102. if (atIndices === void 0) { atIndices = null; }
  10103. var result = [];
  10104. var i;
  10105. var index;
  10106. if (!atIndices) {
  10107. var length = this._postProcesses.length;
  10108. for (i = 0; i < length; i++) {
  10109. if (this._postProcesses[i] !== postProcess) {
  10110. continue;
  10111. }
  10112. delete this._postProcesses[i];
  10113. index = this._postProcessesTakenIndices.indexOf(i);
  10114. this._postProcessesTakenIndices.splice(index, 1);
  10115. }
  10116. }
  10117. else {
  10118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10119. for (i = 0; i < atIndices.length; i++) {
  10120. var foundPostProcess = this._postProcesses[atIndices[i]];
  10121. if (foundPostProcess !== postProcess) {
  10122. result.push(i);
  10123. continue;
  10124. }
  10125. delete this._postProcesses[atIndices[i]];
  10126. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10127. this._postProcessesTakenIndices.splice(index, 1);
  10128. }
  10129. }
  10130. return result;
  10131. };
  10132. Camera.prototype.getWorldMatrix = function () {
  10133. if (!this._worldMatrix) {
  10134. this._worldMatrix = BABYLON.Matrix.Identity();
  10135. }
  10136. var viewMatrix = this.getViewMatrix();
  10137. viewMatrix.invertToRef(this._worldMatrix);
  10138. return this._worldMatrix;
  10139. };
  10140. Camera.prototype._getViewMatrix = function () {
  10141. return BABYLON.Matrix.Identity();
  10142. };
  10143. Camera.prototype.getViewMatrix = function (force) {
  10144. this._computedViewMatrix = this._computeViewMatrix(force);
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. if (!this.parent || !this.parent.getWorldMatrix) {
  10149. this._globalPosition.copyFrom(this.position);
  10150. }
  10151. else {
  10152. if (!this._worldMatrix) {
  10153. this._worldMatrix = BABYLON.Matrix.Identity();
  10154. }
  10155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10158. this._computedViewMatrix.invert();
  10159. this._markSyncedWithParent();
  10160. }
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. return this._computedViewMatrix;
  10163. };
  10164. Camera.prototype._computeViewMatrix = function (force) {
  10165. if (!force && this._isSynchronizedViewMatrix()) {
  10166. return this._computedViewMatrix;
  10167. }
  10168. this._computedViewMatrix = this._getViewMatrix();
  10169. this._currentRenderId = this.getScene().getRenderId();
  10170. return this._computedViewMatrix;
  10171. };
  10172. Camera.prototype.getProjectionMatrix = function (force) {
  10173. if (!force && this._isSynchronizedProjectionMatrix()) {
  10174. return this._projectionMatrix;
  10175. }
  10176. var engine = this.getEngine();
  10177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10178. if (this.minZ <= 0) {
  10179. this.minZ = 0.1;
  10180. }
  10181. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10182. return this._projectionMatrix;
  10183. }
  10184. var halfWidth = engine.getRenderWidth() / 2.0;
  10185. var halfHeight = engine.getRenderHeight() / 2.0;
  10186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10187. return this._projectionMatrix;
  10188. };
  10189. Camera.prototype.dispose = function () {
  10190. // Animations
  10191. this.getScene().stopAnimation(this);
  10192. // Remove from scene
  10193. this.getScene().removeCamera(this);
  10194. while (this._rigCameras.length > 0) {
  10195. this._rigCameras.pop().dispose();
  10196. }
  10197. // Postprocesses
  10198. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10199. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10200. }
  10201. };
  10202. // ---- Camera rigs section ----
  10203. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10204. while (this._rigCameras.length > 0) {
  10205. this._rigCameras.pop().dispose();
  10206. }
  10207. this.cameraRigMode = mode;
  10208. this._cameraRigParams = {};
  10209. switch (this.cameraRigMode) {
  10210. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10212. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10213. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10214. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10215. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10216. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10217. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10218. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10219. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10220. break;
  10221. }
  10222. var postProcesses = new Array();
  10223. switch (this.cameraRigMode) {
  10224. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10225. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10226. this._rigCameras[0].isIntermediate = true;
  10227. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10228. postProcesses[1].onApply = function (effect) {
  10229. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10230. };
  10231. break;
  10232. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10233. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10234. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10235. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10236. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10237. var secondCamIndex = 1 - firstCamIndex;
  10238. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10239. this._rigCameras[firstCamIndex].isIntermediate = true;
  10240. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10241. break;
  10242. case Camera.RIG_MODE_VR:
  10243. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10244. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10245. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10246. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10247. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10248. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10249. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10250. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10251. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10252. if (metrics.compensateDistortion) {
  10253. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10254. }
  10255. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10256. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10257. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10258. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10259. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10260. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10261. if (metrics.compensateDistortion) {
  10262. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10263. }
  10264. break;
  10265. }
  10266. this._update();
  10267. };
  10268. Camera.prototype._getVRProjectionMatrix = function () {
  10269. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10270. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10271. return this._projectionMatrix;
  10272. };
  10273. Camera.prototype.setCameraRigParameter = function (name, value) {
  10274. this._cameraRigParams[name] = value;
  10275. //provisionnally:
  10276. if (name === "interaxialDistance") {
  10277. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10278. }
  10279. };
  10280. /**
  10281. * May needs to be overridden by children so sub has required properties to be copied
  10282. */
  10283. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10284. return null;
  10285. };
  10286. /**
  10287. * May needs to be overridden by children
  10288. */
  10289. Camera.prototype._updateRigCameras = function () {
  10290. for (var i = 0; i < this._rigCameras.length; i++) {
  10291. this._rigCameras[i].minZ = this.minZ;
  10292. this._rigCameras[i].maxZ = this.maxZ;
  10293. this._rigCameras[i].fov = this.fov;
  10294. }
  10295. // only update viewport when ANAGLYPH
  10296. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10297. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10298. }
  10299. };
  10300. Camera.prototype.serialize = function () {
  10301. var serializationObject = {};
  10302. serializationObject.name = this.name;
  10303. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10304. serializationObject.id = this.id;
  10305. serializationObject.position = this.position.asArray();
  10306. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10307. // Parent
  10308. if (this.parent) {
  10309. serializationObject.parentId = this.parent.id;
  10310. }
  10311. serializationObject.fov = this.fov;
  10312. serializationObject.minZ = this.minZ;
  10313. serializationObject.maxZ = this.maxZ;
  10314. serializationObject.inertia = this.inertia;
  10315. // Animations
  10316. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10317. // Layer mask
  10318. serializationObject.layerMask = this.layerMask;
  10319. return serializationObject;
  10320. };
  10321. Camera.Parse = function (parsedCamera, scene) {
  10322. var camera;
  10323. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10324. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10325. var interaxial_distance;
  10326. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10327. var alpha = parsedCamera.alpha;
  10328. var beta = parsedCamera.beta;
  10329. var radius = parsedCamera.radius;
  10330. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10331. interaxial_distance = parsedCamera.interaxial_distance;
  10332. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10333. }
  10334. else {
  10335. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10336. }
  10337. }
  10338. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10339. interaxial_distance = parsedCamera.interaxial_distance;
  10340. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10341. }
  10342. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10343. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10344. }
  10345. else if (parsedCamera.type === "FollowCamera") {
  10346. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10347. camera.heightOffset = parsedCamera.heightOffset;
  10348. camera.radius = parsedCamera.radius;
  10349. camera.rotationOffset = parsedCamera.rotationOffset;
  10350. if (lockedTargetMesh)
  10351. camera.target = lockedTargetMesh;
  10352. }
  10353. else if (parsedCamera.type === "GamepadCamera") {
  10354. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10355. }
  10356. else if (parsedCamera.type === "TouchCamera") {
  10357. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10358. }
  10359. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10360. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10361. }
  10362. else if (parsedCamera.type === "WebVRFreeCamera") {
  10363. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10364. }
  10365. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10366. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10367. }
  10368. else {
  10369. // Free Camera is the default value
  10370. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10371. }
  10372. // apply 3d rig, when found
  10373. if (parsedCamera.cameraRigMode) {
  10374. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10375. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10376. }
  10377. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10378. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10379. camera.lockedTarget = lockedTargetMesh;
  10380. }
  10381. camera.id = parsedCamera.id;
  10382. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10383. // Parent
  10384. if (parsedCamera.parentId) {
  10385. camera._waitingParentId = parsedCamera.parentId;
  10386. }
  10387. // Target
  10388. if (parsedCamera.target) {
  10389. if (camera.setTarget) {
  10390. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10391. }
  10392. else {
  10393. //For ArcRotate
  10394. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10395. }
  10396. }
  10397. else {
  10398. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10399. }
  10400. camera.fov = parsedCamera.fov;
  10401. camera.minZ = parsedCamera.minZ;
  10402. camera.maxZ = parsedCamera.maxZ;
  10403. camera.speed = parsedCamera.speed;
  10404. camera.inertia = parsedCamera.inertia;
  10405. camera.checkCollisions = parsedCamera.checkCollisions;
  10406. camera.applyGravity = parsedCamera.applyGravity;
  10407. if (parsedCamera.ellipsoid) {
  10408. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10409. }
  10410. // Animations
  10411. if (parsedCamera.animations) {
  10412. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10413. var parsedAnimation = parsedCamera.animations[animationIndex];
  10414. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10415. }
  10416. }
  10417. if (parsedCamera.autoAnimate) {
  10418. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10419. }
  10420. // Layer Mask
  10421. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10422. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10423. }
  10424. else {
  10425. camera.layerMask = 0x0FFFFFFF;
  10426. }
  10427. return camera;
  10428. };
  10429. // Statics
  10430. Camera._PERSPECTIVE_CAMERA = 0;
  10431. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10432. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10433. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10434. Camera._RIG_MODE_NONE = 0;
  10435. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10436. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10437. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10438. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10439. Camera._RIG_MODE_VR = 20;
  10440. return Camera;
  10441. })(BABYLON.Node);
  10442. BABYLON.Camera = Camera;
  10443. })(BABYLON || (BABYLON = {}));
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. var TargetCamera = (function (_super) {
  10447. __extends(TargetCamera, _super);
  10448. function TargetCamera(name, position, scene) {
  10449. _super.call(this, name, position, scene);
  10450. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10451. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10452. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10453. this.speed = 2.0;
  10454. this.noRotationConstraint = false;
  10455. this.lockedTarget = null;
  10456. this._currentTarget = BABYLON.Vector3.Zero();
  10457. this._viewMatrix = BABYLON.Matrix.Zero();
  10458. this._camMatrix = BABYLON.Matrix.Zero();
  10459. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10460. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10461. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10462. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10463. this._lookAtTemp = BABYLON.Matrix.Zero();
  10464. this._tempMatrix = BABYLON.Matrix.Zero();
  10465. }
  10466. TargetCamera.prototype.getFrontPosition = function (distance) {
  10467. var direction = this.getTarget().subtract(this.position);
  10468. direction.normalize();
  10469. direction.scaleInPlace(distance);
  10470. return this.globalPosition.add(direction);
  10471. };
  10472. TargetCamera.prototype._getLockedTargetPosition = function () {
  10473. if (!this.lockedTarget) {
  10474. return null;
  10475. }
  10476. return this.lockedTarget.position || this.lockedTarget;
  10477. };
  10478. // Cache
  10479. TargetCamera.prototype._initCache = function () {
  10480. _super.prototype._initCache.call(this);
  10481. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10482. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10483. };
  10484. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10485. if (!ignoreParentClass) {
  10486. _super.prototype._updateCache.call(this);
  10487. }
  10488. var lockedTargetPosition = this._getLockedTargetPosition();
  10489. if (!lockedTargetPosition) {
  10490. this._cache.lockedTarget = null;
  10491. }
  10492. else {
  10493. if (!this._cache.lockedTarget) {
  10494. this._cache.lockedTarget = lockedTargetPosition.clone();
  10495. }
  10496. else {
  10497. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10498. }
  10499. }
  10500. this._cache.rotation.copyFrom(this.rotation);
  10501. };
  10502. // Synchronized
  10503. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10504. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10505. return false;
  10506. }
  10507. var lockedTargetPosition = this._getLockedTargetPosition();
  10508. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10509. && this._cache.rotation.equals(this.rotation);
  10510. };
  10511. // Methods
  10512. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10513. var engine = this.getEngine();
  10514. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10515. };
  10516. // Target
  10517. TargetCamera.prototype.setTarget = function (target) {
  10518. this.upVector.normalize();
  10519. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10520. this._camMatrix.invert();
  10521. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10522. var vDir = target.subtract(this.position);
  10523. if (vDir.x >= 0.0) {
  10524. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10525. }
  10526. else {
  10527. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10528. }
  10529. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10530. if (isNaN(this.rotation.x)) {
  10531. this.rotation.x = 0;
  10532. }
  10533. if (isNaN(this.rotation.y)) {
  10534. this.rotation.y = 0;
  10535. }
  10536. if (isNaN(this.rotation.z)) {
  10537. this.rotation.z = 0;
  10538. }
  10539. };
  10540. TargetCamera.prototype.getTarget = function () {
  10541. return this._currentTarget;
  10542. };
  10543. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10544. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10545. };
  10546. TargetCamera.prototype._updatePosition = function () {
  10547. this.position.addInPlace(this.cameraDirection);
  10548. };
  10549. TargetCamera.prototype._checkInputs = function () {
  10550. var needToMove = this._decideIfNeedsToMove();
  10551. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10552. // Move
  10553. if (needToMove) {
  10554. this._updatePosition();
  10555. }
  10556. // Rotate
  10557. if (needToRotate) {
  10558. this.rotation.x += this.cameraRotation.x;
  10559. this.rotation.y += this.cameraRotation.y;
  10560. if (!this.noRotationConstraint) {
  10561. var limit = (Math.PI / 2) * 0.95;
  10562. if (this.rotation.x > limit)
  10563. this.rotation.x = limit;
  10564. if (this.rotation.x < -limit)
  10565. this.rotation.x = -limit;
  10566. }
  10567. }
  10568. // Inertia
  10569. if (needToMove) {
  10570. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10571. this.cameraDirection.x = 0;
  10572. }
  10573. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10574. this.cameraDirection.y = 0;
  10575. }
  10576. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10577. this.cameraDirection.z = 0;
  10578. }
  10579. this.cameraDirection.scaleInPlace(this.inertia);
  10580. }
  10581. if (needToRotate) {
  10582. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10583. this.cameraRotation.x = 0;
  10584. }
  10585. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10586. this.cameraRotation.y = 0;
  10587. }
  10588. this.cameraRotation.scaleInPlace(this.inertia);
  10589. }
  10590. _super.prototype._checkInputs.call(this);
  10591. };
  10592. TargetCamera.prototype._getViewMatrix = function () {
  10593. if (!this.lockedTarget) {
  10594. // Compute
  10595. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10596. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10597. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10598. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10599. this._lookAtTemp.invert();
  10600. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10601. }
  10602. else {
  10603. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10604. }
  10605. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10606. // Computing target and final matrix
  10607. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10608. }
  10609. else {
  10610. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10611. }
  10612. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10613. return this._viewMatrix;
  10614. };
  10615. TargetCamera.prototype._getVRViewMatrix = function () {
  10616. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10617. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10618. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10619. // Computing target and final matrix
  10620. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10621. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10622. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10623. return this._viewMatrix;
  10624. };
  10625. /**
  10626. * @override
  10627. * Override Camera.createRigCamera
  10628. */
  10629. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10630. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10631. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10632. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10633. rigCamera._cameraRigParams = {};
  10634. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10635. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10636. }
  10637. return rigCamera;
  10638. }
  10639. return null;
  10640. };
  10641. /**
  10642. * @override
  10643. * Override Camera._updateRigCameras
  10644. */
  10645. TargetCamera.prototype._updateRigCameras = function () {
  10646. switch (this.cameraRigMode) {
  10647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10651. case BABYLON.Camera.RIG_MODE_VR:
  10652. var camLeft = this._rigCameras[0];
  10653. var camRight = this._rigCameras[1];
  10654. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10655. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10656. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10657. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10658. camLeft.position.copyFrom(this.position);
  10659. camRight.position.copyFrom(this.position);
  10660. }
  10661. else {
  10662. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10663. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10664. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10665. camLeft.setTarget(this.getTarget());
  10666. camRight.setTarget(this.getTarget());
  10667. }
  10668. break;
  10669. }
  10670. _super.prototype._updateRigCameras.call(this);
  10671. };
  10672. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10673. if (!this._rigCamTransformMatrix) {
  10674. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10675. }
  10676. var target = this.getTarget();
  10677. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10678. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10679. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10680. };
  10681. TargetCamera.prototype.serialize = function () {
  10682. var serializationObject = _super.prototype.serialize.call(this);
  10683. serializationObject.speed = this.speed;
  10684. if (this.rotation) {
  10685. serializationObject.rotation = this.rotation.asArray();
  10686. }
  10687. if (this.lockedTarget && this.lockedTarget.id) {
  10688. serializationObject.lockedTargetId = this.lockedTarget.id;
  10689. }
  10690. return serializationObject;
  10691. };
  10692. return TargetCamera;
  10693. })(BABYLON.Camera);
  10694. BABYLON.TargetCamera = TargetCamera;
  10695. })(BABYLON || (BABYLON = {}));
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. var FreeCamera = (function (_super) {
  10699. __extends(FreeCamera, _super);
  10700. function FreeCamera(name, position, scene) {
  10701. var _this = this;
  10702. _super.call(this, name, position, scene);
  10703. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10704. this.keysUp = [38];
  10705. this.keysDown = [40];
  10706. this.keysLeft = [37];
  10707. this.keysRight = [39];
  10708. this.checkCollisions = false;
  10709. this.applyGravity = false;
  10710. this.angularSensibility = 2000.0;
  10711. this._keys = [];
  10712. this._collider = new BABYLON.Collider();
  10713. this._needMoveForGravity = false;
  10714. this._oldPosition = BABYLON.Vector3.Zero();
  10715. this._diffPosition = BABYLON.Vector3.Zero();
  10716. this._newPosition = BABYLON.Vector3.Zero();
  10717. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10718. if (collidedMesh === void 0) { collidedMesh = null; }
  10719. //TODO move this to the collision coordinator!
  10720. if (_this.getScene().workerCollisions)
  10721. newPosition.multiplyInPlace(_this._collider.radius);
  10722. var updatePosition = function (newPos) {
  10723. _this._newPosition.copyFrom(newPos);
  10724. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10725. var oldPosition = _this.position.clone();
  10726. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10727. _this.position.addInPlace(_this._diffPosition);
  10728. if (_this.onCollide && collidedMesh) {
  10729. _this.onCollide(collidedMesh);
  10730. }
  10731. }
  10732. };
  10733. updatePosition(newPosition);
  10734. };
  10735. }
  10736. // Controls
  10737. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10738. var _this = this;
  10739. var previousPosition;
  10740. var engine = this.getEngine();
  10741. if (this._attachedElement) {
  10742. return;
  10743. }
  10744. this._attachedElement = element;
  10745. if (this._onMouseDown === undefined) {
  10746. this._onMouseDown = function (evt) {
  10747. previousPosition = {
  10748. x: evt.clientX,
  10749. y: evt.clientY
  10750. };
  10751. if (!noPreventDefault) {
  10752. evt.preventDefault();
  10753. }
  10754. };
  10755. this._onMouseUp = function (evt) {
  10756. previousPosition = null;
  10757. if (!noPreventDefault) {
  10758. evt.preventDefault();
  10759. }
  10760. };
  10761. this._onMouseOut = function (evt) {
  10762. previousPosition = null;
  10763. _this._keys = [];
  10764. if (!noPreventDefault) {
  10765. evt.preventDefault();
  10766. }
  10767. };
  10768. this._onMouseMove = function (evt) {
  10769. if (!previousPosition && !engine.isPointerLock) {
  10770. return;
  10771. }
  10772. var offsetX;
  10773. var offsetY;
  10774. if (!engine.isPointerLock) {
  10775. offsetX = evt.clientX - previousPosition.x;
  10776. offsetY = evt.clientY - previousPosition.y;
  10777. }
  10778. else {
  10779. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10780. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10781. }
  10782. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10783. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10784. previousPosition = {
  10785. x: evt.clientX,
  10786. y: evt.clientY
  10787. };
  10788. if (!noPreventDefault) {
  10789. evt.preventDefault();
  10790. }
  10791. };
  10792. this._onKeyDown = function (evt) {
  10793. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10794. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10795. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10796. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10797. var index = _this._keys.indexOf(evt.keyCode);
  10798. if (index === -1) {
  10799. _this._keys.push(evt.keyCode);
  10800. }
  10801. if (!noPreventDefault) {
  10802. evt.preventDefault();
  10803. }
  10804. }
  10805. };
  10806. this._onKeyUp = function (evt) {
  10807. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10808. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10809. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10810. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10811. var index = _this._keys.indexOf(evt.keyCode);
  10812. if (index >= 0) {
  10813. _this._keys.splice(index, 1);
  10814. }
  10815. if (!noPreventDefault) {
  10816. evt.preventDefault();
  10817. }
  10818. }
  10819. };
  10820. this._onLostFocus = function () {
  10821. _this._keys = [];
  10822. };
  10823. this._reset = function () {
  10824. _this._keys = [];
  10825. previousPosition = null;
  10826. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10827. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10828. };
  10829. }
  10830. element.addEventListener("mousedown", this._onMouseDown, false);
  10831. element.addEventListener("mouseup", this._onMouseUp, false);
  10832. element.addEventListener("mouseout", this._onMouseOut, false);
  10833. element.addEventListener("mousemove", this._onMouseMove, false);
  10834. BABYLON.Tools.RegisterTopRootEvents([
  10835. { name: "keydown", handler: this._onKeyDown },
  10836. { name: "keyup", handler: this._onKeyUp },
  10837. { name: "blur", handler: this._onLostFocus }
  10838. ]);
  10839. };
  10840. FreeCamera.prototype.detachControl = function (element) {
  10841. if (this._attachedElement !== element) {
  10842. return;
  10843. }
  10844. element.removeEventListener("mousedown", this._onMouseDown);
  10845. element.removeEventListener("mouseup", this._onMouseUp);
  10846. element.removeEventListener("mouseout", this._onMouseOut);
  10847. element.removeEventListener("mousemove", this._onMouseMove);
  10848. BABYLON.Tools.UnregisterTopRootEvents([
  10849. { name: "keydown", handler: this._onKeyDown },
  10850. { name: "keyup", handler: this._onKeyUp },
  10851. { name: "blur", handler: this._onLostFocus }
  10852. ]);
  10853. this._attachedElement = null;
  10854. if (this._reset) {
  10855. this._reset();
  10856. }
  10857. };
  10858. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10859. var globalPosition;
  10860. if (this.parent) {
  10861. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10862. }
  10863. else {
  10864. globalPosition = this.position;
  10865. }
  10866. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10867. this._collider.radius = this.ellipsoid;
  10868. //no need for clone, as long as gravity is not on.
  10869. var actualVelocity = velocity;
  10870. //add gravity to the velocity to prevent the dual-collision checking
  10871. if (this.applyGravity) {
  10872. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10873. actualVelocity = velocity.add(this.getScene().gravity);
  10874. }
  10875. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10876. };
  10877. FreeCamera.prototype._checkInputs = function () {
  10878. if (!this._localDirection) {
  10879. this._localDirection = BABYLON.Vector3.Zero();
  10880. this._transformedDirection = BABYLON.Vector3.Zero();
  10881. }
  10882. // Keyboard
  10883. for (var index = 0; index < this._keys.length; index++) {
  10884. var keyCode = this._keys[index];
  10885. var speed = this._computeLocalCameraSpeed();
  10886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10887. this._localDirection.copyFromFloats(-speed, 0, 0);
  10888. }
  10889. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10890. this._localDirection.copyFromFloats(0, 0, speed);
  10891. }
  10892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10893. this._localDirection.copyFromFloats(speed, 0, 0);
  10894. }
  10895. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10896. this._localDirection.copyFromFloats(0, 0, -speed);
  10897. }
  10898. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10899. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10900. this.cameraDirection.addInPlace(this._transformedDirection);
  10901. }
  10902. _super.prototype._checkInputs.call(this);
  10903. };
  10904. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10905. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10906. };
  10907. FreeCamera.prototype._updatePosition = function () {
  10908. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10909. this._collideWithWorld(this.cameraDirection);
  10910. }
  10911. else {
  10912. this.position.addInPlace(this.cameraDirection);
  10913. }
  10914. };
  10915. FreeCamera.prototype.serialize = function () {
  10916. var serializationObject = _super.prototype.serialize.call(this);
  10917. serializationObject.checkCollisions = this.checkCollisions;
  10918. serializationObject.applyGravity = this.applyGravity;
  10919. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10920. return serializationObject;
  10921. };
  10922. return FreeCamera;
  10923. })(BABYLON.TargetCamera);
  10924. BABYLON.FreeCamera = FreeCamera;
  10925. })(BABYLON || (BABYLON = {}));
  10926. var BABYLON;
  10927. (function (BABYLON) {
  10928. var FollowCamera = (function (_super) {
  10929. __extends(FollowCamera, _super);
  10930. function FollowCamera(name, position, scene) {
  10931. _super.call(this, name, position, scene);
  10932. this.radius = 12;
  10933. this.rotationOffset = 0;
  10934. this.heightOffset = 4;
  10935. this.cameraAcceleration = 0.05;
  10936. this.maxCameraSpeed = 20;
  10937. }
  10938. FollowCamera.prototype.getRadians = function (degrees) {
  10939. return degrees * Math.PI / 180;
  10940. };
  10941. FollowCamera.prototype.follow = function (cameraTarget) {
  10942. if (!cameraTarget)
  10943. return;
  10944. var yRotation;
  10945. if (cameraTarget.rotationQuaternion) {
  10946. var rotMatrix = new BABYLON.Matrix();
  10947. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10948. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10949. }
  10950. else {
  10951. yRotation = cameraTarget.rotation.y;
  10952. }
  10953. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10954. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10955. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10956. var dx = targetX - this.position.x;
  10957. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10958. var dz = (targetZ) - this.position.z;
  10959. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10960. var vy = dy * this.cameraAcceleration;
  10961. var vz = dz * this.cameraAcceleration * 2;
  10962. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10963. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10964. }
  10965. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10966. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10967. }
  10968. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10969. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10970. }
  10971. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10972. this.setTarget(cameraTarget.position);
  10973. };
  10974. FollowCamera.prototype._checkInputs = function () {
  10975. _super.prototype._checkInputs.call(this);
  10976. this.follow(this.target);
  10977. };
  10978. FollowCamera.prototype.serialize = function () {
  10979. var serializationObject = _super.prototype.serialize.call(this);
  10980. serializationObject.radius = this.radius;
  10981. serializationObject.heightOffset = this.heightOffset;
  10982. serializationObject.rotationOffset = this.rotationOffset;
  10983. return serializationObject;
  10984. };
  10985. return FollowCamera;
  10986. })(BABYLON.TargetCamera);
  10987. BABYLON.FollowCamera = FollowCamera;
  10988. var ArcFollowCamera = (function (_super) {
  10989. __extends(ArcFollowCamera, _super);
  10990. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10991. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10992. this.alpha = alpha;
  10993. this.beta = beta;
  10994. this.radius = radius;
  10995. this.target = target;
  10996. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10997. this.follow();
  10998. }
  10999. ArcFollowCamera.prototype.follow = function () {
  11000. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11001. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11002. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11003. this.position = this.target.position.add(this._cartesianCoordinates);
  11004. this.setTarget(this.target.position);
  11005. };
  11006. ArcFollowCamera.prototype._checkInputs = function () {
  11007. _super.prototype._checkInputs.call(this);
  11008. this.follow();
  11009. };
  11010. ArcFollowCamera.prototype.serialize = function () {
  11011. var serializationObject = _super.prototype.serialize.call(this);
  11012. serializationObject.radius = this.radius;
  11013. return serializationObject;
  11014. };
  11015. return ArcFollowCamera;
  11016. })(BABYLON.TargetCamera);
  11017. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11018. })(BABYLON || (BABYLON = {}));
  11019. var BABYLON;
  11020. (function (BABYLON) {
  11021. // We're mainly based on the logic defined into the FreeCamera code
  11022. var TouchCamera = (function (_super) {
  11023. __extends(TouchCamera, _super);
  11024. function TouchCamera(name, position, scene) {
  11025. _super.call(this, name, position, scene);
  11026. this._offsetX = null;
  11027. this._offsetY = null;
  11028. this._pointerCount = 0;
  11029. this._pointerPressed = [];
  11030. this.angularSensibility = 200000.0;
  11031. this.moveSensibility = 500.0;
  11032. }
  11033. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11034. var _this = this;
  11035. var previousPosition;
  11036. if (this._attachedCanvas) {
  11037. return;
  11038. }
  11039. this._attachedCanvas = canvas;
  11040. if (this._onPointerDown === undefined) {
  11041. this._onPointerDown = function (evt) {
  11042. if (!noPreventDefault) {
  11043. evt.preventDefault();
  11044. }
  11045. _this._pointerPressed.push(evt.pointerId);
  11046. if (_this._pointerPressed.length !== 1) {
  11047. return;
  11048. }
  11049. previousPosition = {
  11050. x: evt.clientX,
  11051. y: evt.clientY
  11052. };
  11053. };
  11054. this._onPointerUp = function (evt) {
  11055. if (!noPreventDefault) {
  11056. evt.preventDefault();
  11057. }
  11058. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11059. if (index === -1) {
  11060. return;
  11061. }
  11062. _this._pointerPressed.splice(index, 1);
  11063. if (index != 0) {
  11064. return;
  11065. }
  11066. previousPosition = null;
  11067. _this._offsetX = null;
  11068. _this._offsetY = null;
  11069. };
  11070. this._onPointerMove = function (evt) {
  11071. if (!noPreventDefault) {
  11072. evt.preventDefault();
  11073. }
  11074. if (!previousPosition) {
  11075. return;
  11076. }
  11077. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11078. if (index != 0) {
  11079. return;
  11080. }
  11081. _this._offsetX = evt.clientX - previousPosition.x;
  11082. _this._offsetY = -(evt.clientY - previousPosition.y);
  11083. };
  11084. this._onLostFocus = function () {
  11085. _this._offsetX = null;
  11086. _this._offsetY = null;
  11087. };
  11088. }
  11089. canvas.addEventListener("pointerdown", this._onPointerDown);
  11090. canvas.addEventListener("pointerup", this._onPointerUp);
  11091. canvas.addEventListener("pointerout", this._onPointerUp);
  11092. canvas.addEventListener("pointermove", this._onPointerMove);
  11093. BABYLON.Tools.RegisterTopRootEvents([
  11094. { name: "blur", handler: this._onLostFocus }
  11095. ]);
  11096. };
  11097. TouchCamera.prototype.detachControl = function (canvas) {
  11098. if (this._attachedCanvas !== canvas) {
  11099. return;
  11100. }
  11101. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11102. canvas.removeEventListener("pointerup", this._onPointerUp);
  11103. canvas.removeEventListener("pointerout", this._onPointerUp);
  11104. canvas.removeEventListener("pointermove", this._onPointerMove);
  11105. BABYLON.Tools.UnregisterTopRootEvents([
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. this._attachedCanvas = null;
  11109. };
  11110. TouchCamera.prototype._checkInputs = function () {
  11111. if (this._offsetX) {
  11112. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11113. if (this._pointerPressed.length > 1) {
  11114. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11115. }
  11116. else {
  11117. var speed = this._computeLocalCameraSpeed();
  11118. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11119. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11120. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11121. }
  11122. }
  11123. _super.prototype._checkInputs.call(this);
  11124. };
  11125. return TouchCamera;
  11126. })(BABYLON.FreeCamera);
  11127. BABYLON.TouchCamera = TouchCamera;
  11128. })(BABYLON || (BABYLON = {}));
  11129. var BABYLON;
  11130. (function (BABYLON) {
  11131. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11132. var ArcRotateCamera = (function (_super) {
  11133. __extends(ArcRotateCamera, _super);
  11134. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11135. var _this = this;
  11136. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11137. this.alpha = alpha;
  11138. this.beta = beta;
  11139. this.radius = radius;
  11140. this.target = target;
  11141. this.inertialAlphaOffset = 0;
  11142. this.inertialBetaOffset = 0;
  11143. this.inertialRadiusOffset = 0;
  11144. this.lowerAlphaLimit = null;
  11145. this.upperAlphaLimit = null;
  11146. this.lowerBetaLimit = 0.01;
  11147. this.upperBetaLimit = Math.PI;
  11148. this.lowerRadiusLimit = null;
  11149. this.upperRadiusLimit = null;
  11150. this.angularSensibilityX = 1000.0;
  11151. this.angularSensibilityY = 1000.0;
  11152. this.wheelPrecision = 3.0;
  11153. this.pinchPrecision = 2.0;
  11154. this.panningSensibility = 50.0;
  11155. this.inertialPanningX = 0;
  11156. this.inertialPanningY = 0;
  11157. this.keysUp = [38];
  11158. this.keysDown = [40];
  11159. this.keysLeft = [37];
  11160. this.keysRight = [39];
  11161. this.zoomOnFactor = 1;
  11162. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11163. this.pinchInwards = true;
  11164. this.allowUpsideDown = true;
  11165. this._keys = [];
  11166. this._viewMatrix = new BABYLON.Matrix();
  11167. this._isRightClick = false;
  11168. this._isCtrlPushed = false;
  11169. this.checkCollisions = false;
  11170. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11171. this._collider = new BABYLON.Collider();
  11172. this._previousPosition = BABYLON.Vector3.Zero();
  11173. this._collisionVelocity = BABYLON.Vector3.Zero();
  11174. this._newPosition = BABYLON.Vector3.Zero();
  11175. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11176. if (collidedMesh === void 0) { collidedMesh = null; }
  11177. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11178. newPosition.multiplyInPlace(_this._collider.radius);
  11179. }
  11180. if (!collidedMesh) {
  11181. _this._previousPosition.copyFrom(_this.position);
  11182. }
  11183. else {
  11184. _this.setPosition(newPosition);
  11185. if (_this.onCollide) {
  11186. _this.onCollide(collidedMesh);
  11187. }
  11188. }
  11189. // Recompute because of constraints
  11190. var cosa = Math.cos(_this.alpha);
  11191. var sina = Math.sin(_this.alpha);
  11192. var cosb = Math.cos(_this.beta);
  11193. var sinb = Math.sin(_this.beta);
  11194. var target = _this._getTargetPosition();
  11195. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11196. _this.position.copyFrom(_this._newPosition);
  11197. var up = _this.upVector;
  11198. if (_this.allowUpsideDown && _this.beta < 0) {
  11199. up = up.clone();
  11200. up = up.negate();
  11201. }
  11202. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11203. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11204. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11205. _this._collisionTriggered = false;
  11206. };
  11207. if (!this.target) {
  11208. this.target = BABYLON.Vector3.Zero();
  11209. }
  11210. this.getViewMatrix();
  11211. }
  11212. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11213. //deprecated angularSensibility support
  11214. get: function () {
  11215. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11216. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11217. },
  11218. //deprecated angularSensibility support
  11219. set: function (value) {
  11220. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11221. this.angularSensibilityX = value;
  11222. this.angularSensibilityY = value;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. ArcRotateCamera.prototype._getTargetPosition = function () {
  11228. return this.target.position || this.target;
  11229. };
  11230. // Cache
  11231. ArcRotateCamera.prototype._initCache = function () {
  11232. _super.prototype._initCache.call(this);
  11233. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11234. this._cache.alpha = undefined;
  11235. this._cache.beta = undefined;
  11236. this._cache.radius = undefined;
  11237. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11238. };
  11239. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11240. if (!ignoreParentClass) {
  11241. _super.prototype._updateCache.call(this);
  11242. }
  11243. this._cache.target.copyFrom(this._getTargetPosition());
  11244. this._cache.alpha = this.alpha;
  11245. this._cache.beta = this.beta;
  11246. this._cache.radius = this.radius;
  11247. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11248. };
  11249. // Synchronized
  11250. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11251. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11252. return false;
  11253. return this._cache.target.equals(this._getTargetPosition())
  11254. && this._cache.alpha === this.alpha
  11255. && this._cache.beta === this.beta
  11256. && this._cache.radius === this.radius
  11257. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11258. };
  11259. // Methods
  11260. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11261. var _this = this;
  11262. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11263. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11264. var previousPinchDistance = 0;
  11265. var pointers = new BABYLON.SmartCollection();
  11266. if (this._attachedElement) {
  11267. return;
  11268. }
  11269. this._attachedElement = element;
  11270. var engine = this.getEngine();
  11271. if (this._onPointerDown === undefined) {
  11272. this._onPointerDown = function (evt) {
  11273. // Manage panning with right click
  11274. _this._isRightClick = evt.button === 2;
  11275. // manage pointers
  11276. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11277. cacheSoloPointer = pointers.item(evt.pointerId);
  11278. if (!noPreventDefault) {
  11279. evt.preventDefault();
  11280. }
  11281. };
  11282. this._onPointerUp = function (evt) {
  11283. cacheSoloPointer = null;
  11284. previousPinchDistance = 0;
  11285. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11286. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11287. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11288. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11289. pointers.empty();
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onContextMenu = function (evt) {
  11295. evt.preventDefault();
  11296. };
  11297. this._onPointerMove = function (evt) {
  11298. if (!noPreventDefault) {
  11299. evt.preventDefault();
  11300. }
  11301. switch (pointers.count) {
  11302. case 1:
  11303. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11304. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11305. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11306. }
  11307. else {
  11308. var offsetX = evt.clientX - cacheSoloPointer.x;
  11309. var offsetY = evt.clientY - cacheSoloPointer.y;
  11310. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11311. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11312. }
  11313. cacheSoloPointer.x = evt.clientX;
  11314. cacheSoloPointer.y = evt.clientY;
  11315. break;
  11316. case 2:
  11317. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11318. pointers.item(evt.pointerId).x = evt.clientX;
  11319. pointers.item(evt.pointerId).y = evt.clientY;
  11320. var direction = _this.pinchInwards ? 1 : -1;
  11321. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11322. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11323. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11324. if (previousPinchDistance === 0) {
  11325. previousPinchDistance = pinchSquaredDistance;
  11326. return;
  11327. }
  11328. if (pinchSquaredDistance !== previousPinchDistance) {
  11329. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11330. previousPinchDistance = pinchSquaredDistance;
  11331. }
  11332. break;
  11333. default:
  11334. if (pointers.item(evt.pointerId)) {
  11335. pointers.item(evt.pointerId).x = evt.clientX;
  11336. pointers.item(evt.pointerId).y = evt.clientY;
  11337. }
  11338. }
  11339. };
  11340. this._onMouseMove = function (evt) {
  11341. if (!engine.isPointerLock) {
  11342. return;
  11343. }
  11344. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11345. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11346. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11347. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11348. if (!noPreventDefault) {
  11349. evt.preventDefault();
  11350. }
  11351. };
  11352. this._wheel = function (event) {
  11353. var delta = 0;
  11354. if (event.wheelDelta) {
  11355. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11356. }
  11357. else if (event.detail) {
  11358. delta = -event.detail / _this.wheelPrecision;
  11359. }
  11360. if (delta)
  11361. _this.inertialRadiusOffset += delta;
  11362. if (event.preventDefault) {
  11363. if (!noPreventDefault) {
  11364. event.preventDefault();
  11365. }
  11366. }
  11367. };
  11368. this._onKeyDown = function (evt) {
  11369. _this._isCtrlPushed = evt.ctrlKey;
  11370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11373. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11374. var index = _this._keys.indexOf(evt.keyCode);
  11375. if (index === -1) {
  11376. _this._keys.push(evt.keyCode);
  11377. }
  11378. if (evt.preventDefault) {
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. }
  11383. }
  11384. };
  11385. this._onKeyUp = function (evt) {
  11386. _this._isCtrlPushed = evt.ctrlKey;
  11387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11390. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11391. var index = _this._keys.indexOf(evt.keyCode);
  11392. if (index >= 0) {
  11393. _this._keys.splice(index, 1);
  11394. }
  11395. if (evt.preventDefault) {
  11396. if (!noPreventDefault) {
  11397. evt.preventDefault();
  11398. }
  11399. }
  11400. }
  11401. };
  11402. this._onLostFocus = function () {
  11403. _this._keys = [];
  11404. pointers.empty();
  11405. previousPinchDistance = 0;
  11406. cacheSoloPointer = null;
  11407. };
  11408. this._onGestureStart = function (e) {
  11409. if (window.MSGesture === undefined) {
  11410. return;
  11411. }
  11412. if (!_this._MSGestureHandler) {
  11413. _this._MSGestureHandler = new MSGesture();
  11414. _this._MSGestureHandler.target = element;
  11415. }
  11416. _this._MSGestureHandler.addPointer(e.pointerId);
  11417. };
  11418. this._onGesture = function (e) {
  11419. _this.radius *= e.scale;
  11420. if (e.preventDefault) {
  11421. if (!noPreventDefault) {
  11422. e.stopPropagation();
  11423. e.preventDefault();
  11424. }
  11425. }
  11426. };
  11427. this._reset = function () {
  11428. _this._keys = [];
  11429. _this.inertialAlphaOffset = 0;
  11430. _this.inertialBetaOffset = 0;
  11431. _this.inertialRadiusOffset = 0;
  11432. pointers.empty();
  11433. previousPinchDistance = 0;
  11434. cacheSoloPointer = null;
  11435. };
  11436. }
  11437. if (!useCtrlForPanning) {
  11438. element.addEventListener("contextmenu", this._onContextMenu, false);
  11439. }
  11440. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11441. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11442. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11443. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11444. element.addEventListener("mousemove", this._onMouseMove, false);
  11445. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11446. element.addEventListener("MSGestureChange", this._onGesture, false);
  11447. element.addEventListener('mousewheel', this._wheel, false);
  11448. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11449. BABYLON.Tools.RegisterTopRootEvents([
  11450. { name: "keydown", handler: this._onKeyDown },
  11451. { name: "keyup", handler: this._onKeyUp },
  11452. { name: "blur", handler: this._onLostFocus }
  11453. ]);
  11454. };
  11455. ArcRotateCamera.prototype.detachControl = function (element) {
  11456. if (this._attachedElement !== element) {
  11457. return;
  11458. }
  11459. element.removeEventListener("contextmenu", this._onContextMenu);
  11460. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11461. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11462. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11463. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11464. element.removeEventListener("mousemove", this._onMouseMove);
  11465. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11466. element.removeEventListener("MSGestureChange", this._onGesture);
  11467. element.removeEventListener('mousewheel', this._wheel);
  11468. element.removeEventListener('DOMMouseScroll', this._wheel);
  11469. BABYLON.Tools.UnregisterTopRootEvents([
  11470. { name: "keydown", handler: this._onKeyDown },
  11471. { name: "keyup", handler: this._onKeyUp },
  11472. { name: "blur", handler: this._onLostFocus }
  11473. ]);
  11474. this._MSGestureHandler = null;
  11475. this._attachedElement = null;
  11476. if (this._reset) {
  11477. this._reset();
  11478. }
  11479. };
  11480. ArcRotateCamera.prototype._checkInputs = function () {
  11481. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11482. if (this._collisionTriggered) {
  11483. return;
  11484. }
  11485. // Keyboard
  11486. for (var index = 0; index < this._keys.length; index++) {
  11487. var keyCode = this._keys[index];
  11488. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11489. this.inertialAlphaOffset -= 0.01;
  11490. }
  11491. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11492. this.inertialBetaOffset -= 0.01;
  11493. }
  11494. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11495. this.inertialAlphaOffset += 0.01;
  11496. }
  11497. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11498. this.inertialBetaOffset += 0.01;
  11499. }
  11500. }
  11501. // Inertia
  11502. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11503. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11504. this.beta += this.inertialBetaOffset;
  11505. this.radius -= this.inertialRadiusOffset;
  11506. this.inertialAlphaOffset *= this.inertia;
  11507. this.inertialBetaOffset *= this.inertia;
  11508. this.inertialRadiusOffset *= this.inertia;
  11509. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11510. this.inertialAlphaOffset = 0;
  11511. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11512. this.inertialBetaOffset = 0;
  11513. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11514. this.inertialRadiusOffset = 0;
  11515. }
  11516. // Panning inertia
  11517. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11518. if (!this._localDirection) {
  11519. this._localDirection = BABYLON.Vector3.Zero();
  11520. this._transformedDirection = BABYLON.Vector3.Zero();
  11521. }
  11522. this.inertialPanningX *= this.inertia;
  11523. this.inertialPanningY *= this.inertia;
  11524. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11525. this.inertialPanningX = 0;
  11526. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11527. this.inertialPanningY = 0;
  11528. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11529. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11530. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11531. this.target.addInPlace(this._transformedDirection);
  11532. }
  11533. // Limits
  11534. this._checkLimits();
  11535. _super.prototype._checkInputs.call(this);
  11536. };
  11537. ArcRotateCamera.prototype._checkLimits = function () {
  11538. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11539. if (this.allowUpsideDown && this.beta > Math.PI) {
  11540. this.beta = this.beta - (2 * Math.PI);
  11541. }
  11542. }
  11543. else {
  11544. if (this.beta < this.lowerBetaLimit) {
  11545. this.beta = this.lowerBetaLimit;
  11546. }
  11547. }
  11548. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11549. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11550. this.beta = this.beta + (2 * Math.PI);
  11551. }
  11552. }
  11553. else {
  11554. if (this.beta > this.upperBetaLimit) {
  11555. this.beta = this.upperBetaLimit;
  11556. }
  11557. }
  11558. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11559. this.alpha = this.lowerAlphaLimit;
  11560. }
  11561. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11562. this.alpha = this.upperAlphaLimit;
  11563. }
  11564. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11565. this.radius = this.lowerRadiusLimit;
  11566. }
  11567. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11568. this.radius = this.upperRadiusLimit;
  11569. }
  11570. };
  11571. ArcRotateCamera.prototype.setPosition = function (position) {
  11572. if (this.position.equals(position)) {
  11573. return;
  11574. }
  11575. var radiusv3 = position.subtract(this._getTargetPosition());
  11576. this.radius = radiusv3.length();
  11577. // Alpha
  11578. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11579. if (radiusv3.z < 0) {
  11580. this.alpha = 2 * Math.PI - this.alpha;
  11581. }
  11582. // Beta
  11583. this.beta = Math.acos(radiusv3.y / this.radius);
  11584. this._checkLimits();
  11585. };
  11586. ArcRotateCamera.prototype.setTarget = function (target) {
  11587. this.target = target;
  11588. };
  11589. ArcRotateCamera.prototype._getViewMatrix = function () {
  11590. // Compute
  11591. var cosa = Math.cos(this.alpha);
  11592. var sina = Math.sin(this.alpha);
  11593. var cosb = Math.cos(this.beta);
  11594. var sinb = Math.sin(this.beta);
  11595. var target = this._getTargetPosition();
  11596. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11597. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11598. this._collider.radius = this.collisionRadius;
  11599. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11600. this._collisionTriggered = true;
  11601. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11602. }
  11603. else {
  11604. this.position.copyFrom(this._newPosition);
  11605. var up = this.upVector;
  11606. if (this.allowUpsideDown && this.beta < 0) {
  11607. up = up.clone();
  11608. up = up.negate();
  11609. }
  11610. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11611. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11612. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11613. }
  11614. return this._viewMatrix;
  11615. };
  11616. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11617. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11618. meshes = meshes || this.getScene().meshes;
  11619. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11620. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11621. this.radius = distance * this.zoomOnFactor;
  11622. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11623. };
  11624. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11625. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11626. var meshesOrMinMaxVector;
  11627. var distance;
  11628. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11629. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11630. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11631. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11632. }
  11633. else {
  11634. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11635. distance = meshesOrMinMaxVectorAndDistance.distance;
  11636. }
  11637. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11638. if (!doNotUpdateMaxZ) {
  11639. this.maxZ = distance * 2;
  11640. }
  11641. };
  11642. /**
  11643. * @override
  11644. * Override Camera.createRigCamera
  11645. */
  11646. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11647. switch (this.cameraRigMode) {
  11648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11652. case BABYLON.Camera.RIG_MODE_VR:
  11653. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11654. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11655. }
  11656. return null;
  11657. };
  11658. /**
  11659. * @override
  11660. * Override Camera._updateRigCameras
  11661. */
  11662. ArcRotateCamera.prototype._updateRigCameras = function () {
  11663. switch (this.cameraRigMode) {
  11664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11668. case BABYLON.Camera.RIG_MODE_VR:
  11669. var camLeft = this._rigCameras[0];
  11670. var camRight = this._rigCameras[1];
  11671. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11672. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11673. camLeft.beta = camRight.beta = this.beta;
  11674. camLeft.radius = camRight.radius = this.radius;
  11675. break;
  11676. }
  11677. _super.prototype._updateRigCameras.call(this);
  11678. };
  11679. ArcRotateCamera.prototype.serialize = function () {
  11680. var serializationObject = _super.prototype.serialize.call(this);
  11681. if (this.target instanceof BABYLON.Vector3) {
  11682. serializationObject.target = this.target.asArray();
  11683. }
  11684. if (this.target && this.target.id) {
  11685. serializationObject.lockedTargetId = this.target.id;
  11686. }
  11687. serializationObject.checkCollisions = this.checkCollisions;
  11688. serializationObject.alpha = this.alpha;
  11689. serializationObject.beta = this.beta;
  11690. serializationObject.radius = this.radius;
  11691. return serializationObject;
  11692. };
  11693. return ArcRotateCamera;
  11694. })(BABYLON.TargetCamera);
  11695. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11696. })(BABYLON || (BABYLON = {}));
  11697. var BABYLON;
  11698. (function (BABYLON) {
  11699. var RenderingManager = (function () {
  11700. function RenderingManager(scene) {
  11701. this._renderingGroups = new Array();
  11702. this._scene = scene;
  11703. }
  11704. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11705. if (this._scene._activeParticleSystems.length === 0) {
  11706. return;
  11707. }
  11708. // Particles
  11709. var activeCamera = this._scene.activeCamera;
  11710. var beforeParticlesDate = BABYLON.Tools.Now;
  11711. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11712. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11713. if (particleSystem.renderingGroupId !== index) {
  11714. continue;
  11715. }
  11716. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11717. continue;
  11718. }
  11719. this._clearDepthBuffer();
  11720. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11721. this._scene._activeParticles += particleSystem.render();
  11722. }
  11723. }
  11724. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11725. };
  11726. RenderingManager.prototype._renderSprites = function (index) {
  11727. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11728. return;
  11729. }
  11730. // Sprites
  11731. var activeCamera = this._scene.activeCamera;
  11732. var beforeSpritessDate = BABYLON.Tools.Now;
  11733. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11734. var spriteManager = this._scene.spriteManagers[id];
  11735. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11736. this._clearDepthBuffer();
  11737. spriteManager.render();
  11738. }
  11739. }
  11740. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11741. };
  11742. RenderingManager.prototype._clearDepthBuffer = function () {
  11743. if (this._depthBufferAlreadyCleaned) {
  11744. return;
  11745. }
  11746. this._scene.getEngine().clear(0, false, true);
  11747. this._depthBufferAlreadyCleaned = true;
  11748. };
  11749. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11750. if (this._currentRenderSprites) {
  11751. this._renderSprites(this._currentIndex);
  11752. }
  11753. if (this._currentRenderParticles) {
  11754. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11755. }
  11756. };
  11757. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11758. this._currentActiveMeshes = activeMeshes;
  11759. this._currentRenderParticles = renderParticles;
  11760. this._currentRenderSprites = renderSprites;
  11761. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11762. this._depthBufferAlreadyCleaned = false;
  11763. var renderingGroup = this._renderingGroups[index];
  11764. var needToStepBack = false;
  11765. this._currentIndex = index;
  11766. if (renderingGroup) {
  11767. this._clearDepthBuffer();
  11768. if (!renderingGroup.onBeforeTransparentRendering) {
  11769. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11770. }
  11771. if (!renderingGroup.render(customRenderFunction)) {
  11772. this._renderingGroups.splice(index, 1);
  11773. needToStepBack = true;
  11774. this._renderSpritesAndParticles();
  11775. }
  11776. }
  11777. else {
  11778. this._renderSpritesAndParticles();
  11779. }
  11780. if (needToStepBack) {
  11781. index--;
  11782. }
  11783. }
  11784. };
  11785. RenderingManager.prototype.reset = function () {
  11786. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11787. if (renderingGroup) {
  11788. renderingGroup.prepare();
  11789. }
  11790. });
  11791. };
  11792. RenderingManager.prototype.dispatch = function (subMesh) {
  11793. var mesh = subMesh.getMesh();
  11794. var renderingGroupId = mesh.renderingGroupId || 0;
  11795. if (!this._renderingGroups[renderingGroupId]) {
  11796. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11797. }
  11798. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11799. };
  11800. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11801. return RenderingManager;
  11802. })();
  11803. BABYLON.RenderingManager = RenderingManager;
  11804. })(BABYLON || (BABYLON = {}));
  11805. var BABYLON;
  11806. (function (BABYLON) {
  11807. var RenderingGroup = (function () {
  11808. function RenderingGroup(index, scene) {
  11809. this.index = index;
  11810. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11811. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11812. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11813. this._scene = scene;
  11814. }
  11815. RenderingGroup.prototype.render = function (customRenderFunction) {
  11816. if (customRenderFunction) {
  11817. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11818. return true;
  11819. }
  11820. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11821. if (this.onBeforeTransparentRendering) {
  11822. this.onBeforeTransparentRendering();
  11823. }
  11824. return false;
  11825. }
  11826. var engine = this._scene.getEngine();
  11827. // Opaque
  11828. var subIndex;
  11829. var submesh;
  11830. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11831. submesh = this._opaqueSubMeshes.data[subIndex];
  11832. submesh.render(false);
  11833. }
  11834. // Alpha test
  11835. engine.setAlphaTesting(true);
  11836. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11837. submesh = this._alphaTestSubMeshes.data[subIndex];
  11838. submesh.render(false);
  11839. }
  11840. engine.setAlphaTesting(false);
  11841. if (this.onBeforeTransparentRendering) {
  11842. this.onBeforeTransparentRendering();
  11843. }
  11844. // Transparent
  11845. if (this._transparentSubMeshes.length) {
  11846. // Sorting
  11847. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11848. submesh = this._transparentSubMeshes.data[subIndex];
  11849. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11850. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11851. }
  11852. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11853. sortedArray.sort(function (a, b) {
  11854. // Alpha index first
  11855. if (a._alphaIndex > b._alphaIndex) {
  11856. return 1;
  11857. }
  11858. if (a._alphaIndex < b._alphaIndex) {
  11859. return -1;
  11860. }
  11861. // Then distance to camera
  11862. if (a._distanceToCamera < b._distanceToCamera) {
  11863. return 1;
  11864. }
  11865. if (a._distanceToCamera > b._distanceToCamera) {
  11866. return -1;
  11867. }
  11868. return 0;
  11869. });
  11870. // Rendering
  11871. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11872. submesh = sortedArray[subIndex];
  11873. submesh.render(true);
  11874. }
  11875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11876. }
  11877. return true;
  11878. };
  11879. RenderingGroup.prototype.prepare = function () {
  11880. this._opaqueSubMeshes.reset();
  11881. this._transparentSubMeshes.reset();
  11882. this._alphaTestSubMeshes.reset();
  11883. };
  11884. RenderingGroup.prototype.dispatch = function (subMesh) {
  11885. var material = subMesh.getMaterial();
  11886. var mesh = subMesh.getMesh();
  11887. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11888. this._transparentSubMeshes.push(subMesh);
  11889. }
  11890. else if (material.needAlphaTesting()) {
  11891. this._alphaTestSubMeshes.push(subMesh);
  11892. }
  11893. else {
  11894. this._opaqueSubMeshes.push(subMesh); // Opaque
  11895. }
  11896. };
  11897. return RenderingGroup;
  11898. })();
  11899. BABYLON.RenderingGroup = RenderingGroup;
  11900. })(BABYLON || (BABYLON = {}));
  11901. var BABYLON;
  11902. (function (BABYLON) {
  11903. /**
  11904. * Represents a scene to be rendered by the engine.
  11905. * @see http://doc.babylonjs.com/page.php?p=21911
  11906. */
  11907. var Scene = (function () {
  11908. /**
  11909. * @constructor
  11910. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11911. */
  11912. function Scene(engine) {
  11913. // Members
  11914. this.autoClear = true;
  11915. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11916. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11917. this.forceWireframe = false;
  11918. this.forcePointsCloud = false;
  11919. this.forceShowBoundingBoxes = false;
  11920. this.animationsEnabled = true;
  11921. this.constantlyUpdateMeshUnderPointer = false;
  11922. 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
  11923. // Fog
  11924. /**
  11925. * is fog enabled on this scene.
  11926. * @type {boolean}
  11927. */
  11928. this.fogEnabled = true;
  11929. this.fogMode = Scene.FOGMODE_NONE;
  11930. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11931. this.fogDensity = 0.1;
  11932. this.fogStart = 0;
  11933. this.fogEnd = 1000.0;
  11934. // Lights
  11935. /**
  11936. * is shadow enabled on this scene.
  11937. * @type {boolean}
  11938. */
  11939. this.shadowsEnabled = true;
  11940. /**
  11941. * is light enabled on this scene.
  11942. * @type {boolean}
  11943. */
  11944. this.lightsEnabled = true;
  11945. /**
  11946. * All of the lights added to this scene.
  11947. * @see BABYLON.Light
  11948. * @type {BABYLON.Light[]}
  11949. */
  11950. this.lights = new Array();
  11951. // Cameras
  11952. /**
  11953. * All of the cameras added to this scene.
  11954. * @see BABYLON.Camera
  11955. * @type {BABYLON.Camera[]}
  11956. */
  11957. this.cameras = new Array();
  11958. this.activeCameras = new Array();
  11959. // Meshes
  11960. /**
  11961. * All of the (abstract) meshes added to this scene.
  11962. * @see BABYLON.AbstractMesh
  11963. * @type {BABYLON.AbstractMesh[]}
  11964. */
  11965. this.meshes = new Array();
  11966. // Geometries
  11967. this._geometries = new Array();
  11968. this.materials = new Array();
  11969. this.multiMaterials = new Array();
  11970. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11971. // Textures
  11972. this.texturesEnabled = true;
  11973. this.textures = new Array();
  11974. // Particles
  11975. this.particlesEnabled = true;
  11976. this.particleSystems = new Array();
  11977. // Sprites
  11978. this.spritesEnabled = true;
  11979. this.spriteManagers = new Array();
  11980. // Layers
  11981. this.layers = new Array();
  11982. // Skeletons
  11983. this.skeletonsEnabled = true;
  11984. this.skeletons = new Array();
  11985. // Lens flares
  11986. this.lensFlaresEnabled = true;
  11987. this.lensFlareSystems = new Array();
  11988. // Collisions
  11989. this.collisionsEnabled = true;
  11990. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11991. // Postprocesses
  11992. this.postProcessesEnabled = true;
  11993. // Customs render targets
  11994. this.renderTargetsEnabled = true;
  11995. this.dumpNextRenderTargets = false;
  11996. this.customRenderTargets = new Array();
  11997. // Imported meshes
  11998. this.importedMeshesFiles = new Array();
  11999. // Probes
  12000. this.probesEnabled = true;
  12001. this.reflectionProbes = new Array();
  12002. this._actionManagers = new Array();
  12003. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12004. // Procedural textures
  12005. this.proceduralTexturesEnabled = true;
  12006. this._proceduralTextures = new Array();
  12007. this.soundTracks = new Array();
  12008. this._audioEnabled = true;
  12009. this._headphone = false;
  12010. this._totalVertices = 0;
  12011. this._activeIndices = 0;
  12012. this._activeParticles = 0;
  12013. this._lastFrameDuration = 0;
  12014. this._evaluateActiveMeshesDuration = 0;
  12015. this._renderTargetsDuration = 0;
  12016. this._particlesDuration = 0;
  12017. this._renderDuration = 0;
  12018. this._spritesDuration = 0;
  12019. this._animationRatio = 0;
  12020. this._renderId = 0;
  12021. this._executeWhenReadyTimeoutId = -1;
  12022. this._toBeDisposed = new BABYLON.SmartArray(256);
  12023. this._onReadyCallbacks = new Array();
  12024. this._pendingData = []; //ANY
  12025. this._onBeforeRenderCallbacks = new Array();
  12026. this._onAfterRenderCallbacks = new Array();
  12027. this._activeMeshes = new BABYLON.SmartArray(256);
  12028. this._processedMaterials = new BABYLON.SmartArray(256);
  12029. this._renderTargets = new BABYLON.SmartArray(256);
  12030. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12031. this._activeSkeletons = new BABYLON.SmartArray(32);
  12032. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12033. this._activeBones = 0;
  12034. this._activeAnimatables = new Array();
  12035. this._transformMatrix = BABYLON.Matrix.Zero();
  12036. this._edgesRenderers = new BABYLON.SmartArray(16);
  12037. this._uniqueIdCounter = 0;
  12038. this._engine = engine;
  12039. engine.scenes.push(this);
  12040. this._renderingManager = new BABYLON.RenderingManager(this);
  12041. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12042. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12043. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12044. if (BABYLON.OutlineRenderer) {
  12045. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12046. }
  12047. this.attachControl();
  12048. this._debugLayer = new BABYLON.DebugLayer(this);
  12049. if (BABYLON.SoundTrack) {
  12050. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12051. }
  12052. //simplification queue
  12053. if (BABYLON.SimplificationQueue) {
  12054. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12055. }
  12056. //collision coordinator initialization. For now legacy per default.
  12057. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12058. }
  12059. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12060. get: function () {
  12061. return Scene._FOGMODE_NONE;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12067. get: function () {
  12068. return Scene._FOGMODE_EXP;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12074. get: function () {
  12075. return Scene._FOGMODE_EXP2;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12081. get: function () {
  12082. return Scene._FOGMODE_LINEAR;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(Scene.prototype, "debugLayer", {
  12088. // Properties
  12089. get: function () {
  12090. return this._debugLayer;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12096. get: function () {
  12097. return this._workerCollisions;
  12098. },
  12099. set: function (enabled) {
  12100. enabled = (enabled && !!Worker);
  12101. this._workerCollisions = enabled;
  12102. if (this.collisionCoordinator) {
  12103. this.collisionCoordinator.destroy();
  12104. }
  12105. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12106. this.collisionCoordinator.init(this);
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12112. get: function () {
  12113. return this._selectionOctree;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12119. /**
  12120. * The mesh that is currently under the pointer.
  12121. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12122. */
  12123. get: function () {
  12124. return this._meshUnderPointer;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. Object.defineProperty(Scene.prototype, "pointerX", {
  12130. /**
  12131. * Current on-screen X position of the pointer
  12132. * @return {number} X position of the pointer
  12133. */
  12134. get: function () {
  12135. return this._pointerX;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "pointerY", {
  12141. /**
  12142. * Current on-screen Y position of the pointer
  12143. * @return {number} Y position of the pointer
  12144. */
  12145. get: function () {
  12146. return this._pointerY;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Scene.prototype.getCachedMaterial = function () {
  12152. return this._cachedMaterial;
  12153. };
  12154. Scene.prototype.getBoundingBoxRenderer = function () {
  12155. return this._boundingBoxRenderer;
  12156. };
  12157. Scene.prototype.getOutlineRenderer = function () {
  12158. return this._outlineRenderer;
  12159. };
  12160. Scene.prototype.getEngine = function () {
  12161. return this._engine;
  12162. };
  12163. Scene.prototype.getTotalVertices = function () {
  12164. return this._totalVertices;
  12165. };
  12166. Scene.prototype.getActiveIndices = function () {
  12167. return this._activeIndices;
  12168. };
  12169. Scene.prototype.getActiveParticles = function () {
  12170. return this._activeParticles;
  12171. };
  12172. Scene.prototype.getActiveBones = function () {
  12173. return this._activeBones;
  12174. };
  12175. // Stats
  12176. Scene.prototype.getLastFrameDuration = function () {
  12177. return this._lastFrameDuration;
  12178. };
  12179. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12180. return this._evaluateActiveMeshesDuration;
  12181. };
  12182. Scene.prototype.getActiveMeshes = function () {
  12183. return this._activeMeshes;
  12184. };
  12185. Scene.prototype.getRenderTargetsDuration = function () {
  12186. return this._renderTargetsDuration;
  12187. };
  12188. Scene.prototype.getRenderDuration = function () {
  12189. return this._renderDuration;
  12190. };
  12191. Scene.prototype.getParticlesDuration = function () {
  12192. return this._particlesDuration;
  12193. };
  12194. Scene.prototype.getSpritesDuration = function () {
  12195. return this._spritesDuration;
  12196. };
  12197. Scene.prototype.getAnimationRatio = function () {
  12198. return this._animationRatio;
  12199. };
  12200. Scene.prototype.getRenderId = function () {
  12201. return this._renderId;
  12202. };
  12203. Scene.prototype.incrementRenderId = function () {
  12204. this._renderId++;
  12205. };
  12206. Scene.prototype._updatePointerPosition = function (evt) {
  12207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12208. this._pointerX = evt.clientX - canvasRect.left;
  12209. this._pointerY = evt.clientY - canvasRect.top;
  12210. if (this.cameraToUseForPointers) {
  12211. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12212. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12213. }
  12214. };
  12215. // Pointers handling
  12216. Scene.prototype.attachControl = function () {
  12217. var _this = this;
  12218. var spritePredicate = function (sprite) {
  12219. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12220. };
  12221. this._onPointerMove = function (evt) {
  12222. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12223. return;
  12224. }
  12225. var canvas = _this._engine.getRenderingCanvas();
  12226. _this._updatePointerPosition(evt);
  12227. // Meshes
  12228. 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);
  12229. if (pickResult.hit && pickResult.pickedMesh) {
  12230. _this._meshUnderPointer = pickResult.pickedMesh;
  12231. _this.setPointerOverMesh(pickResult.pickedMesh);
  12232. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12233. canvas.style.cursor = "pointer";
  12234. }
  12235. else {
  12236. canvas.style.cursor = "";
  12237. }
  12238. }
  12239. else {
  12240. // Sprites
  12241. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12242. if (pickResult.hit && pickResult.pickedSprite) {
  12243. canvas.style.cursor = "pointer";
  12244. }
  12245. else {
  12246. // Restore pointer
  12247. _this.setPointerOverMesh(null);
  12248. canvas.style.cursor = "";
  12249. _this._meshUnderPointer = null;
  12250. }
  12251. }
  12252. if (_this.onPointerMove) {
  12253. _this.onPointerMove(evt, pickResult);
  12254. }
  12255. };
  12256. this._onPointerDown = function (evt) {
  12257. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12258. return;
  12259. }
  12260. _this._updatePointerPosition(evt);
  12261. var predicate = null;
  12262. // Meshes
  12263. if (!_this.onPointerDown) {
  12264. predicate = function (mesh) {
  12265. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12266. };
  12267. }
  12268. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12269. if (pickResult.hit && pickResult.pickedMesh) {
  12270. if (pickResult.pickedMesh.actionManager) {
  12271. switch (evt.button) {
  12272. case 0:
  12273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12274. break;
  12275. case 1:
  12276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12277. break;
  12278. case 2:
  12279. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12280. break;
  12281. }
  12282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12283. }
  12284. }
  12285. if (_this.onPointerDown) {
  12286. _this.onPointerDown(evt, pickResult);
  12287. }
  12288. // Sprites
  12289. if (_this.spriteManagers.length > 0) {
  12290. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12291. if (pickResult.hit && pickResult.pickedSprite) {
  12292. if (pickResult.pickedSprite.actionManager) {
  12293. switch (evt.button) {
  12294. case 0:
  12295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12296. break;
  12297. case 1:
  12298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12299. break;
  12300. case 2:
  12301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12302. break;
  12303. }
  12304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12305. }
  12306. }
  12307. }
  12308. };
  12309. this._onPointerUp = function (evt) {
  12310. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12311. return;
  12312. }
  12313. var predicate = null;
  12314. _this._updatePointerPosition(evt);
  12315. if (!_this.onPointerUp) {
  12316. predicate = function (mesh) {
  12317. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12318. };
  12319. }
  12320. // Meshes
  12321. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12322. if (pickResult.hit && pickResult.pickedMesh) {
  12323. if (pickResult.pickedMesh.actionManager) {
  12324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12325. }
  12326. }
  12327. if (_this.onPointerUp) {
  12328. _this.onPointerUp(evt, pickResult);
  12329. }
  12330. // Sprites
  12331. if (_this.spriteManagers.length > 0) {
  12332. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12333. if (pickResult.hit && pickResult.pickedSprite) {
  12334. if (pickResult.pickedSprite.actionManager) {
  12335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12336. }
  12337. }
  12338. }
  12339. };
  12340. this._onKeyDown = function (evt) {
  12341. if (_this.actionManager) {
  12342. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12343. }
  12344. };
  12345. this._onKeyUp = function (evt) {
  12346. if (_this.actionManager) {
  12347. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12348. }
  12349. };
  12350. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12351. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12352. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12353. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12354. // Wheel
  12355. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12356. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12357. BABYLON.Tools.RegisterTopRootEvents([
  12358. { name: "keydown", handler: this._onKeyDown },
  12359. { name: "keyup", handler: this._onKeyUp }
  12360. ]);
  12361. };
  12362. Scene.prototype.detachControl = function () {
  12363. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12364. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12365. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12366. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12367. // Wheel
  12368. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12369. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12370. BABYLON.Tools.UnregisterTopRootEvents([
  12371. { name: "keydown", handler: this._onKeyDown },
  12372. { name: "keyup", handler: this._onKeyUp }
  12373. ]);
  12374. };
  12375. // Ready
  12376. Scene.prototype.isReady = function () {
  12377. if (this._pendingData.length > 0) {
  12378. return false;
  12379. }
  12380. var index;
  12381. for (index = 0; index < this._geometries.length; index++) {
  12382. var geometry = this._geometries[index];
  12383. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12384. return false;
  12385. }
  12386. }
  12387. for (index = 0; index < this.meshes.length; index++) {
  12388. var mesh = this.meshes[index];
  12389. if (!mesh.isReady()) {
  12390. return false;
  12391. }
  12392. var mat = mesh.material;
  12393. if (mat) {
  12394. if (!mat.isReady(mesh)) {
  12395. return false;
  12396. }
  12397. }
  12398. }
  12399. return true;
  12400. };
  12401. Scene.prototype.resetCachedMaterial = function () {
  12402. this._cachedMaterial = null;
  12403. };
  12404. Scene.prototype.registerBeforeRender = function (func) {
  12405. this._onBeforeRenderCallbacks.push(func);
  12406. };
  12407. Scene.prototype.unregisterBeforeRender = function (func) {
  12408. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12409. if (index > -1) {
  12410. this._onBeforeRenderCallbacks.splice(index, 1);
  12411. }
  12412. };
  12413. Scene.prototype.registerAfterRender = function (func) {
  12414. this._onAfterRenderCallbacks.push(func);
  12415. };
  12416. Scene.prototype.unregisterAfterRender = function (func) {
  12417. var index = this._onAfterRenderCallbacks.indexOf(func);
  12418. if (index > -1) {
  12419. this._onAfterRenderCallbacks.splice(index, 1);
  12420. }
  12421. };
  12422. Scene.prototype._addPendingData = function (data) {
  12423. this._pendingData.push(data);
  12424. };
  12425. Scene.prototype._removePendingData = function (data) {
  12426. var index = this._pendingData.indexOf(data);
  12427. if (index !== -1) {
  12428. this._pendingData.splice(index, 1);
  12429. }
  12430. };
  12431. Scene.prototype.getWaitingItemsCount = function () {
  12432. return this._pendingData.length;
  12433. };
  12434. /**
  12435. * Registers a function to be executed when the scene is ready.
  12436. * @param {Function} func - the function to be executed.
  12437. */
  12438. Scene.prototype.executeWhenReady = function (func) {
  12439. var _this = this;
  12440. this._onReadyCallbacks.push(func);
  12441. if (this._executeWhenReadyTimeoutId !== -1) {
  12442. return;
  12443. }
  12444. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12445. _this._checkIsReady();
  12446. }, 150);
  12447. };
  12448. Scene.prototype._checkIsReady = function () {
  12449. var _this = this;
  12450. if (this.isReady()) {
  12451. this._onReadyCallbacks.forEach(function (func) {
  12452. func();
  12453. });
  12454. this._onReadyCallbacks = [];
  12455. this._executeWhenReadyTimeoutId = -1;
  12456. return;
  12457. }
  12458. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12459. _this._checkIsReady();
  12460. }, 150);
  12461. };
  12462. // Animations
  12463. /**
  12464. * Will start the animation sequence of a given target
  12465. * @param target - the target
  12466. * @param {number} from - from which frame should animation start
  12467. * @param {number} to - till which frame should animation run.
  12468. * @param {boolean} [loop] - should the animation loop
  12469. * @param {number} [speedRatio] - the speed in which to run the animation
  12470. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12471. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12472. * @return {BABYLON.Animatable} the animatable object created for this animation
  12473. * @see BABYLON.Animatable
  12474. * @see http://doc.babylonjs.com/page.php?p=22081
  12475. */
  12476. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12477. if (speedRatio === void 0) { speedRatio = 1.0; }
  12478. this.stopAnimation(target);
  12479. if (!animatable) {
  12480. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12481. }
  12482. // Local animations
  12483. if (target.animations) {
  12484. animatable.appendAnimations(target, target.animations);
  12485. }
  12486. // Children animations
  12487. if (target.getAnimatables) {
  12488. var animatables = target.getAnimatables();
  12489. for (var index = 0; index < animatables.length; index++) {
  12490. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12491. }
  12492. }
  12493. return animatable;
  12494. };
  12495. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12496. if (speedRatio === undefined) {
  12497. speedRatio = 1.0;
  12498. }
  12499. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12500. return animatable;
  12501. };
  12502. Scene.prototype.getAnimatableByTarget = function (target) {
  12503. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12504. if (this._activeAnimatables[index].target === target) {
  12505. return this._activeAnimatables[index];
  12506. }
  12507. }
  12508. return null;
  12509. };
  12510. /**
  12511. * Will stop the animation of the given target
  12512. * @param target - the target
  12513. * @see beginAnimation
  12514. */
  12515. Scene.prototype.stopAnimation = function (target) {
  12516. var animatable = this.getAnimatableByTarget(target);
  12517. if (animatable) {
  12518. animatable.stop();
  12519. }
  12520. };
  12521. Scene.prototype._animate = function () {
  12522. if (!this.animationsEnabled) {
  12523. return;
  12524. }
  12525. if (!this._animationStartDate) {
  12526. this._animationStartDate = BABYLON.Tools.Now;
  12527. }
  12528. // Getting time
  12529. var now = BABYLON.Tools.Now;
  12530. var delay = now - this._animationStartDate;
  12531. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12532. this._activeAnimatables[index]._animate(delay);
  12533. }
  12534. };
  12535. // Matrix
  12536. Scene.prototype.getViewMatrix = function () {
  12537. return this._viewMatrix;
  12538. };
  12539. Scene.prototype.getProjectionMatrix = function () {
  12540. return this._projectionMatrix;
  12541. };
  12542. Scene.prototype.getTransformMatrix = function () {
  12543. return this._transformMatrix;
  12544. };
  12545. Scene.prototype.setTransformMatrix = function (view, projection) {
  12546. this._viewMatrix = view;
  12547. this._projectionMatrix = projection;
  12548. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12549. };
  12550. // Methods
  12551. Scene.prototype.addMesh = function (newMesh) {
  12552. newMesh.uniqueId = this._uniqueIdCounter++;
  12553. var position = this.meshes.push(newMesh);
  12554. //notify the collision coordinator
  12555. this.collisionCoordinator.onMeshAdded(newMesh);
  12556. if (this.onNewMeshAdded) {
  12557. this.onNewMeshAdded(newMesh, position, this);
  12558. }
  12559. };
  12560. Scene.prototype.removeMesh = function (toRemove) {
  12561. var index = this.meshes.indexOf(toRemove);
  12562. if (index !== -1) {
  12563. // Remove from the scene if mesh found
  12564. this.meshes.splice(index, 1);
  12565. }
  12566. //notify the collision coordinator
  12567. this.collisionCoordinator.onMeshRemoved(toRemove);
  12568. if (this.onMeshRemoved) {
  12569. this.onMeshRemoved(toRemove);
  12570. }
  12571. return index;
  12572. };
  12573. Scene.prototype.removeSkeleton = function (toRemove) {
  12574. var index = this.skeletons.indexOf(toRemove);
  12575. if (index !== -1) {
  12576. // Remove from the scene if mesh found
  12577. this.skeletons.splice(index, 1);
  12578. }
  12579. return index;
  12580. };
  12581. Scene.prototype.removeLight = function (toRemove) {
  12582. var index = this.lights.indexOf(toRemove);
  12583. if (index !== -1) {
  12584. // Remove from the scene if mesh found
  12585. this.lights.splice(index, 1);
  12586. }
  12587. if (this.onLightRemoved) {
  12588. this.onLightRemoved(toRemove);
  12589. }
  12590. return index;
  12591. };
  12592. Scene.prototype.removeCamera = function (toRemove) {
  12593. var index = this.cameras.indexOf(toRemove);
  12594. if (index !== -1) {
  12595. // Remove from the scene if mesh found
  12596. this.cameras.splice(index, 1);
  12597. }
  12598. // Remove from activeCameras
  12599. var index2 = this.activeCameras.indexOf(toRemove);
  12600. if (index2 !== -1) {
  12601. // Remove from the scene if mesh found
  12602. this.activeCameras.splice(index2, 1);
  12603. }
  12604. // Reset the activeCamera
  12605. if (this.activeCamera === toRemove) {
  12606. if (this.cameras.length > 0) {
  12607. this.activeCamera = this.cameras[0];
  12608. }
  12609. else {
  12610. this.activeCamera = null;
  12611. }
  12612. }
  12613. if (this.onCameraRemoved) {
  12614. this.onCameraRemoved(toRemove);
  12615. }
  12616. return index;
  12617. };
  12618. Scene.prototype.addLight = function (newLight) {
  12619. newLight.uniqueId = this._uniqueIdCounter++;
  12620. var position = this.lights.push(newLight);
  12621. if (this.onNewLightAdded) {
  12622. this.onNewLightAdded(newLight, position, this);
  12623. }
  12624. };
  12625. Scene.prototype.addCamera = function (newCamera) {
  12626. newCamera.uniqueId = this._uniqueIdCounter++;
  12627. var position = this.cameras.push(newCamera);
  12628. if (this.onNewCameraAdded) {
  12629. this.onNewCameraAdded(newCamera, position, this);
  12630. }
  12631. };
  12632. /**
  12633. * sets the active camera of the scene using its ID
  12634. * @param {string} id - the camera's ID
  12635. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12636. * @see activeCamera
  12637. */
  12638. Scene.prototype.setActiveCameraByID = function (id) {
  12639. var camera = this.getCameraByID(id);
  12640. if (camera) {
  12641. this.activeCamera = camera;
  12642. return camera;
  12643. }
  12644. return null;
  12645. };
  12646. /**
  12647. * sets the active camera of the scene using its name
  12648. * @param {string} name - the camera's name
  12649. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12650. * @see activeCamera
  12651. */
  12652. Scene.prototype.setActiveCameraByName = function (name) {
  12653. var camera = this.getCameraByName(name);
  12654. if (camera) {
  12655. this.activeCamera = camera;
  12656. return camera;
  12657. }
  12658. return null;
  12659. };
  12660. /**
  12661. * get a material using its id
  12662. * @param {string} the material's ID
  12663. * @return {BABYLON.Material|null} the material or null if none found.
  12664. */
  12665. Scene.prototype.getMaterialByID = function (id) {
  12666. for (var index = 0; index < this.materials.length; index++) {
  12667. if (this.materials[index].id === id) {
  12668. return this.materials[index];
  12669. }
  12670. }
  12671. return null;
  12672. };
  12673. /**
  12674. * get a material using its name
  12675. * @param {string} the material's name
  12676. * @return {BABYLON.Material|null} the material or null if none found.
  12677. */
  12678. Scene.prototype.getMaterialByName = function (name) {
  12679. for (var index = 0; index < this.materials.length; index++) {
  12680. if (this.materials[index].name === name) {
  12681. return this.materials[index];
  12682. }
  12683. }
  12684. return null;
  12685. };
  12686. Scene.prototype.getLensFlareSystemByName = function (name) {
  12687. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12688. if (this.lensFlareSystems[index].name === name) {
  12689. return this.lensFlareSystems[index];
  12690. }
  12691. }
  12692. return null;
  12693. };
  12694. Scene.prototype.getCameraByID = function (id) {
  12695. for (var index = 0; index < this.cameras.length; index++) {
  12696. if (this.cameras[index].id === id) {
  12697. return this.cameras[index];
  12698. }
  12699. }
  12700. return null;
  12701. };
  12702. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12703. for (var index = 0; index < this.cameras.length; index++) {
  12704. if (this.cameras[index].uniqueId === uniqueId) {
  12705. return this.cameras[index];
  12706. }
  12707. }
  12708. return null;
  12709. };
  12710. /**
  12711. * get a camera using its name
  12712. * @param {string} the camera's name
  12713. * @return {BABYLON.Camera|null} the camera or null if none found.
  12714. */
  12715. Scene.prototype.getCameraByName = function (name) {
  12716. for (var index = 0; index < this.cameras.length; index++) {
  12717. if (this.cameras[index].name === name) {
  12718. return this.cameras[index];
  12719. }
  12720. }
  12721. return null;
  12722. };
  12723. /**
  12724. * get a bone using its id
  12725. * @param {string} the bone's id
  12726. * @return {BABYLON.Bone|null} the bone or null if not found
  12727. */
  12728. Scene.prototype.getBoneByID = function (id) {
  12729. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12730. var skeleton = this.skeletons[skeletonIndex];
  12731. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12732. if (skeleton.bones[boneIndex].id === id) {
  12733. return skeleton.bones[boneIndex];
  12734. }
  12735. }
  12736. }
  12737. return null;
  12738. };
  12739. /**
  12740. * get a bone using its id
  12741. * @param {string} the bone's name
  12742. * @return {BABYLON.Bone|null} the bone or null if not found
  12743. */
  12744. Scene.prototype.getBoneByName = function (name) {
  12745. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12746. var skeleton = this.skeletons[skeletonIndex];
  12747. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12748. if (skeleton.bones[boneIndex].name === name) {
  12749. return skeleton.bones[boneIndex];
  12750. }
  12751. }
  12752. }
  12753. return null;
  12754. };
  12755. /**
  12756. * get a light node using its name
  12757. * @param {string} the light's name
  12758. * @return {BABYLON.Light|null} the light or null if none found.
  12759. */
  12760. Scene.prototype.getLightByName = function (name) {
  12761. for (var index = 0; index < this.lights.length; index++) {
  12762. if (this.lights[index].name === name) {
  12763. return this.lights[index];
  12764. }
  12765. }
  12766. return null;
  12767. };
  12768. /**
  12769. * get a light node using its ID
  12770. * @param {string} the light's id
  12771. * @return {BABYLON.Light|null} the light or null if none found.
  12772. */
  12773. Scene.prototype.getLightByID = function (id) {
  12774. for (var index = 0; index < this.lights.length; index++) {
  12775. if (this.lights[index].id === id) {
  12776. return this.lights[index];
  12777. }
  12778. }
  12779. return null;
  12780. };
  12781. /**
  12782. * get a light node using its scene-generated unique ID
  12783. * @param {number} the light's unique id
  12784. * @return {BABYLON.Light|null} the light or null if none found.
  12785. */
  12786. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12787. for (var index = 0; index < this.lights.length; index++) {
  12788. if (this.lights[index].uniqueId === uniqueId) {
  12789. return this.lights[index];
  12790. }
  12791. }
  12792. return null;
  12793. };
  12794. /**
  12795. * get a particle system by id
  12796. * @param id {number} the particle system id
  12797. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12798. */
  12799. Scene.prototype.getParticleSystemByID = function (id) {
  12800. for (var index = 0; index < this.particleSystems.length; index++) {
  12801. if (this.particleSystems[index].id === id) {
  12802. return this.particleSystems[index];
  12803. }
  12804. }
  12805. return null;
  12806. };
  12807. /**
  12808. * get a geometry using its ID
  12809. * @param {string} the geometry's id
  12810. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12811. */
  12812. Scene.prototype.getGeometryByID = function (id) {
  12813. for (var index = 0; index < this._geometries.length; index++) {
  12814. if (this._geometries[index].id === id) {
  12815. return this._geometries[index];
  12816. }
  12817. }
  12818. return null;
  12819. };
  12820. /**
  12821. * add a new geometry to this scene.
  12822. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12823. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12824. * @return {boolean} was the geometry added or not
  12825. */
  12826. Scene.prototype.pushGeometry = function (geometry, force) {
  12827. if (!force && this.getGeometryByID(geometry.id)) {
  12828. return false;
  12829. }
  12830. this._geometries.push(geometry);
  12831. //notify the collision coordinator
  12832. this.collisionCoordinator.onGeometryAdded(geometry);
  12833. if (this.onGeometryAdded) {
  12834. this.onGeometryAdded(geometry);
  12835. }
  12836. return true;
  12837. };
  12838. /**
  12839. * Removes an existing geometry
  12840. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12841. * @return {boolean} was the geometry removed or not
  12842. */
  12843. Scene.prototype.removeGeometry = function (geometry) {
  12844. var index = this._geometries.indexOf(geometry);
  12845. if (index > -1) {
  12846. this._geometries.splice(index, 1);
  12847. //notify the collision coordinator
  12848. this.collisionCoordinator.onGeometryDeleted(geometry);
  12849. if (this.onGeometryRemoved) {
  12850. this.onGeometryRemoved(geometry);
  12851. }
  12852. return true;
  12853. }
  12854. return false;
  12855. };
  12856. Scene.prototype.getGeometries = function () {
  12857. return this._geometries;
  12858. };
  12859. /**
  12860. * Get the first added mesh found of a given ID
  12861. * @param {string} id - the id to search for
  12862. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12863. */
  12864. Scene.prototype.getMeshByID = function (id) {
  12865. for (var index = 0; index < this.meshes.length; index++) {
  12866. if (this.meshes[index].id === id) {
  12867. return this.meshes[index];
  12868. }
  12869. }
  12870. return null;
  12871. };
  12872. /**
  12873. * Get a mesh with its auto-generated unique id
  12874. * @param {number} uniqueId - the unique id to search for
  12875. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12876. */
  12877. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12878. for (var index = 0; index < this.meshes.length; index++) {
  12879. if (this.meshes[index].uniqueId === uniqueId) {
  12880. return this.meshes[index];
  12881. }
  12882. }
  12883. return null;
  12884. };
  12885. /**
  12886. * Get a the last added mesh found of a given ID
  12887. * @param {string} id - the id to search for
  12888. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12889. */
  12890. Scene.prototype.getLastMeshByID = function (id) {
  12891. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12892. if (this.meshes[index].id === id) {
  12893. return this.meshes[index];
  12894. }
  12895. }
  12896. return null;
  12897. };
  12898. /**
  12899. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12900. * @param {string} id - the id to search for
  12901. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12902. */
  12903. Scene.prototype.getLastEntryByID = function (id) {
  12904. var index;
  12905. for (index = this.meshes.length - 1; index >= 0; index--) {
  12906. if (this.meshes[index].id === id) {
  12907. return this.meshes[index];
  12908. }
  12909. }
  12910. for (index = this.cameras.length - 1; index >= 0; index--) {
  12911. if (this.cameras[index].id === id) {
  12912. return this.cameras[index];
  12913. }
  12914. }
  12915. for (index = this.lights.length - 1; index >= 0; index--) {
  12916. if (this.lights[index].id === id) {
  12917. return this.lights[index];
  12918. }
  12919. }
  12920. return null;
  12921. };
  12922. Scene.prototype.getNodeByID = function (id) {
  12923. var mesh = this.getMeshByID(id);
  12924. if (mesh) {
  12925. return mesh;
  12926. }
  12927. var light = this.getLightByID(id);
  12928. if (light) {
  12929. return light;
  12930. }
  12931. var camera = this.getCameraByID(id);
  12932. if (camera) {
  12933. return camera;
  12934. }
  12935. var bone = this.getBoneByID(id);
  12936. return bone;
  12937. };
  12938. Scene.prototype.getNodeByName = function (name) {
  12939. var mesh = this.getMeshByName(name);
  12940. if (mesh) {
  12941. return mesh;
  12942. }
  12943. var light = this.getLightByName(name);
  12944. if (light) {
  12945. return light;
  12946. }
  12947. var camera = this.getCameraByName(name);
  12948. if (camera) {
  12949. return camera;
  12950. }
  12951. var bone = this.getBoneByName(name);
  12952. return bone;
  12953. };
  12954. Scene.prototype.getMeshByName = function (name) {
  12955. for (var index = 0; index < this.meshes.length; index++) {
  12956. if (this.meshes[index].name === name) {
  12957. return this.meshes[index];
  12958. }
  12959. }
  12960. return null;
  12961. };
  12962. Scene.prototype.getSoundByName = function (name) {
  12963. var index;
  12964. if (BABYLON.AudioEngine) {
  12965. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12966. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12967. return this.mainSoundTrack.soundCollection[index];
  12968. }
  12969. }
  12970. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12971. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12972. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12973. return this.soundTracks[sdIndex].soundCollection[index];
  12974. }
  12975. }
  12976. }
  12977. }
  12978. return null;
  12979. };
  12980. Scene.prototype.getLastSkeletonByID = function (id) {
  12981. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12982. if (this.skeletons[index].id === id) {
  12983. return this.skeletons[index];
  12984. }
  12985. }
  12986. return null;
  12987. };
  12988. Scene.prototype.getSkeletonById = function (id) {
  12989. for (var index = 0; index < this.skeletons.length; index++) {
  12990. if (this.skeletons[index].id === id) {
  12991. return this.skeletons[index];
  12992. }
  12993. }
  12994. return null;
  12995. };
  12996. Scene.prototype.getSkeletonByName = function (name) {
  12997. for (var index = 0; index < this.skeletons.length; index++) {
  12998. if (this.skeletons[index].name === name) {
  12999. return this.skeletons[index];
  13000. }
  13001. }
  13002. return null;
  13003. };
  13004. Scene.prototype.isActiveMesh = function (mesh) {
  13005. return (this._activeMeshes.indexOf(mesh) !== -1);
  13006. };
  13007. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13008. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13009. var material = subMesh.getMaterial();
  13010. if (mesh.showSubMeshesBoundingBox) {
  13011. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13012. }
  13013. if (material) {
  13014. // Render targets
  13015. if (material.getRenderTargetTextures) {
  13016. if (this._processedMaterials.indexOf(material) === -1) {
  13017. this._processedMaterials.push(material);
  13018. this._renderTargets.concat(material.getRenderTargetTextures());
  13019. }
  13020. }
  13021. // Dispatch
  13022. this._activeIndices += subMesh.indexCount;
  13023. this._renderingManager.dispatch(subMesh);
  13024. }
  13025. }
  13026. };
  13027. Scene.prototype._evaluateActiveMeshes = function () {
  13028. this.activeCamera._activeMeshes.reset();
  13029. this._activeMeshes.reset();
  13030. this._renderingManager.reset();
  13031. this._processedMaterials.reset();
  13032. this._activeParticleSystems.reset();
  13033. this._activeSkeletons.reset();
  13034. this._softwareSkinnedMeshes.reset();
  13035. this._boundingBoxRenderer.reset();
  13036. this._edgesRenderers.reset();
  13037. if (!this._frustumPlanes) {
  13038. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13039. }
  13040. else {
  13041. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13042. }
  13043. // Meshes
  13044. var meshes;
  13045. var len;
  13046. if (this._selectionOctree) {
  13047. var selection = this._selectionOctree.select(this._frustumPlanes);
  13048. meshes = selection.data;
  13049. len = selection.length;
  13050. }
  13051. else {
  13052. len = this.meshes.length;
  13053. meshes = this.meshes;
  13054. }
  13055. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13056. var mesh = meshes[meshIndex];
  13057. if (mesh.isBlocked) {
  13058. continue;
  13059. }
  13060. this._totalVertices += mesh.getTotalVertices();
  13061. if (!mesh.isReady() || !mesh.isEnabled()) {
  13062. continue;
  13063. }
  13064. mesh.computeWorldMatrix();
  13065. // Intersections
  13066. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13067. this._meshesForIntersections.pushNoDuplicate(mesh);
  13068. }
  13069. // Switch to current LOD
  13070. var meshLOD = mesh.getLOD(this.activeCamera);
  13071. if (!meshLOD) {
  13072. continue;
  13073. }
  13074. mesh._preActivate();
  13075. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13076. this._activeMeshes.push(mesh);
  13077. this.activeCamera._activeMeshes.push(mesh);
  13078. mesh._activate(this._renderId);
  13079. this._activeMesh(meshLOD);
  13080. }
  13081. }
  13082. // Particle systems
  13083. var beforeParticlesDate = BABYLON.Tools.Now;
  13084. if (this.particlesEnabled) {
  13085. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13086. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13087. var particleSystem = this.particleSystems[particleIndex];
  13088. if (!particleSystem.isStarted()) {
  13089. continue;
  13090. }
  13091. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13092. this._activeParticleSystems.push(particleSystem);
  13093. particleSystem.animate();
  13094. }
  13095. }
  13096. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13097. }
  13098. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13099. };
  13100. Scene.prototype._activeMesh = function (mesh) {
  13101. if (mesh.skeleton && this.skeletonsEnabled) {
  13102. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13103. if (!mesh.computeBonesUsingShaders) {
  13104. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13105. }
  13106. }
  13107. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13108. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13109. }
  13110. if (mesh._edgesRenderer) {
  13111. this._edgesRenderers.push(mesh._edgesRenderer);
  13112. }
  13113. if (mesh && mesh.subMeshes) {
  13114. // Submeshes Octrees
  13115. var len;
  13116. var subMeshes;
  13117. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13118. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13119. len = intersections.length;
  13120. subMeshes = intersections.data;
  13121. }
  13122. else {
  13123. subMeshes = mesh.subMeshes;
  13124. len = subMeshes.length;
  13125. }
  13126. for (var subIndex = 0; subIndex < len; subIndex++) {
  13127. var subMesh = subMeshes[subIndex];
  13128. this._evaluateSubMesh(subMesh, mesh);
  13129. }
  13130. }
  13131. };
  13132. Scene.prototype.updateTransformMatrix = function (force) {
  13133. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13134. };
  13135. Scene.prototype._renderForCamera = function (camera) {
  13136. var engine = this._engine;
  13137. this.activeCamera = camera;
  13138. if (!this.activeCamera)
  13139. throw new Error("Active camera not set");
  13140. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13141. // Viewport
  13142. engine.setViewport(this.activeCamera.viewport);
  13143. // Camera
  13144. this.resetCachedMaterial();
  13145. this._renderId++;
  13146. this.updateTransformMatrix();
  13147. if (this.beforeCameraRender) {
  13148. this.beforeCameraRender(this.activeCamera);
  13149. }
  13150. // Meshes
  13151. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13152. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13153. this._evaluateActiveMeshes();
  13154. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13155. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13156. // Skeletons
  13157. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13158. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13159. skeleton.prepare();
  13160. }
  13161. // Software skinning
  13162. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13163. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13164. mesh.applySkeleton(mesh.skeleton);
  13165. }
  13166. // Render targets
  13167. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13168. if (this.renderTargetsEnabled) {
  13169. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13170. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13171. var renderTarget = this._renderTargets.data[renderIndex];
  13172. if (renderTarget._shouldRender()) {
  13173. this._renderId++;
  13174. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13175. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13176. }
  13177. }
  13178. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13179. this._renderId++;
  13180. }
  13181. if (this._renderTargets.length > 0) {
  13182. engine.restoreDefaultFramebuffer();
  13183. }
  13184. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13185. // Prepare Frame
  13186. this.postProcessManager._prepareFrame();
  13187. var beforeRenderDate = BABYLON.Tools.Now;
  13188. // Backgrounds
  13189. var layerIndex;
  13190. var layer;
  13191. if (this.layers.length) {
  13192. engine.setDepthBuffer(false);
  13193. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13194. layer = this.layers[layerIndex];
  13195. if (layer.isBackground) {
  13196. layer.render();
  13197. }
  13198. }
  13199. engine.setDepthBuffer(true);
  13200. }
  13201. // Render
  13202. BABYLON.Tools.StartPerformanceCounter("Main render");
  13203. this._renderingManager.render(null, null, true, true);
  13204. BABYLON.Tools.EndPerformanceCounter("Main render");
  13205. // Bounding boxes
  13206. this._boundingBoxRenderer.render();
  13207. // Edges
  13208. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13209. this._edgesRenderers.data[edgesRendererIndex].render();
  13210. }
  13211. // Lens flares
  13212. if (this.lensFlaresEnabled) {
  13213. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13214. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13215. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13216. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13217. lensFlareSystem.render();
  13218. }
  13219. }
  13220. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13221. }
  13222. // Foregrounds
  13223. if (this.layers.length) {
  13224. engine.setDepthBuffer(false);
  13225. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13226. layer = this.layers[layerIndex];
  13227. if (!layer.isBackground) {
  13228. layer.render();
  13229. }
  13230. }
  13231. engine.setDepthBuffer(true);
  13232. }
  13233. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13234. // Finalize frame
  13235. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13236. // Update camera
  13237. this.activeCamera._updateFromScene();
  13238. // Reset some special arrays
  13239. this._renderTargets.reset();
  13240. if (this.afterCameraRender) {
  13241. this.afterCameraRender(this.activeCamera);
  13242. }
  13243. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13244. };
  13245. Scene.prototype._processSubCameras = function (camera) {
  13246. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13247. this._renderForCamera(camera);
  13248. return;
  13249. }
  13250. // rig cameras
  13251. for (var index = 0; index < camera._rigCameras.length; index++) {
  13252. this._renderForCamera(camera._rigCameras[index]);
  13253. }
  13254. this.activeCamera = camera;
  13255. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13256. // Update camera
  13257. this.activeCamera._updateFromScene();
  13258. };
  13259. Scene.prototype._checkIntersections = function () {
  13260. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13261. var sourceMesh = this._meshesForIntersections.data[index];
  13262. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13263. var action = sourceMesh.actionManager.actions[actionIndex];
  13264. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13265. var parameters = action.getTriggerParameter();
  13266. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13267. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13268. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13269. if (areIntersecting && currentIntersectionInProgress === -1) {
  13270. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13271. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13272. sourceMesh._intersectionsInProgress.push(otherMesh);
  13273. }
  13274. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13275. sourceMesh._intersectionsInProgress.push(otherMesh);
  13276. }
  13277. }
  13278. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13279. //They intersected, and now they don't.
  13280. //is this trigger an exit trigger? execute an event.
  13281. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13282. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13283. }
  13284. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13285. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13286. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13287. }
  13288. }
  13289. }
  13290. }
  13291. }
  13292. };
  13293. Scene.prototype.render = function () {
  13294. var startDate = BABYLON.Tools.Now;
  13295. this._particlesDuration = 0;
  13296. this._spritesDuration = 0;
  13297. this._activeParticles = 0;
  13298. this._renderDuration = 0;
  13299. this._renderTargetsDuration = 0;
  13300. this._evaluateActiveMeshesDuration = 0;
  13301. this._totalVertices = 0;
  13302. this._activeIndices = 0;
  13303. this._activeBones = 0;
  13304. this.getEngine().resetDrawCalls();
  13305. this._meshesForIntersections.reset();
  13306. this.resetCachedMaterial();
  13307. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13308. // Actions
  13309. if (this.actionManager) {
  13310. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13311. }
  13312. //Simplification Queue
  13313. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13314. this.simplificationQueue.executeNext();
  13315. }
  13316. // Animations
  13317. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13318. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13319. this._animate();
  13320. // Physics
  13321. if (this._physicsEngine) {
  13322. BABYLON.Tools.StartPerformanceCounter("Physics");
  13323. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13324. BABYLON.Tools.EndPerformanceCounter("Physics");
  13325. }
  13326. // Before render
  13327. if (this.beforeRender) {
  13328. this.beforeRender();
  13329. }
  13330. var callbackIndex;
  13331. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13332. this._onBeforeRenderCallbacks[callbackIndex]();
  13333. }
  13334. // Customs render targets
  13335. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13336. var engine = this.getEngine();
  13337. var currentActiveCamera = this.activeCamera;
  13338. if (this.renderTargetsEnabled) {
  13339. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13340. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13341. var renderTarget = this.customRenderTargets[customIndex];
  13342. if (renderTarget._shouldRender()) {
  13343. this._renderId++;
  13344. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13345. if (!this.activeCamera)
  13346. throw new Error("Active camera not set");
  13347. // Viewport
  13348. engine.setViewport(this.activeCamera.viewport);
  13349. // Camera
  13350. this.updateTransformMatrix();
  13351. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13352. }
  13353. }
  13354. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13355. this._renderId++;
  13356. }
  13357. if (this.customRenderTargets.length > 0) {
  13358. engine.restoreDefaultFramebuffer();
  13359. }
  13360. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13361. this.activeCamera = currentActiveCamera;
  13362. // Procedural textures
  13363. if (this.proceduralTexturesEnabled) {
  13364. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13365. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13366. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13367. if (proceduralTexture._shouldRender()) {
  13368. proceduralTexture.render();
  13369. }
  13370. }
  13371. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13372. }
  13373. // Clear
  13374. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13375. // Shadows
  13376. if (this.shadowsEnabled) {
  13377. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13378. var light = this.lights[lightIndex];
  13379. var shadowGenerator = light.getShadowGenerator();
  13380. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13381. this._renderTargets.push(shadowGenerator.getShadowMap());
  13382. }
  13383. }
  13384. }
  13385. // Depth renderer
  13386. if (this._depthRenderer) {
  13387. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13388. }
  13389. // RenderPipeline
  13390. this.postProcessRenderPipelineManager.update();
  13391. // Multi-cameras?
  13392. if (this.activeCameras.length > 0) {
  13393. var currentRenderId = this._renderId;
  13394. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13395. this._renderId = currentRenderId;
  13396. this._processSubCameras(this.activeCameras[cameraIndex]);
  13397. }
  13398. }
  13399. else {
  13400. if (!this.activeCamera) {
  13401. throw new Error("No camera defined");
  13402. }
  13403. this._processSubCameras(this.activeCamera);
  13404. }
  13405. // Intersection checks
  13406. this._checkIntersections();
  13407. // Update the audio listener attached to the camera
  13408. if (BABYLON.AudioEngine) {
  13409. this._updateAudioParameters();
  13410. }
  13411. // After render
  13412. if (this.afterRender) {
  13413. this.afterRender();
  13414. }
  13415. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13416. this._onAfterRenderCallbacks[callbackIndex]();
  13417. }
  13418. // Cleaning
  13419. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13420. this._toBeDisposed.data[index].dispose();
  13421. this._toBeDisposed[index] = null;
  13422. }
  13423. this._toBeDisposed.reset();
  13424. if (this.dumpNextRenderTargets) {
  13425. this.dumpNextRenderTargets = false;
  13426. }
  13427. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13428. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13429. };
  13430. Scene.prototype._updateAudioParameters = function () {
  13431. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13432. return;
  13433. }
  13434. var listeningCamera;
  13435. var audioEngine = BABYLON.Engine.audioEngine;
  13436. if (this.activeCameras.length > 0) {
  13437. listeningCamera = this.activeCameras[0];
  13438. }
  13439. else {
  13440. listeningCamera = this.activeCamera;
  13441. }
  13442. if (listeningCamera && audioEngine.canUseWebAudio) {
  13443. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13444. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13445. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13446. cameraDirection.normalize();
  13447. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13448. var i;
  13449. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13450. var sound = this.mainSoundTrack.soundCollection[i];
  13451. if (sound.useCustomAttenuation) {
  13452. sound.updateDistanceFromListener();
  13453. }
  13454. }
  13455. for (i = 0; i < this.soundTracks.length; i++) {
  13456. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13457. sound = this.soundTracks[i].soundCollection[j];
  13458. if (sound.useCustomAttenuation) {
  13459. sound.updateDistanceFromListener();
  13460. }
  13461. }
  13462. }
  13463. }
  13464. };
  13465. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13466. // Audio
  13467. get: function () {
  13468. return this._audioEnabled;
  13469. },
  13470. set: function (value) {
  13471. this._audioEnabled = value;
  13472. if (BABYLON.AudioEngine) {
  13473. if (this._audioEnabled) {
  13474. this._enableAudio();
  13475. }
  13476. else {
  13477. this._disableAudio();
  13478. }
  13479. }
  13480. },
  13481. enumerable: true,
  13482. configurable: true
  13483. });
  13484. Scene.prototype._disableAudio = function () {
  13485. var i;
  13486. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13487. this.mainSoundTrack.soundCollection[i].pause();
  13488. }
  13489. for (i = 0; i < this.soundTracks.length; i++) {
  13490. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13491. this.soundTracks[i].soundCollection[j].pause();
  13492. }
  13493. }
  13494. };
  13495. Scene.prototype._enableAudio = function () {
  13496. var i;
  13497. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13498. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13499. this.mainSoundTrack.soundCollection[i].play();
  13500. }
  13501. }
  13502. for (i = 0; i < this.soundTracks.length; i++) {
  13503. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13504. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13505. this.soundTracks[i].soundCollection[j].play();
  13506. }
  13507. }
  13508. }
  13509. };
  13510. Object.defineProperty(Scene.prototype, "headphone", {
  13511. get: function () {
  13512. return this._headphone;
  13513. },
  13514. set: function (value) {
  13515. this._headphone = value;
  13516. if (BABYLON.AudioEngine) {
  13517. if (this._headphone) {
  13518. this._switchAudioModeForHeadphones();
  13519. }
  13520. else {
  13521. this._switchAudioModeForNormalSpeakers();
  13522. }
  13523. }
  13524. },
  13525. enumerable: true,
  13526. configurable: true
  13527. });
  13528. Scene.prototype._switchAudioModeForHeadphones = function () {
  13529. this.mainSoundTrack.switchPanningModelToHRTF();
  13530. for (var i = 0; i < this.soundTracks.length; i++) {
  13531. this.soundTracks[i].switchPanningModelToHRTF();
  13532. }
  13533. };
  13534. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13535. this.mainSoundTrack.switchPanningModelToEqualPower();
  13536. for (var i = 0; i < this.soundTracks.length; i++) {
  13537. this.soundTracks[i].switchPanningModelToEqualPower();
  13538. }
  13539. };
  13540. Scene.prototype.enableDepthRenderer = function () {
  13541. if (this._depthRenderer) {
  13542. return this._depthRenderer;
  13543. }
  13544. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13545. return this._depthRenderer;
  13546. };
  13547. Scene.prototype.disableDepthRenderer = function () {
  13548. if (!this._depthRenderer) {
  13549. return;
  13550. }
  13551. this._depthRenderer.dispose();
  13552. this._depthRenderer = null;
  13553. };
  13554. Scene.prototype.dispose = function () {
  13555. this.beforeRender = null;
  13556. this.afterRender = null;
  13557. this.skeletons = [];
  13558. this._boundingBoxRenderer.dispose();
  13559. if (this._depthRenderer) {
  13560. this._depthRenderer.dispose();
  13561. }
  13562. // Debug layer
  13563. this.debugLayer.hide();
  13564. // Events
  13565. if (this.onDispose) {
  13566. this.onDispose();
  13567. }
  13568. this._onBeforeRenderCallbacks = [];
  13569. this._onAfterRenderCallbacks = [];
  13570. this.detachControl();
  13571. // Release sounds & sounds tracks
  13572. if (BABYLON.AudioEngine) {
  13573. this.disposeSounds();
  13574. }
  13575. // Detach cameras
  13576. var canvas = this._engine.getRenderingCanvas();
  13577. var index;
  13578. for (index = 0; index < this.cameras.length; index++) {
  13579. this.cameras[index].detachControl(canvas);
  13580. }
  13581. // Release lights
  13582. while (this.lights.length) {
  13583. this.lights[0].dispose();
  13584. }
  13585. // Release meshes
  13586. while (this.meshes.length) {
  13587. this.meshes[0].dispose(true);
  13588. }
  13589. // Release cameras
  13590. while (this.cameras.length) {
  13591. this.cameras[0].dispose();
  13592. }
  13593. // Release materials
  13594. while (this.materials.length) {
  13595. this.materials[0].dispose();
  13596. }
  13597. // Release particles
  13598. while (this.particleSystems.length) {
  13599. this.particleSystems[0].dispose();
  13600. }
  13601. // Release sprites
  13602. while (this.spriteManagers.length) {
  13603. this.spriteManagers[0].dispose();
  13604. }
  13605. // Release layers
  13606. while (this.layers.length) {
  13607. this.layers[0].dispose();
  13608. }
  13609. // Release textures
  13610. while (this.textures.length) {
  13611. this.textures[0].dispose();
  13612. }
  13613. // Post-processes
  13614. this.postProcessManager.dispose();
  13615. // Physics
  13616. if (this._physicsEngine) {
  13617. this.disablePhysicsEngine();
  13618. }
  13619. // Remove from engine
  13620. index = this._engine.scenes.indexOf(this);
  13621. if (index > -1) {
  13622. this._engine.scenes.splice(index, 1);
  13623. }
  13624. this._engine.wipeCaches();
  13625. };
  13626. // Release sounds & sounds tracks
  13627. Scene.prototype.disposeSounds = function () {
  13628. this.mainSoundTrack.dispose();
  13629. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13630. this.soundTracks[scIndex].dispose();
  13631. }
  13632. };
  13633. // Octrees
  13634. Scene.prototype.getWorldExtends = function () {
  13635. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13636. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13637. for (var index = 0; index < this.meshes.length; index++) {
  13638. var mesh = this.meshes[index];
  13639. mesh.computeWorldMatrix(true);
  13640. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13641. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13642. BABYLON.Tools.CheckExtends(minBox, min, max);
  13643. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13644. }
  13645. return {
  13646. min: min,
  13647. max: max
  13648. };
  13649. };
  13650. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13651. if (maxCapacity === void 0) { maxCapacity = 64; }
  13652. if (maxDepth === void 0) { maxDepth = 2; }
  13653. if (!this._selectionOctree) {
  13654. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13655. }
  13656. var worldExtends = this.getWorldExtends();
  13657. // Update octree
  13658. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13659. return this._selectionOctree;
  13660. };
  13661. // Picking
  13662. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13663. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13664. var engine = this._engine;
  13665. if (!camera) {
  13666. if (!this.activeCamera)
  13667. throw new Error("Active camera not set");
  13668. camera = this.activeCamera;
  13669. }
  13670. var cameraViewport = camera.viewport;
  13671. var viewport = cameraViewport.toGlobal(engine);
  13672. // Moving coordinates to local viewport world
  13673. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13674. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13675. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13676. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13677. };
  13678. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13679. var engine = this._engine;
  13680. if (!camera) {
  13681. if (!this.activeCamera)
  13682. throw new Error("Active camera not set");
  13683. camera = this.activeCamera;
  13684. }
  13685. var cameraViewport = camera.viewport;
  13686. var viewport = cameraViewport.toGlobal(engine);
  13687. var identity = BABYLON.Matrix.Identity();
  13688. // Moving coordinates to local viewport world
  13689. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13690. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13691. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13692. };
  13693. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13694. var pickingInfo = null;
  13695. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13696. var mesh = this.meshes[meshIndex];
  13697. if (predicate) {
  13698. if (!predicate(mesh)) {
  13699. continue;
  13700. }
  13701. }
  13702. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13703. continue;
  13704. }
  13705. var world = mesh.getWorldMatrix();
  13706. var ray = rayFunction(world);
  13707. var result = mesh.intersects(ray, fastCheck);
  13708. if (!result || !result.hit)
  13709. continue;
  13710. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13711. continue;
  13712. pickingInfo = result;
  13713. if (fastCheck) {
  13714. break;
  13715. }
  13716. }
  13717. return pickingInfo || new BABYLON.PickingInfo();
  13718. };
  13719. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13720. var pickingInfo = null;
  13721. camera = camera || this.activeCamera;
  13722. if (this.spriteManagers.length > 0) {
  13723. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13724. var spriteManager = this.spriteManagers[spriteIndex];
  13725. if (!spriteManager.isPickable) {
  13726. continue;
  13727. }
  13728. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13729. if (!result || !result.hit)
  13730. continue;
  13731. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13732. continue;
  13733. pickingInfo = result;
  13734. if (fastCheck) {
  13735. break;
  13736. }
  13737. }
  13738. }
  13739. return pickingInfo || new BABYLON.PickingInfo();
  13740. };
  13741. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13742. var _this = this;
  13743. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13744. /// <param name="x">X position on screen</param>
  13745. /// <param name="y">Y position on screen</param>
  13746. /// <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>
  13747. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13748. /// <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>
  13749. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13750. };
  13751. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13752. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13753. /// <param name="x">X position on screen</param>
  13754. /// <param name="y">Y position on screen</param>
  13755. /// <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>
  13756. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13757. /// <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>
  13758. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13759. };
  13760. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13761. var _this = this;
  13762. return this._internalPick(function (world) {
  13763. if (!_this._pickWithRayInverseMatrix) {
  13764. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13765. }
  13766. world.invertToRef(_this._pickWithRayInverseMatrix);
  13767. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13768. }, predicate, fastCheck);
  13769. };
  13770. Scene.prototype.setPointerOverMesh = function (mesh) {
  13771. if (this._pointerOverMesh === mesh) {
  13772. return;
  13773. }
  13774. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13775. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13776. }
  13777. this._pointerOverMesh = mesh;
  13778. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13779. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13780. }
  13781. };
  13782. Scene.prototype.getPointerOverMesh = function () {
  13783. return this._pointerOverMesh;
  13784. };
  13785. // Physics
  13786. Scene.prototype.getPhysicsEngine = function () {
  13787. return this._physicsEngine;
  13788. };
  13789. /**
  13790. * Enables physics to the current scene
  13791. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13792. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13793. * @return {boolean} was the physics engine initialized
  13794. */
  13795. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13796. if (this._physicsEngine) {
  13797. return true;
  13798. }
  13799. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13800. if (!this._physicsEngine.isSupported()) {
  13801. this._physicsEngine = null;
  13802. return false;
  13803. }
  13804. this._physicsEngine._initialize(gravity);
  13805. return true;
  13806. };
  13807. Scene.prototype.disablePhysicsEngine = function () {
  13808. if (!this._physicsEngine) {
  13809. return;
  13810. }
  13811. this._physicsEngine.dispose();
  13812. this._physicsEngine = undefined;
  13813. };
  13814. Scene.prototype.isPhysicsEnabled = function () {
  13815. return this._physicsEngine !== undefined;
  13816. };
  13817. /**
  13818. * Sets the gravity of the physics engine (and NOT of the scene)
  13819. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13820. */
  13821. Scene.prototype.setGravity = function (gravity) {
  13822. if (!this._physicsEngine) {
  13823. return;
  13824. }
  13825. this._physicsEngine._setGravity(gravity);
  13826. };
  13827. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13828. if (parts.parts) {
  13829. options = parts;
  13830. parts = parts.parts;
  13831. }
  13832. if (!this._physicsEngine) {
  13833. return null;
  13834. }
  13835. for (var index = 0; index < parts.length; index++) {
  13836. var mesh = parts[index].mesh;
  13837. mesh._physicImpostor = parts[index].impostor;
  13838. mesh._physicsMass = options.mass / parts.length;
  13839. mesh._physicsFriction = options.friction;
  13840. mesh._physicRestitution = options.restitution;
  13841. }
  13842. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13843. };
  13844. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13845. for (var index = 0; index < compound.parts.length; index++) {
  13846. var mesh = compound.parts[index].mesh;
  13847. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13848. this._physicsEngine._unregisterMesh(mesh);
  13849. }
  13850. };
  13851. // Misc.
  13852. Scene.prototype.createDefaultCameraOrLight = function () {
  13853. // Light
  13854. if (this.lights.length === 0) {
  13855. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13856. }
  13857. // Camera
  13858. if (!this.activeCamera) {
  13859. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13860. // Compute position
  13861. var worldExtends = this.getWorldExtends();
  13862. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13863. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13864. camera.setTarget(worldCenter);
  13865. this.activeCamera = camera;
  13866. }
  13867. };
  13868. // Tags
  13869. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13870. if (tagsQuery === undefined) {
  13871. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13872. return list;
  13873. }
  13874. var listByTags = [];
  13875. forEach = forEach || (function (item) { return; });
  13876. for (var i in list) {
  13877. var item = list[i];
  13878. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13879. listByTags.push(item);
  13880. forEach(item);
  13881. }
  13882. }
  13883. return listByTags;
  13884. };
  13885. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13886. return this._getByTags(this.meshes, tagsQuery, forEach);
  13887. };
  13888. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13889. return this._getByTags(this.cameras, tagsQuery, forEach);
  13890. };
  13891. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13892. return this._getByTags(this.lights, tagsQuery, forEach);
  13893. };
  13894. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13895. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13896. };
  13897. // Statics
  13898. Scene._FOGMODE_NONE = 0;
  13899. Scene._FOGMODE_EXP = 1;
  13900. Scene._FOGMODE_EXP2 = 2;
  13901. Scene._FOGMODE_LINEAR = 3;
  13902. Scene.MinDeltaTime = 1.0;
  13903. Scene.MaxDeltaTime = 1000.0;
  13904. return Scene;
  13905. })();
  13906. BABYLON.Scene = Scene;
  13907. })(BABYLON || (BABYLON = {}));
  13908. var BABYLON;
  13909. (function (BABYLON) {
  13910. var VertexBuffer = (function () {
  13911. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13912. if (engine instanceof BABYLON.Mesh) {
  13913. this._engine = engine.getScene().getEngine();
  13914. }
  13915. else {
  13916. this._engine = engine;
  13917. }
  13918. this._updatable = updatable;
  13919. this._data = data;
  13920. if (!postponeInternalCreation) {
  13921. this.create();
  13922. }
  13923. this._kind = kind;
  13924. if (stride) {
  13925. this._strideSize = stride;
  13926. return;
  13927. }
  13928. // Deduce stride from kind
  13929. switch (kind) {
  13930. case VertexBuffer.PositionKind:
  13931. this._strideSize = 3;
  13932. break;
  13933. case VertexBuffer.NormalKind:
  13934. this._strideSize = 3;
  13935. break;
  13936. case VertexBuffer.UVKind:
  13937. case VertexBuffer.UV2Kind:
  13938. case VertexBuffer.UV3Kind:
  13939. case VertexBuffer.UV4Kind:
  13940. case VertexBuffer.UV5Kind:
  13941. case VertexBuffer.UV6Kind:
  13942. this._strideSize = 2;
  13943. break;
  13944. case VertexBuffer.ColorKind:
  13945. this._strideSize = 4;
  13946. break;
  13947. case VertexBuffer.MatricesIndicesKind:
  13948. case VertexBuffer.MatricesIndicesExtraKind:
  13949. this._strideSize = 4;
  13950. break;
  13951. case VertexBuffer.MatricesWeightsKind:
  13952. case VertexBuffer.MatricesWeightsExtraKind:
  13953. this._strideSize = 4;
  13954. break;
  13955. }
  13956. }
  13957. // Properties
  13958. VertexBuffer.prototype.isUpdatable = function () {
  13959. return this._updatable;
  13960. };
  13961. VertexBuffer.prototype.getData = function () {
  13962. return this._data;
  13963. };
  13964. VertexBuffer.prototype.getBuffer = function () {
  13965. return this._buffer;
  13966. };
  13967. VertexBuffer.prototype.getStrideSize = function () {
  13968. return this._strideSize;
  13969. };
  13970. // Methods
  13971. VertexBuffer.prototype.create = function (data) {
  13972. if (!data && this._buffer) {
  13973. return; // nothing to do
  13974. }
  13975. data = data || this._data;
  13976. if (!this._buffer) {
  13977. if (this._updatable) {
  13978. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13979. }
  13980. else {
  13981. this._buffer = this._engine.createVertexBuffer(data);
  13982. }
  13983. }
  13984. if (this._updatable) {
  13985. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13986. this._data = data;
  13987. }
  13988. };
  13989. VertexBuffer.prototype.update = function (data) {
  13990. this.create(data);
  13991. };
  13992. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13993. if (!this._buffer) {
  13994. return;
  13995. }
  13996. if (this._updatable) {
  13997. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13998. this._data = null;
  13999. }
  14000. };
  14001. VertexBuffer.prototype.dispose = function () {
  14002. if (!this._buffer) {
  14003. return;
  14004. }
  14005. if (this._engine._releaseBuffer(this._buffer)) {
  14006. this._buffer = null;
  14007. }
  14008. };
  14009. Object.defineProperty(VertexBuffer, "PositionKind", {
  14010. get: function () {
  14011. return VertexBuffer._PositionKind;
  14012. },
  14013. enumerable: true,
  14014. configurable: true
  14015. });
  14016. Object.defineProperty(VertexBuffer, "NormalKind", {
  14017. get: function () {
  14018. return VertexBuffer._NormalKind;
  14019. },
  14020. enumerable: true,
  14021. configurable: true
  14022. });
  14023. Object.defineProperty(VertexBuffer, "UVKind", {
  14024. get: function () {
  14025. return VertexBuffer._UVKind;
  14026. },
  14027. enumerable: true,
  14028. configurable: true
  14029. });
  14030. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14031. get: function () {
  14032. return VertexBuffer._UV2Kind;
  14033. },
  14034. enumerable: true,
  14035. configurable: true
  14036. });
  14037. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14038. get: function () {
  14039. return VertexBuffer._UV3Kind;
  14040. },
  14041. enumerable: true,
  14042. configurable: true
  14043. });
  14044. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14045. get: function () {
  14046. return VertexBuffer._UV4Kind;
  14047. },
  14048. enumerable: true,
  14049. configurable: true
  14050. });
  14051. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14052. get: function () {
  14053. return VertexBuffer._UV5Kind;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14059. get: function () {
  14060. return VertexBuffer._UV6Kind;
  14061. },
  14062. enumerable: true,
  14063. configurable: true
  14064. });
  14065. Object.defineProperty(VertexBuffer, "ColorKind", {
  14066. get: function () {
  14067. return VertexBuffer._ColorKind;
  14068. },
  14069. enumerable: true,
  14070. configurable: true
  14071. });
  14072. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14073. get: function () {
  14074. return VertexBuffer._MatricesIndicesKind;
  14075. },
  14076. enumerable: true,
  14077. configurable: true
  14078. });
  14079. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14080. get: function () {
  14081. return VertexBuffer._MatricesWeightsKind;
  14082. },
  14083. enumerable: true,
  14084. configurable: true
  14085. });
  14086. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14087. get: function () {
  14088. return VertexBuffer._MatricesIndicesExtraKind;
  14089. },
  14090. enumerable: true,
  14091. configurable: true
  14092. });
  14093. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14094. get: function () {
  14095. return VertexBuffer._MatricesWeightsExtraKind;
  14096. },
  14097. enumerable: true,
  14098. configurable: true
  14099. });
  14100. // Enums
  14101. VertexBuffer._PositionKind = "position";
  14102. VertexBuffer._NormalKind = "normal";
  14103. VertexBuffer._UVKind = "uv";
  14104. VertexBuffer._UV2Kind = "uv2";
  14105. VertexBuffer._UV3Kind = "uv3";
  14106. VertexBuffer._UV4Kind = "uv4";
  14107. VertexBuffer._UV5Kind = "uv5";
  14108. VertexBuffer._UV6Kind = "uv6";
  14109. VertexBuffer._ColorKind = "color";
  14110. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14111. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14112. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14113. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14114. return VertexBuffer;
  14115. })();
  14116. BABYLON.VertexBuffer = VertexBuffer;
  14117. })(BABYLON || (BABYLON = {}));
  14118. var BABYLON;
  14119. (function (BABYLON) {
  14120. /**
  14121. * Creates an instance based on a source mesh.
  14122. */
  14123. var InstancedMesh = (function (_super) {
  14124. __extends(InstancedMesh, _super);
  14125. function InstancedMesh(name, source) {
  14126. _super.call(this, name, source.getScene());
  14127. source.instances.push(this);
  14128. this._sourceMesh = source;
  14129. this.position.copyFrom(source.position);
  14130. this.rotation.copyFrom(source.rotation);
  14131. this.scaling.copyFrom(source.scaling);
  14132. if (source.rotationQuaternion) {
  14133. this.rotationQuaternion = source.rotationQuaternion.clone();
  14134. }
  14135. this.infiniteDistance = source.infiniteDistance;
  14136. this.setPivotMatrix(source.getPivotMatrix());
  14137. this.refreshBoundingInfo();
  14138. this._syncSubMeshes();
  14139. }
  14140. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14141. // Methods
  14142. get: function () {
  14143. return this._sourceMesh.receiveShadows;
  14144. },
  14145. enumerable: true,
  14146. configurable: true
  14147. });
  14148. Object.defineProperty(InstancedMesh.prototype, "material", {
  14149. get: function () {
  14150. return this._sourceMesh.material;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14156. get: function () {
  14157. return this._sourceMesh.visibility;
  14158. },
  14159. enumerable: true,
  14160. configurable: true
  14161. });
  14162. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14163. get: function () {
  14164. return this._sourceMesh.skeleton;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14170. get: function () {
  14171. return this._sourceMesh.renderingGroupId;
  14172. },
  14173. enumerable: true,
  14174. configurable: true
  14175. });
  14176. InstancedMesh.prototype.getTotalVertices = function () {
  14177. return this._sourceMesh.getTotalVertices();
  14178. };
  14179. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14180. get: function () {
  14181. return this._sourceMesh;
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14187. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14188. };
  14189. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14190. return this._sourceMesh.isVerticesDataPresent(kind);
  14191. };
  14192. InstancedMesh.prototype.getIndices = function () {
  14193. return this._sourceMesh.getIndices();
  14194. };
  14195. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14196. get: function () {
  14197. return this._sourceMesh._positions;
  14198. },
  14199. enumerable: true,
  14200. configurable: true
  14201. });
  14202. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14203. var meshBB = this._sourceMesh.getBoundingInfo();
  14204. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14205. this._updateBoundingInfo();
  14206. };
  14207. InstancedMesh.prototype._preActivate = function () {
  14208. if (this._currentLOD) {
  14209. this._currentLOD._preActivate();
  14210. }
  14211. };
  14212. InstancedMesh.prototype._activate = function (renderId) {
  14213. if (this._currentLOD) {
  14214. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14215. }
  14216. };
  14217. InstancedMesh.prototype.getLOD = function (camera) {
  14218. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14219. if (this._currentLOD === this.sourceMesh) {
  14220. return this;
  14221. }
  14222. return this._currentLOD;
  14223. };
  14224. InstancedMesh.prototype._syncSubMeshes = function () {
  14225. this.releaseSubMeshes();
  14226. if (this._sourceMesh.subMeshes) {
  14227. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14228. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14229. }
  14230. }
  14231. };
  14232. InstancedMesh.prototype._generatePointsArray = function () {
  14233. return this._sourceMesh._generatePointsArray();
  14234. };
  14235. // Clone
  14236. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14237. var result = this._sourceMesh.createInstance(name);
  14238. // Deep copy
  14239. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14240. // Bounding info
  14241. this.refreshBoundingInfo();
  14242. // Parent
  14243. if (newParent) {
  14244. result.parent = newParent;
  14245. }
  14246. if (!doNotCloneChildren) {
  14247. // Children
  14248. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14249. var mesh = this.getScene().meshes[index];
  14250. if (mesh.parent === this) {
  14251. mesh.clone(mesh.name, result);
  14252. }
  14253. }
  14254. }
  14255. result.computeWorldMatrix(true);
  14256. return result;
  14257. };
  14258. // Dispoe
  14259. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14260. // Remove from mesh
  14261. var index = this._sourceMesh.instances.indexOf(this);
  14262. this._sourceMesh.instances.splice(index, 1);
  14263. _super.prototype.dispose.call(this, doNotRecurse);
  14264. };
  14265. return InstancedMesh;
  14266. })(BABYLON.AbstractMesh);
  14267. BABYLON.InstancedMesh = InstancedMesh;
  14268. })(BABYLON || (BABYLON = {}));
  14269. var BABYLON;
  14270. (function (BABYLON) {
  14271. var _InstancesBatch = (function () {
  14272. function _InstancesBatch() {
  14273. this.mustReturn = false;
  14274. this.visibleInstances = new Array();
  14275. this.renderSelf = new Array();
  14276. }
  14277. return _InstancesBatch;
  14278. })();
  14279. BABYLON._InstancesBatch = _InstancesBatch;
  14280. var Mesh = (function (_super) {
  14281. __extends(Mesh, _super);
  14282. /**
  14283. * @constructor
  14284. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14285. * @param {Scene} scene - The scene to add this mesh to.
  14286. * @param {Node} parent - The parent of this mesh, if it has one
  14287. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14288. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14289. * When false, achieved by calling a clone(), also passing False.
  14290. * This will make creation of children, recursive.
  14291. */
  14292. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14293. if (parent === void 0) { parent = null; }
  14294. _super.call(this, name, scene);
  14295. // Members
  14296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14297. this.instances = new Array();
  14298. this._LODLevels = new Array();
  14299. this._onBeforeRenderCallbacks = new Array();
  14300. this._onAfterRenderCallbacks = new Array();
  14301. this._visibleInstances = {};
  14302. this._renderIdForInstances = new Array();
  14303. this._batchCache = new _InstancesBatch();
  14304. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14305. this._sideOrientation = Mesh._DEFAULTSIDE;
  14306. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14307. if (source) {
  14308. // Geometry
  14309. if (source._geometry) {
  14310. source._geometry.applyToMesh(this);
  14311. }
  14312. // Deep copy
  14313. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14314. this.id = name + "." + source.id;
  14315. // Material
  14316. this.material = source.material;
  14317. var index;
  14318. if (!doNotCloneChildren) {
  14319. // Children
  14320. for (index = 0; index < scene.meshes.length; index++) {
  14321. var mesh = scene.meshes[index];
  14322. if (mesh.parent === source) {
  14323. // doNotCloneChildren is always going to be False
  14324. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14325. }
  14326. }
  14327. }
  14328. // Particles
  14329. for (index = 0; index < scene.particleSystems.length; index++) {
  14330. var system = scene.particleSystems[index];
  14331. if (system.emitter === source) {
  14332. system.clone(system.name, this);
  14333. }
  14334. }
  14335. this.computeWorldMatrix(true);
  14336. }
  14337. // Parent
  14338. if (parent !== null) {
  14339. this.parent = parent;
  14340. }
  14341. }
  14342. Object.defineProperty(Mesh, "FRONTSIDE", {
  14343. get: function () {
  14344. return Mesh._FRONTSIDE;
  14345. },
  14346. enumerable: true,
  14347. configurable: true
  14348. });
  14349. Object.defineProperty(Mesh, "BACKSIDE", {
  14350. get: function () {
  14351. return Mesh._BACKSIDE;
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14357. get: function () {
  14358. return Mesh._DOUBLESIDE;
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14364. get: function () {
  14365. return Mesh._DEFAULTSIDE;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(Mesh, "NO_CAP", {
  14371. get: function () {
  14372. return Mesh._NO_CAP;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(Mesh, "CAP_START", {
  14378. get: function () {
  14379. return Mesh._CAP_START;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(Mesh, "CAP_END", {
  14385. get: function () {
  14386. return Mesh._CAP_END;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. Object.defineProperty(Mesh, "CAP_ALL", {
  14392. get: function () {
  14393. return Mesh._CAP_ALL;
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14399. // Methods
  14400. get: function () {
  14401. return this._LODLevels.length > 0;
  14402. },
  14403. enumerable: true,
  14404. configurable: true
  14405. });
  14406. Mesh.prototype._sortLODLevels = function () {
  14407. this._LODLevels.sort(function (a, b) {
  14408. if (a.distance < b.distance) {
  14409. return 1;
  14410. }
  14411. if (a.distance > b.distance) {
  14412. return -1;
  14413. }
  14414. return 0;
  14415. });
  14416. };
  14417. /**
  14418. * Add a mesh as LOD level triggered at the given distance.
  14419. * @param {number} distance - the distance from the center of the object to show this level
  14420. * @param {Mesh} mesh - the mesh to be added as LOD level
  14421. * @return {Mesh} this mesh (for chaining)
  14422. */
  14423. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14424. if (mesh && mesh._masterMesh) {
  14425. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14426. return this;
  14427. }
  14428. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14429. this._LODLevels.push(level);
  14430. if (mesh) {
  14431. mesh._masterMesh = this;
  14432. }
  14433. this._sortLODLevels();
  14434. return this;
  14435. };
  14436. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14437. for (var index = 0; index < this._LODLevels.length; index++) {
  14438. var level = this._LODLevels[index];
  14439. if (level.distance === distance) {
  14440. return level.mesh;
  14441. }
  14442. }
  14443. return null;
  14444. };
  14445. /**
  14446. * Remove a mesh from the LOD array
  14447. * @param {Mesh} mesh - the mesh to be removed.
  14448. * @return {Mesh} this mesh (for chaining)
  14449. */
  14450. Mesh.prototype.removeLODLevel = function (mesh) {
  14451. for (var index = 0; index < this._LODLevels.length; index++) {
  14452. if (this._LODLevels[index].mesh === mesh) {
  14453. this._LODLevels.splice(index, 1);
  14454. if (mesh) {
  14455. mesh._masterMesh = null;
  14456. }
  14457. }
  14458. }
  14459. this._sortLODLevels();
  14460. return this;
  14461. };
  14462. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14463. if (!this._LODLevels || this._LODLevels.length === 0) {
  14464. return this;
  14465. }
  14466. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14467. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14468. if (this.onLODLevelSelection) {
  14469. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14470. }
  14471. return this;
  14472. }
  14473. for (var index = 0; index < this._LODLevels.length; index++) {
  14474. var level = this._LODLevels[index];
  14475. if (level.distance < distanceToCamera) {
  14476. if (level.mesh) {
  14477. level.mesh._preActivate();
  14478. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14479. }
  14480. if (this.onLODLevelSelection) {
  14481. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14482. }
  14483. return level.mesh;
  14484. }
  14485. }
  14486. if (this.onLODLevelSelection) {
  14487. this.onLODLevelSelection(distanceToCamera, this, this);
  14488. }
  14489. return this;
  14490. };
  14491. Object.defineProperty(Mesh.prototype, "geometry", {
  14492. get: function () {
  14493. return this._geometry;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Mesh.prototype.getTotalVertices = function () {
  14499. if (!this._geometry) {
  14500. return 0;
  14501. }
  14502. return this._geometry.getTotalVertices();
  14503. };
  14504. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14505. if (!this._geometry) {
  14506. return null;
  14507. }
  14508. return this._geometry.getVerticesData(kind, copyWhenShared);
  14509. };
  14510. Mesh.prototype.getVertexBuffer = function (kind) {
  14511. if (!this._geometry) {
  14512. return undefined;
  14513. }
  14514. return this._geometry.getVertexBuffer(kind);
  14515. };
  14516. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14517. if (!this._geometry) {
  14518. if (this._delayInfo) {
  14519. return this._delayInfo.indexOf(kind) !== -1;
  14520. }
  14521. return false;
  14522. }
  14523. return this._geometry.isVerticesDataPresent(kind);
  14524. };
  14525. Mesh.prototype.getVerticesDataKinds = function () {
  14526. if (!this._geometry) {
  14527. var result = [];
  14528. if (this._delayInfo) {
  14529. for (var kind in this._delayInfo) {
  14530. result.push(kind);
  14531. }
  14532. }
  14533. return result;
  14534. }
  14535. return this._geometry.getVerticesDataKinds();
  14536. };
  14537. Mesh.prototype.getTotalIndices = function () {
  14538. if (!this._geometry) {
  14539. return 0;
  14540. }
  14541. return this._geometry.getTotalIndices();
  14542. };
  14543. Mesh.prototype.getIndices = function (copyWhenShared) {
  14544. if (!this._geometry) {
  14545. return [];
  14546. }
  14547. return this._geometry.getIndices(copyWhenShared);
  14548. };
  14549. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14550. get: function () {
  14551. return this._masterMesh !== null && this._masterMesh !== undefined;
  14552. },
  14553. enumerable: true,
  14554. configurable: true
  14555. });
  14556. Mesh.prototype.isReady = function () {
  14557. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14558. return false;
  14559. }
  14560. return _super.prototype.isReady.call(this);
  14561. };
  14562. Mesh.prototype.isDisposed = function () {
  14563. return this._isDisposed;
  14564. };
  14565. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14566. get: function () {
  14567. return this._sideOrientation;
  14568. },
  14569. set: function (sideO) {
  14570. this._sideOrientation = sideO;
  14571. },
  14572. enumerable: true,
  14573. configurable: true
  14574. });
  14575. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14576. get: function () {
  14577. return this._areNormalsFrozen;
  14578. },
  14579. enumerable: true,
  14580. configurable: true
  14581. });
  14582. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14583. Mesh.prototype.freezeNormals = function () {
  14584. this._areNormalsFrozen = true;
  14585. };
  14586. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14587. Mesh.prototype.unfreezeNormals = function () {
  14588. this._areNormalsFrozen = false;
  14589. };
  14590. // Methods
  14591. Mesh.prototype._preActivate = function () {
  14592. var sceneRenderId = this.getScene().getRenderId();
  14593. if (this._preActivateId === sceneRenderId) {
  14594. return;
  14595. }
  14596. this._preActivateId = sceneRenderId;
  14597. this._visibleInstances = null;
  14598. };
  14599. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14600. if (!this._visibleInstances) {
  14601. this._visibleInstances = {};
  14602. this._visibleInstances.defaultRenderId = renderId;
  14603. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14604. }
  14605. if (!this._visibleInstances[renderId]) {
  14606. this._visibleInstances[renderId] = new Array();
  14607. }
  14608. this._visibleInstances[renderId].push(instance);
  14609. };
  14610. Mesh.prototype.refreshBoundingInfo = function () {
  14611. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14612. if (data) {
  14613. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14614. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14615. }
  14616. if (this.subMeshes) {
  14617. for (var index = 0; index < this.subMeshes.length; index++) {
  14618. this.subMeshes[index].refreshBoundingInfo();
  14619. }
  14620. }
  14621. this._updateBoundingInfo();
  14622. };
  14623. Mesh.prototype._createGlobalSubMesh = function () {
  14624. var totalVertices = this.getTotalVertices();
  14625. if (!totalVertices || !this.getIndices()) {
  14626. return null;
  14627. }
  14628. this.releaseSubMeshes();
  14629. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14630. };
  14631. Mesh.prototype.subdivide = function (count) {
  14632. if (count < 1) {
  14633. return;
  14634. }
  14635. var totalIndices = this.getTotalIndices();
  14636. var subdivisionSize = (totalIndices / count) | 0;
  14637. var offset = 0;
  14638. // Ensure that subdivisionSize is a multiple of 3
  14639. while (subdivisionSize % 3 !== 0) {
  14640. subdivisionSize++;
  14641. }
  14642. this.releaseSubMeshes();
  14643. for (var index = 0; index < count; index++) {
  14644. if (offset >= totalIndices) {
  14645. break;
  14646. }
  14647. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14648. offset += subdivisionSize;
  14649. }
  14650. this.synchronizeInstances();
  14651. };
  14652. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14653. if (!this._geometry) {
  14654. var vertexData = new BABYLON.VertexData();
  14655. vertexData.set(data, kind);
  14656. var scene = this.getScene();
  14657. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14658. }
  14659. else {
  14660. this._geometry.setVerticesData(kind, data, updatable, stride);
  14661. }
  14662. };
  14663. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14664. if (!this._geometry) {
  14665. return;
  14666. }
  14667. if (!makeItUnique) {
  14668. this._geometry.updateVerticesData(kind, data, updateExtends);
  14669. }
  14670. else {
  14671. this.makeGeometryUnique();
  14672. this.updateVerticesData(kind, data, updateExtends, false);
  14673. }
  14674. };
  14675. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14676. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14677. if (!this._geometry) {
  14678. return;
  14679. }
  14680. if (!makeItUnique) {
  14681. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14682. }
  14683. else {
  14684. this.makeGeometryUnique();
  14685. this.updateVerticesDataDirectly(kind, data, offset, false);
  14686. }
  14687. };
  14688. // Mesh positions update function :
  14689. // updates the mesh positions according to the positionFunction returned values.
  14690. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14691. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14692. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14693. if (computeNormals === void 0) { computeNormals = true; }
  14694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14695. positionFunction(positions);
  14696. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14697. if (computeNormals) {
  14698. var indices = this.getIndices();
  14699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14700. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14701. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14702. }
  14703. };
  14704. Mesh.prototype.makeGeometryUnique = function () {
  14705. if (!this._geometry) {
  14706. return;
  14707. }
  14708. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14709. geometry.applyToMesh(this);
  14710. };
  14711. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14712. if (!this._geometry) {
  14713. var vertexData = new BABYLON.VertexData();
  14714. vertexData.indices = indices;
  14715. var scene = this.getScene();
  14716. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14717. }
  14718. else {
  14719. this._geometry.setIndices(indices, totalVertices);
  14720. }
  14721. };
  14722. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14723. var engine = this.getScene().getEngine();
  14724. // Wireframe
  14725. var indexToBind;
  14726. switch (fillMode) {
  14727. case BABYLON.Material.PointFillMode:
  14728. indexToBind = null;
  14729. break;
  14730. case BABYLON.Material.WireFrameFillMode:
  14731. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14732. break;
  14733. default:
  14734. case BABYLON.Material.TriangleFillMode:
  14735. indexToBind = this._geometry.getIndexBuffer();
  14736. break;
  14737. }
  14738. // VBOs
  14739. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14740. };
  14741. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14742. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14743. return;
  14744. }
  14745. var engine = this.getScene().getEngine();
  14746. // Draw order
  14747. switch (fillMode) {
  14748. case BABYLON.Material.PointFillMode:
  14749. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14750. break;
  14751. case BABYLON.Material.WireFrameFillMode:
  14752. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14753. break;
  14754. default:
  14755. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14756. }
  14757. };
  14758. Mesh.prototype.registerBeforeRender = function (func) {
  14759. this._onBeforeRenderCallbacks.push(func);
  14760. };
  14761. Mesh.prototype.unregisterBeforeRender = function (func) {
  14762. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14763. if (index > -1) {
  14764. this._onBeforeRenderCallbacks.splice(index, 1);
  14765. }
  14766. };
  14767. Mesh.prototype.registerAfterRender = function (func) {
  14768. this._onAfterRenderCallbacks.push(func);
  14769. };
  14770. Mesh.prototype.unregisterAfterRender = function (func) {
  14771. var index = this._onAfterRenderCallbacks.indexOf(func);
  14772. if (index > -1) {
  14773. this._onAfterRenderCallbacks.splice(index, 1);
  14774. }
  14775. };
  14776. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14777. var scene = this.getScene();
  14778. this._batchCache.mustReturn = false;
  14779. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14780. this._batchCache.visibleInstances[subMeshId] = null;
  14781. if (this._visibleInstances) {
  14782. var currentRenderId = scene.getRenderId();
  14783. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14784. var selfRenderId = this._renderId;
  14785. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14786. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14787. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14788. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14789. }
  14790. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14791. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14792. this._batchCache.mustReturn = true;
  14793. return this._batchCache;
  14794. }
  14795. if (currentRenderId !== selfRenderId) {
  14796. this._batchCache.renderSelf[subMeshId] = false;
  14797. }
  14798. }
  14799. this._renderIdForInstances[subMeshId] = currentRenderId;
  14800. }
  14801. return this._batchCache;
  14802. };
  14803. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14804. var visibleInstances = batch.visibleInstances[subMesh._id];
  14805. var matricesCount = visibleInstances.length + 1;
  14806. var bufferSize = matricesCount * 16 * 4;
  14807. while (this._instancesBufferSize < bufferSize) {
  14808. this._instancesBufferSize *= 2;
  14809. }
  14810. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14811. if (this._worldMatricesInstancesBuffer) {
  14812. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14813. }
  14814. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14815. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14816. }
  14817. var offset = 0;
  14818. var instancesCount = 0;
  14819. var world = this.getWorldMatrix();
  14820. if (batch.renderSelf[subMesh._id]) {
  14821. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14822. offset += 16;
  14823. instancesCount++;
  14824. }
  14825. if (visibleInstances) {
  14826. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14827. var instance = visibleInstances[instanceIndex];
  14828. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14829. offset += 16;
  14830. instancesCount++;
  14831. }
  14832. }
  14833. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14834. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14835. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14836. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14837. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14838. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14839. this._draw(subMesh, fillMode, instancesCount);
  14840. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14841. };
  14842. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14843. var scene = this.getScene();
  14844. var engine = scene.getEngine();
  14845. if (hardwareInstancedRendering) {
  14846. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14847. }
  14848. else {
  14849. if (batch.renderSelf[subMesh._id]) {
  14850. // Draw
  14851. if (onBeforeDraw) {
  14852. onBeforeDraw(false, this.getWorldMatrix());
  14853. }
  14854. this._draw(subMesh, fillMode);
  14855. }
  14856. if (batch.visibleInstances[subMesh._id]) {
  14857. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14858. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14859. // World
  14860. var world = instance.getWorldMatrix();
  14861. if (onBeforeDraw) {
  14862. onBeforeDraw(true, world);
  14863. }
  14864. // Draw
  14865. this._draw(subMesh, fillMode);
  14866. }
  14867. }
  14868. }
  14869. };
  14870. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14871. var scene = this.getScene();
  14872. // Managing instances
  14873. var batch = this._getInstancesRenderList(subMesh._id);
  14874. if (batch.mustReturn) {
  14875. return;
  14876. }
  14877. // Checking geometry state
  14878. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14879. return;
  14880. }
  14881. var callbackIndex;
  14882. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14883. this._onBeforeRenderCallbacks[callbackIndex](this);
  14884. }
  14885. var engine = scene.getEngine();
  14886. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14887. // Material
  14888. var effectiveMaterial = subMesh.getMaterial();
  14889. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14890. return;
  14891. }
  14892. // Outline - step 1
  14893. var savedDepthWrite = engine.getDepthWrite();
  14894. if (this.renderOutline) {
  14895. engine.setDepthWrite(false);
  14896. scene.getOutlineRenderer().render(subMesh, batch);
  14897. engine.setDepthWrite(savedDepthWrite);
  14898. }
  14899. effectiveMaterial._preBind();
  14900. var effect = effectiveMaterial.getEffect();
  14901. // Bind
  14902. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14903. this._bind(subMesh, effect, fillMode);
  14904. var world = this.getWorldMatrix();
  14905. effectiveMaterial.bind(world, this);
  14906. // Alpha mode
  14907. if (enableAlphaMode) {
  14908. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14909. }
  14910. // Draw
  14911. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14912. if (isInstance) {
  14913. effectiveMaterial.bindOnlyWorldMatrix(world);
  14914. }
  14915. });
  14916. // Unbind
  14917. effectiveMaterial.unbind();
  14918. // Outline - step 2
  14919. if (this.renderOutline && savedDepthWrite) {
  14920. engine.setDepthWrite(true);
  14921. engine.setColorWrite(false);
  14922. scene.getOutlineRenderer().render(subMesh, batch);
  14923. engine.setColorWrite(true);
  14924. }
  14925. // Overlay
  14926. if (this.renderOverlay) {
  14927. var currentMode = engine.getAlphaMode();
  14928. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14929. scene.getOutlineRenderer().render(subMesh, batch, true);
  14930. engine.setAlphaMode(currentMode);
  14931. }
  14932. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14933. this._onAfterRenderCallbacks[callbackIndex](this);
  14934. }
  14935. };
  14936. Mesh.prototype.getEmittedParticleSystems = function () {
  14937. var results = new Array();
  14938. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14939. var particleSystem = this.getScene().particleSystems[index];
  14940. if (particleSystem.emitter === this) {
  14941. results.push(particleSystem);
  14942. }
  14943. }
  14944. return results;
  14945. };
  14946. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14947. var results = new Array();
  14948. var descendants = this.getDescendants();
  14949. descendants.push(this);
  14950. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14951. var particleSystem = this.getScene().particleSystems[index];
  14952. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14953. results.push(particleSystem);
  14954. }
  14955. }
  14956. return results;
  14957. };
  14958. Mesh.prototype.getChildren = function () {
  14959. var results = [];
  14960. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14961. var mesh = this.getScene().meshes[index];
  14962. if (mesh.parent === this) {
  14963. results.push(mesh);
  14964. }
  14965. }
  14966. return results;
  14967. };
  14968. Mesh.prototype._checkDelayState = function () {
  14969. var _this = this;
  14970. var that = this;
  14971. var scene = this.getScene();
  14972. if (this._geometry) {
  14973. this._geometry.load(scene);
  14974. }
  14975. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14976. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14977. scene._addPendingData(that);
  14978. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14979. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14980. if (data instanceof ArrayBuffer) {
  14981. _this._delayLoadingFunction(data, _this);
  14982. }
  14983. else {
  14984. _this._delayLoadingFunction(JSON.parse(data), _this);
  14985. }
  14986. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14987. scene._removePendingData(_this);
  14988. }, function () { }, scene.database, getBinaryData);
  14989. }
  14990. };
  14991. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14992. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14993. return false;
  14994. }
  14995. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14996. return false;
  14997. }
  14998. this._checkDelayState();
  14999. return true;
  15000. };
  15001. Mesh.prototype.setMaterialByID = function (id) {
  15002. var materials = this.getScene().materials;
  15003. var index;
  15004. for (index = 0; index < materials.length; index++) {
  15005. if (materials[index].id === id) {
  15006. this.material = materials[index];
  15007. return;
  15008. }
  15009. }
  15010. // Multi
  15011. var multiMaterials = this.getScene().multiMaterials;
  15012. for (index = 0; index < multiMaterials.length; index++) {
  15013. if (multiMaterials[index].id === id) {
  15014. this.material = multiMaterials[index];
  15015. return;
  15016. }
  15017. }
  15018. };
  15019. Mesh.prototype.getAnimatables = function () {
  15020. var results = [];
  15021. if (this.material) {
  15022. results.push(this.material);
  15023. }
  15024. if (this.skeleton) {
  15025. results.push(this.skeleton);
  15026. }
  15027. return results;
  15028. };
  15029. // Geometry
  15030. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15031. // Position
  15032. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15033. return;
  15034. }
  15035. this._resetPointsArrayCache();
  15036. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15037. var temp = [];
  15038. var index;
  15039. for (index = 0; index < data.length; index += 3) {
  15040. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15041. }
  15042. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15043. // Normals
  15044. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15045. return;
  15046. }
  15047. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15048. temp = [];
  15049. for (index = 0; index < data.length; index += 3) {
  15050. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15051. }
  15052. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15053. // flip faces?
  15054. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15055. this.flipFaces();
  15056. }
  15057. };
  15058. // Will apply current transform to mesh and reset world matrix
  15059. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15060. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15061. this.scaling.copyFromFloats(1, 1, 1);
  15062. this.position.copyFromFloats(0, 0, 0);
  15063. this.rotation.copyFromFloats(0, 0, 0);
  15064. //only if quaternion is already set
  15065. if (this.rotationQuaternion) {
  15066. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15067. }
  15068. this._worldMatrix = BABYLON.Matrix.Identity();
  15069. };
  15070. // Cache
  15071. Mesh.prototype._resetPointsArrayCache = function () {
  15072. this._positions = null;
  15073. };
  15074. Mesh.prototype._generatePointsArray = function () {
  15075. if (this._positions)
  15076. return true;
  15077. this._positions = [];
  15078. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15079. if (!data) {
  15080. return false;
  15081. }
  15082. for (var index = 0; index < data.length; index += 3) {
  15083. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15084. }
  15085. return true;
  15086. };
  15087. // Clone
  15088. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15089. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15090. };
  15091. // Dispose
  15092. Mesh.prototype.dispose = function (doNotRecurse) {
  15093. if (this._geometry) {
  15094. this._geometry.releaseForMesh(this, true);
  15095. }
  15096. // Instances
  15097. if (this._worldMatricesInstancesBuffer) {
  15098. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15099. this._worldMatricesInstancesBuffer = null;
  15100. }
  15101. while (this.instances.length) {
  15102. this.instances[0].dispose();
  15103. }
  15104. _super.prototype.dispose.call(this, doNotRecurse);
  15105. };
  15106. // Geometric tools
  15107. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15108. var _this = this;
  15109. var scene = this.getScene();
  15110. var onload = function (img) {
  15111. // Getting height map data
  15112. var canvas = document.createElement("canvas");
  15113. var context = canvas.getContext("2d");
  15114. var heightMapWidth = img.width;
  15115. var heightMapHeight = img.height;
  15116. canvas.width = heightMapWidth;
  15117. canvas.height = heightMapHeight;
  15118. context.drawImage(img, 0, 0);
  15119. // Create VertexData from map data
  15120. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15121. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15122. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15123. //execute success callback, if set
  15124. if (onSuccess) {
  15125. onSuccess(_this);
  15126. }
  15127. };
  15128. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15129. };
  15130. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15131. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15132. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15133. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15134. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15135. return;
  15136. }
  15137. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15138. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15139. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15140. var position = BABYLON.Vector3.Zero();
  15141. var normal = BABYLON.Vector3.Zero();
  15142. var uv = BABYLON.Vector2.Zero();
  15143. for (var index = 0; index < positions.length; index += 3) {
  15144. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15145. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15146. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15147. // Compute height
  15148. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15149. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15150. var pos = (u + v * heightMapWidth) * 4;
  15151. var r = buffer[pos] / 255.0;
  15152. var g = buffer[pos + 1] / 255.0;
  15153. var b = buffer[pos + 2] / 255.0;
  15154. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15155. normal.normalize();
  15156. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15157. position = position.add(normal);
  15158. position.toArray(positions, index);
  15159. }
  15160. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15161. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15162. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15163. };
  15164. Mesh.prototype.convertToFlatShadedMesh = function () {
  15165. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15166. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15167. var kinds = this.getVerticesDataKinds();
  15168. var vbs = [];
  15169. var data = [];
  15170. var newdata = [];
  15171. var updatableNormals = false;
  15172. var kindIndex;
  15173. var kind;
  15174. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15175. kind = kinds[kindIndex];
  15176. var vertexBuffer = this.getVertexBuffer(kind);
  15177. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15178. updatableNormals = vertexBuffer.isUpdatable();
  15179. kinds.splice(kindIndex, 1);
  15180. kindIndex--;
  15181. continue;
  15182. }
  15183. vbs[kind] = vertexBuffer;
  15184. data[kind] = vbs[kind].getData();
  15185. newdata[kind] = [];
  15186. }
  15187. // Save previous submeshes
  15188. var previousSubmeshes = this.subMeshes.slice(0);
  15189. var indices = this.getIndices();
  15190. var totalIndices = this.getTotalIndices();
  15191. // Generating unique vertices per face
  15192. var index;
  15193. for (index = 0; index < totalIndices; index++) {
  15194. var vertexIndex = indices[index];
  15195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15196. kind = kinds[kindIndex];
  15197. var stride = vbs[kind].getStrideSize();
  15198. for (var offset = 0; offset < stride; offset++) {
  15199. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15200. }
  15201. }
  15202. }
  15203. // Updating faces & normal
  15204. var normals = [];
  15205. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15206. for (index = 0; index < totalIndices; index += 3) {
  15207. indices[index] = index;
  15208. indices[index + 1] = index + 1;
  15209. indices[index + 2] = index + 2;
  15210. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15211. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15212. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15213. var p1p2 = p1.subtract(p2);
  15214. var p3p2 = p3.subtract(p2);
  15215. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15216. // Store same normals for every vertex
  15217. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15218. normals.push(normal.x);
  15219. normals.push(normal.y);
  15220. normals.push(normal.z);
  15221. }
  15222. }
  15223. this.setIndices(indices);
  15224. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15225. // Updating vertex buffers
  15226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15227. kind = kinds[kindIndex];
  15228. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15229. }
  15230. // Updating submeshes
  15231. this.releaseSubMeshes();
  15232. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15233. var previousOne = previousSubmeshes[submeshIndex];
  15234. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15235. }
  15236. this.synchronizeInstances();
  15237. };
  15238. // will inverse faces orientations, and invert normals too if specified
  15239. Mesh.prototype.flipFaces = function (flipNormals) {
  15240. if (flipNormals === void 0) { flipNormals = false; }
  15241. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15242. var i;
  15243. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15244. for (i = 0; i < vertex_data.normals.length; i++) {
  15245. vertex_data.normals[i] *= -1;
  15246. }
  15247. }
  15248. var temp;
  15249. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15250. // reassign indices
  15251. temp = vertex_data.indices[i + 1];
  15252. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15253. vertex_data.indices[i + 2] = temp;
  15254. }
  15255. vertex_data.applyToMesh(this);
  15256. };
  15257. // Instances
  15258. Mesh.prototype.createInstance = function (name) {
  15259. return new BABYLON.InstancedMesh(name, this);
  15260. };
  15261. Mesh.prototype.synchronizeInstances = function () {
  15262. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15263. var instance = this.instances[instanceIndex];
  15264. instance._syncSubMeshes();
  15265. }
  15266. };
  15267. /**
  15268. * Simplify the mesh according to the given array of settings.
  15269. * Function will return immediately and will simplify async.
  15270. * @param settings a collection of simplification settings.
  15271. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15272. * @param type the type of simplification to run.
  15273. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15274. */
  15275. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15276. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15277. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15278. this.getScene().simplificationQueue.addTask({
  15279. settings: settings,
  15280. parallelProcessing: parallelProcessing,
  15281. mesh: this,
  15282. simplificationType: simplificationType,
  15283. successCallback: successCallback
  15284. });
  15285. };
  15286. /**
  15287. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15288. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15289. * This should be used together with the simplification to avoid disappearing triangles.
  15290. * @param successCallback an optional success callback to be called after the optimization finished.
  15291. */
  15292. Mesh.prototype.optimizeIndices = function (successCallback) {
  15293. var _this = this;
  15294. var indices = this.getIndices();
  15295. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15296. var vectorPositions = [];
  15297. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15298. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15299. }
  15300. var dupes = [];
  15301. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15302. var realPos = vectorPositions.length - 1 - iteration;
  15303. var testedPosition = vectorPositions[realPos];
  15304. for (var j = 0; j < realPos; ++j) {
  15305. var againstPosition = vectorPositions[j];
  15306. if (testedPosition.equals(againstPosition)) {
  15307. dupes[realPos] = j;
  15308. break;
  15309. }
  15310. }
  15311. }, function () {
  15312. for (var i = 0; i < indices.length; ++i) {
  15313. indices[i] = dupes[indices[i]] || indices[i];
  15314. }
  15315. //indices are now reordered
  15316. var originalSubMeshes = _this.subMeshes.slice(0);
  15317. _this.setIndices(indices);
  15318. _this.subMeshes = originalSubMeshes;
  15319. if (successCallback) {
  15320. successCallback(_this);
  15321. }
  15322. });
  15323. };
  15324. // Statics
  15325. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15326. var mesh = new Mesh(parsedMesh.name, scene);
  15327. mesh.id = parsedMesh.id;
  15328. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15329. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15330. if (parsedMesh.rotationQuaternion) {
  15331. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15332. }
  15333. else if (parsedMesh.rotation) {
  15334. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15335. }
  15336. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15337. if (parsedMesh.localMatrix) {
  15338. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15339. }
  15340. else if (parsedMesh.pivotMatrix) {
  15341. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15342. }
  15343. mesh.setEnabled(parsedMesh.isEnabled);
  15344. mesh.isVisible = parsedMesh.isVisible;
  15345. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15346. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15347. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15348. if (parsedMesh.applyFog !== undefined) {
  15349. mesh.applyFog = parsedMesh.applyFog;
  15350. }
  15351. if (parsedMesh.pickable !== undefined) {
  15352. mesh.isPickable = parsedMesh.pickable;
  15353. }
  15354. if (parsedMesh.alphaIndex !== undefined) {
  15355. mesh.alphaIndex = parsedMesh.alphaIndex;
  15356. }
  15357. mesh.receiveShadows = parsedMesh.receiveShadows;
  15358. mesh.billboardMode = parsedMesh.billboardMode;
  15359. if (parsedMesh.visibility !== undefined) {
  15360. mesh.visibility = parsedMesh.visibility;
  15361. }
  15362. mesh.checkCollisions = parsedMesh.checkCollisions;
  15363. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15364. // freezeWorldMatrix
  15365. if (parsedMesh.freezeWorldMatrix) {
  15366. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15367. }
  15368. // Parent
  15369. if (parsedMesh.parentId) {
  15370. mesh._waitingParentId = parsedMesh.parentId;
  15371. }
  15372. // Actions
  15373. if (parsedMesh.actions !== undefined) {
  15374. mesh._waitingActions = parsedMesh.actions;
  15375. }
  15376. // Geometry
  15377. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15378. if (parsedMesh.delayLoadingFile) {
  15379. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15380. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15381. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15382. if (parsedMesh._binaryInfo) {
  15383. mesh._binaryInfo = parsedMesh._binaryInfo;
  15384. }
  15385. mesh._delayInfo = [];
  15386. if (parsedMesh.hasUVs) {
  15387. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15388. }
  15389. if (parsedMesh.hasUVs2) {
  15390. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15391. }
  15392. if (parsedMesh.hasUVs3) {
  15393. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15394. }
  15395. if (parsedMesh.hasUVs4) {
  15396. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15397. }
  15398. if (parsedMesh.hasUVs5) {
  15399. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15400. }
  15401. if (parsedMesh.hasUVs6) {
  15402. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15403. }
  15404. if (parsedMesh.hasColors) {
  15405. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15406. }
  15407. if (parsedMesh.hasMatricesIndices) {
  15408. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15409. }
  15410. if (parsedMesh.hasMatricesWeights) {
  15411. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15412. }
  15413. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15414. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15415. mesh._checkDelayState();
  15416. }
  15417. }
  15418. else {
  15419. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15420. }
  15421. // Material
  15422. if (parsedMesh.materialId) {
  15423. mesh.setMaterialByID(parsedMesh.materialId);
  15424. }
  15425. else {
  15426. mesh.material = null;
  15427. }
  15428. // Skeleton
  15429. if (parsedMesh.skeletonId > -1) {
  15430. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15431. if (parsedMesh.numBoneInfluencers) {
  15432. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15433. }
  15434. }
  15435. // Physics
  15436. if (parsedMesh.physicsImpostor) {
  15437. if (!scene.isPhysicsEnabled()) {
  15438. scene.enablePhysics();
  15439. }
  15440. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15441. }
  15442. // Animations
  15443. if (parsedMesh.animations) {
  15444. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15445. var parsedAnimation = parsedMesh.animations[animationIndex];
  15446. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15447. }
  15448. }
  15449. if (parsedMesh.autoAnimate) {
  15450. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15451. }
  15452. // Layer Mask
  15453. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15454. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15455. }
  15456. else {
  15457. mesh.layerMask = 0x0FFFFFFF;
  15458. }
  15459. // Instances
  15460. if (parsedMesh.instances) {
  15461. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15462. var parsedInstance = parsedMesh.instances[index];
  15463. var instance = mesh.createInstance(parsedInstance.name);
  15464. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15465. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15466. if (parsedInstance.rotationQuaternion) {
  15467. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15468. }
  15469. else if (parsedInstance.rotation) {
  15470. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15471. }
  15472. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15473. instance.checkCollisions = mesh.checkCollisions;
  15474. if (parsedMesh.animations) {
  15475. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15476. parsedAnimation = parsedMesh.animations[animationIndex];
  15477. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15478. }
  15479. }
  15480. }
  15481. }
  15482. return mesh;
  15483. };
  15484. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15485. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15486. pathArray: pathArray,
  15487. closeArray: closeArray,
  15488. closePath: closePath,
  15489. offset: offset,
  15490. updatable: updatable,
  15491. sideOrientation: sideOrientation,
  15492. instance: instance
  15493. }, scene);
  15494. };
  15495. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15496. var options = {
  15497. radius: radius,
  15498. tessellation: tessellation,
  15499. sideOrientation: sideOrientation,
  15500. updatable: updatable
  15501. };
  15502. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15503. };
  15504. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15505. var options = {
  15506. size: size,
  15507. sideOrientation: sideOrientation,
  15508. updatable: updatable
  15509. };
  15510. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15511. };
  15512. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15513. var options = {
  15514. segments: segments,
  15515. diameterX: diameter,
  15516. diameterY: diameter,
  15517. diameterZ: diameter,
  15518. sideOrientation: sideOrientation,
  15519. updatable: updatable
  15520. };
  15521. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15522. };
  15523. // Cylinder and cone
  15524. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15525. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15526. if (scene !== undefined) {
  15527. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15528. updatable = scene;
  15529. }
  15530. scene = subdivisions;
  15531. subdivisions = 1;
  15532. }
  15533. var options = {
  15534. height: height,
  15535. diameterTop: diameterTop,
  15536. diameterBottom: diameterBottom,
  15537. tessellation: tessellation,
  15538. subdivisions: subdivisions,
  15539. sideOrientation: sideOrientation,
  15540. updatable: updatable
  15541. };
  15542. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15543. };
  15544. // Torus (Code from SharpDX.org)
  15545. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15546. var options = {
  15547. diameter: diameter,
  15548. thickness: thickness,
  15549. tessellation: tessellation,
  15550. sideOrientation: sideOrientation,
  15551. updatable: updatable
  15552. };
  15553. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15554. };
  15555. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15556. var options = {
  15557. radius: radius,
  15558. tube: tube,
  15559. radialSegments: radialSegments,
  15560. tubularSegments: tubularSegments,
  15561. p: p,
  15562. q: q,
  15563. sideOrientation: sideOrientation,
  15564. updatable: updatable
  15565. };
  15566. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15567. };
  15568. // Lines
  15569. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15570. var options = {
  15571. points: points,
  15572. updatable: updatable,
  15573. instance: instance
  15574. };
  15575. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15576. };
  15577. // Dashed Lines
  15578. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15579. var options = {
  15580. points: points,
  15581. dashSize: dashSize,
  15582. gapSize: gapSize,
  15583. dashNb: dashNb,
  15584. updatable: updatable
  15585. };
  15586. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15587. };
  15588. // Extrusion
  15589. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15590. var options = {
  15591. shape: shape,
  15592. path: path,
  15593. scale: scale,
  15594. rotation: rotation,
  15595. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15596. sideOrientation: sideOrientation,
  15597. instance: instance,
  15598. updatable: updatable
  15599. };
  15600. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15601. };
  15602. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15603. var options = {
  15604. shape: shape,
  15605. path: path,
  15606. scaleFunction: scaleFunction,
  15607. rotationFunction: rotationFunction,
  15608. ribbonCloseArray: ribbonCloseArray,
  15609. ribbonClosePath: ribbonClosePath,
  15610. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15611. sideOrientation: sideOrientation,
  15612. instance: instance,
  15613. updatable: updatable
  15614. };
  15615. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15616. };
  15617. // Lathe
  15618. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15619. var options = {
  15620. shape: shape,
  15621. radius: radius,
  15622. tessellation: tessellation,
  15623. sideOrientation: sideOrientation,
  15624. updatable: updatable
  15625. };
  15626. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15627. };
  15628. // Plane & ground
  15629. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15630. var options = {
  15631. size: size,
  15632. width: size,
  15633. height: size,
  15634. sideOrientation: sideOrientation,
  15635. updatable: updatable
  15636. };
  15637. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15638. };
  15639. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15640. var options = {
  15641. width: width,
  15642. height: height,
  15643. subdivisions: subdivisions,
  15644. updatable: updatable
  15645. };
  15646. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15647. };
  15648. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15649. var options = {
  15650. xmin: xmin,
  15651. zmin: zmin,
  15652. xmax: xmax,
  15653. zmax: zmax,
  15654. subdivisions: subdivisions,
  15655. precision: precision,
  15656. updatable: updatable
  15657. };
  15658. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15659. };
  15660. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15661. var options = {
  15662. width: width,
  15663. height: height,
  15664. subdivisions: subdivisions,
  15665. minHeight: minHeight,
  15666. maxHeight: maxHeight,
  15667. updatable: updatable,
  15668. onReady: onReady
  15669. };
  15670. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15671. };
  15672. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15673. var options = {
  15674. path: path,
  15675. radius: radius,
  15676. tessellation: tessellation,
  15677. radiusFunction: radiusFunction,
  15678. arc: 1,
  15679. cap: cap,
  15680. updatable: updatable,
  15681. sideOrientation: sideOrientation,
  15682. instance: instance
  15683. };
  15684. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15685. };
  15686. Mesh.CreatePolyhedron = function (name, options, scene) {
  15687. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15688. };
  15689. Mesh.CreateIcoSphere = function (name, options, scene) {
  15690. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15691. };
  15692. // Decals
  15693. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15694. var options = {
  15695. position: position,
  15696. normal: normal,
  15697. size: size,
  15698. angle: angle
  15699. };
  15700. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15701. };
  15702. // Skeletons
  15703. /**
  15704. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15705. */
  15706. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15707. var source;
  15708. if (!this._sourcePositions) {
  15709. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15710. this._sourcePositions = new Float32Array(source);
  15711. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15712. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15713. }
  15714. }
  15715. return this._sourcePositions;
  15716. };
  15717. /**
  15718. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15719. */
  15720. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15721. var source;
  15722. if (!this._sourceNormals) {
  15723. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15724. this._sourceNormals = new Float32Array(source);
  15725. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15726. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15727. }
  15728. }
  15729. return this._sourceNormals;
  15730. };
  15731. /**
  15732. * Update the vertex buffers by applying transformation from the bones
  15733. * @param {skeleton} skeleton to apply
  15734. */
  15735. Mesh.prototype.applySkeleton = function (skeleton) {
  15736. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15737. return this;
  15738. }
  15739. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15740. return this;
  15741. }
  15742. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15743. return this;
  15744. }
  15745. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15746. return this;
  15747. }
  15748. if (!this._sourcePositions) {
  15749. this.setPositionsForCPUSkinning();
  15750. }
  15751. if (!this._sourceNormals) {
  15752. this.setNormalsForCPUSkinning();
  15753. }
  15754. // positionsData checks for not being Float32Array will only pass at most once
  15755. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15756. if (!(positionsData instanceof Float32Array)) {
  15757. positionsData = new Float32Array(positionsData);
  15758. }
  15759. // normalsData checks for not being Float32Array will only pass at most once
  15760. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15761. if (!(normalsData instanceof Float32Array)) {
  15762. normalsData = new Float32Array(normalsData);
  15763. }
  15764. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15765. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15766. var needExtras = this.numBoneInfluencers > 4;
  15767. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15768. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15769. var skeletonMatrices = skeleton.getTransformMatrices();
  15770. var tempVector3 = BABYLON.Vector3.Zero();
  15771. var finalMatrix = new BABYLON.Matrix();
  15772. var tempMatrix = new BABYLON.Matrix();
  15773. var matWeightIdx = 0;
  15774. var inf;
  15775. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15776. var weight;
  15777. for (inf = 0; inf < 4; inf++) {
  15778. weight = matricesWeightsData[matWeightIdx + inf];
  15779. if (weight > 0) {
  15780. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15781. finalMatrix.addToSelf(tempMatrix);
  15782. }
  15783. else
  15784. break;
  15785. }
  15786. if (needExtras) {
  15787. for (inf = 0; inf < 4; inf++) {
  15788. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15789. if (weight > 0) {
  15790. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15791. finalMatrix.addToSelf(tempMatrix);
  15792. }
  15793. else
  15794. break;
  15795. }
  15796. }
  15797. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15798. tempVector3.toArray(positionsData, index);
  15799. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15800. tempVector3.toArray(normalsData, index);
  15801. finalMatrix.reset();
  15802. }
  15803. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15804. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15805. return this;
  15806. };
  15807. // Tools
  15808. Mesh.MinMax = function (meshes) {
  15809. var minVector = null;
  15810. var maxVector = null;
  15811. for (var i in meshes) {
  15812. var mesh = meshes[i];
  15813. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15814. if (!minVector) {
  15815. minVector = boundingBox.minimumWorld;
  15816. maxVector = boundingBox.maximumWorld;
  15817. continue;
  15818. }
  15819. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15820. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15821. }
  15822. return {
  15823. min: minVector,
  15824. max: maxVector
  15825. };
  15826. };
  15827. Mesh.Center = function (meshesOrMinMaxVector) {
  15828. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15829. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15830. };
  15831. /**
  15832. * Merge the array of meshes into a single mesh for performance reasons.
  15833. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15834. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15835. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15836. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15837. */
  15838. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15839. if (disposeSource === void 0) { disposeSource = true; }
  15840. var index;
  15841. if (!allow32BitsIndices) {
  15842. var totalVertices = 0;
  15843. // Counting vertices
  15844. for (index = 0; index < meshes.length; index++) {
  15845. if (meshes[index]) {
  15846. totalVertices += meshes[index].getTotalVertices();
  15847. if (totalVertices > 65536) {
  15848. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15849. return null;
  15850. }
  15851. }
  15852. }
  15853. }
  15854. // Merge
  15855. var vertexData;
  15856. var otherVertexData;
  15857. var source;
  15858. for (index = 0; index < meshes.length; index++) {
  15859. if (meshes[index]) {
  15860. meshes[index].computeWorldMatrix(true);
  15861. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15862. otherVertexData.transform(meshes[index].getWorldMatrix());
  15863. if (vertexData) {
  15864. vertexData.merge(otherVertexData);
  15865. }
  15866. else {
  15867. vertexData = otherVertexData;
  15868. source = meshes[index];
  15869. }
  15870. }
  15871. }
  15872. if (!meshSubclass) {
  15873. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15874. }
  15875. vertexData.applyToMesh(meshSubclass);
  15876. // Setting properties
  15877. meshSubclass.material = source.material;
  15878. meshSubclass.checkCollisions = source.checkCollisions;
  15879. // Cleaning
  15880. if (disposeSource) {
  15881. for (index = 0; index < meshes.length; index++) {
  15882. if (meshes[index]) {
  15883. meshes[index].dispose();
  15884. }
  15885. }
  15886. }
  15887. return meshSubclass;
  15888. };
  15889. // Consts
  15890. Mesh._FRONTSIDE = 0;
  15891. Mesh._BACKSIDE = 1;
  15892. Mesh._DOUBLESIDE = 2;
  15893. Mesh._DEFAULTSIDE = 0;
  15894. Mesh._NO_CAP = 0;
  15895. Mesh._CAP_START = 1;
  15896. Mesh._CAP_END = 2;
  15897. Mesh._CAP_ALL = 3;
  15898. return Mesh;
  15899. })(BABYLON.AbstractMesh);
  15900. BABYLON.Mesh = Mesh;
  15901. })(BABYLON || (BABYLON = {}));
  15902. var BABYLON;
  15903. (function (BABYLON) {
  15904. var SubMesh = (function () {
  15905. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15906. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15907. this.materialIndex = materialIndex;
  15908. this.verticesStart = verticesStart;
  15909. this.verticesCount = verticesCount;
  15910. this.indexStart = indexStart;
  15911. this.indexCount = indexCount;
  15912. this._renderId = 0;
  15913. this._mesh = mesh;
  15914. this._renderingMesh = renderingMesh || mesh;
  15915. mesh.subMeshes.push(this);
  15916. this._trianglePlanes = [];
  15917. this._id = mesh.subMeshes.length - 1;
  15918. if (createBoundingBox) {
  15919. this.refreshBoundingInfo();
  15920. mesh.computeWorldMatrix(true);
  15921. }
  15922. }
  15923. SubMesh.prototype.getBoundingInfo = function () {
  15924. return this._boundingInfo;
  15925. };
  15926. SubMesh.prototype.getMesh = function () {
  15927. return this._mesh;
  15928. };
  15929. SubMesh.prototype.getRenderingMesh = function () {
  15930. return this._renderingMesh;
  15931. };
  15932. SubMesh.prototype.getMaterial = function () {
  15933. var rootMaterial = this._renderingMesh.material;
  15934. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15935. var multiMaterial = rootMaterial;
  15936. return multiMaterial.getSubMaterial(this.materialIndex);
  15937. }
  15938. if (!rootMaterial) {
  15939. return this._mesh.getScene().defaultMaterial;
  15940. }
  15941. return rootMaterial;
  15942. };
  15943. // Methods
  15944. SubMesh.prototype.refreshBoundingInfo = function () {
  15945. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15946. if (!data) {
  15947. this._boundingInfo = this._mesh._boundingInfo;
  15948. return;
  15949. }
  15950. var indices = this._renderingMesh.getIndices();
  15951. var extend;
  15952. //is this the only submesh?
  15953. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15954. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15955. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15956. }
  15957. else {
  15958. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15959. }
  15960. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15961. };
  15962. SubMesh.prototype._checkCollision = function (collider) {
  15963. return this._boundingInfo._checkCollision(collider);
  15964. };
  15965. SubMesh.prototype.updateBoundingInfo = function (world) {
  15966. if (!this._boundingInfo) {
  15967. this.refreshBoundingInfo();
  15968. }
  15969. this._boundingInfo._update(world);
  15970. };
  15971. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15972. return this._boundingInfo.isInFrustum(frustumPlanes);
  15973. };
  15974. SubMesh.prototype.render = function (enableAlphaMode) {
  15975. this._renderingMesh.render(this, enableAlphaMode);
  15976. };
  15977. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15978. if (!this._linesIndexBuffer) {
  15979. var linesIndices = [];
  15980. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15981. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15982. }
  15983. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15984. this.linesIndexCount = linesIndices.length;
  15985. }
  15986. return this._linesIndexBuffer;
  15987. };
  15988. SubMesh.prototype.canIntersects = function (ray) {
  15989. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15990. };
  15991. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15992. var intersectInfo = null;
  15993. // Triangles test
  15994. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15995. var p0 = positions[indices[index]];
  15996. var p1 = positions[indices[index + 1]];
  15997. var p2 = positions[indices[index + 2]];
  15998. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15999. if (currentIntersectInfo) {
  16000. if (currentIntersectInfo.distance < 0) {
  16001. continue;
  16002. }
  16003. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16004. intersectInfo = currentIntersectInfo;
  16005. intersectInfo.faceId = index / 3;
  16006. if (fastCheck) {
  16007. break;
  16008. }
  16009. }
  16010. }
  16011. }
  16012. return intersectInfo;
  16013. };
  16014. // Clone
  16015. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16016. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16017. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16018. return result;
  16019. };
  16020. // Dispose
  16021. SubMesh.prototype.dispose = function () {
  16022. if (this._linesIndexBuffer) {
  16023. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16024. this._linesIndexBuffer = null;
  16025. }
  16026. // Remove from mesh
  16027. var index = this._mesh.subMeshes.indexOf(this);
  16028. this._mesh.subMeshes.splice(index, 1);
  16029. };
  16030. // Statics
  16031. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16032. var minVertexIndex = Number.MAX_VALUE;
  16033. var maxVertexIndex = -Number.MAX_VALUE;
  16034. renderingMesh = renderingMesh || mesh;
  16035. var indices = renderingMesh.getIndices();
  16036. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16037. var vertexIndex = indices[index];
  16038. if (vertexIndex < minVertexIndex)
  16039. minVertexIndex = vertexIndex;
  16040. if (vertexIndex > maxVertexIndex)
  16041. maxVertexIndex = vertexIndex;
  16042. }
  16043. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16044. };
  16045. return SubMesh;
  16046. })();
  16047. BABYLON.SubMesh = SubMesh;
  16048. })(BABYLON || (BABYLON = {}));
  16049. var BABYLON;
  16050. (function (BABYLON) {
  16051. var MeshBuilder = (function () {
  16052. function MeshBuilder() {
  16053. }
  16054. MeshBuilder.CreateBox = function (name, options, scene) {
  16055. var box = new BABYLON.Mesh(name, scene);
  16056. var vertexData = BABYLON.VertexData.CreateBox(options);
  16057. vertexData.applyToMesh(box, options.updatable);
  16058. return box;
  16059. };
  16060. MeshBuilder.CreateSphere = function (name, options, scene) {
  16061. var sphere = new BABYLON.Mesh(name, scene);
  16062. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16063. vertexData.applyToMesh(sphere, options.updatable);
  16064. return sphere;
  16065. };
  16066. MeshBuilder.CreateDisc = function (name, options, scene) {
  16067. var disc = new BABYLON.Mesh(name, scene);
  16068. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16069. vertexData.applyToMesh(disc, options.updatable);
  16070. return disc;
  16071. };
  16072. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16073. var sphere = new BABYLON.Mesh(name, scene);
  16074. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16075. vertexData.applyToMesh(sphere, options.updatable);
  16076. return sphere;
  16077. };
  16078. ;
  16079. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16080. var pathArray = options.pathArray;
  16081. var closeArray = options.closeArray;
  16082. var closePath = options.closePath;
  16083. var offset = options.offset;
  16084. var sideOrientation = options.sideOrientation;
  16085. var instance = options.instance;
  16086. var updatable = options.updatable;
  16087. if (instance) {
  16088. // positionFunction : ribbon case
  16089. // only pathArray and sideOrientation parameters are taken into account for positions update
  16090. var positionFunction = function (positions) {
  16091. var minlg = pathArray[0].length;
  16092. var i = 0;
  16093. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16094. for (var si = 1; si <= ns; si++) {
  16095. for (var p = 0; p < pathArray.length; p++) {
  16096. var path = pathArray[p];
  16097. var l = path.length;
  16098. minlg = (minlg < l) ? minlg : l;
  16099. var j = 0;
  16100. while (j < minlg) {
  16101. positions[i] = path[j].x;
  16102. positions[i + 1] = path[j].y;
  16103. positions[i + 2] = path[j].z;
  16104. j++;
  16105. i += 3;
  16106. }
  16107. if (instance._closePath) {
  16108. positions[i] = path[0].x;
  16109. positions[i + 1] = path[0].y;
  16110. positions[i + 2] = path[0].z;
  16111. i += 3;
  16112. }
  16113. }
  16114. }
  16115. };
  16116. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16117. positionFunction(positions);
  16118. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16119. if (!(instance.areNormalsFrozen)) {
  16120. var indices = instance.getIndices();
  16121. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16122. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16123. if (instance._closePath) {
  16124. var indexFirst = 0;
  16125. var indexLast = 0;
  16126. for (var p = 0; p < pathArray.length; p++) {
  16127. indexFirst = instance._idx[p] * 3;
  16128. if (p + 1 < pathArray.length) {
  16129. indexLast = (instance._idx[p + 1] - 1) * 3;
  16130. }
  16131. else {
  16132. indexLast = normals.length - 3;
  16133. }
  16134. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16135. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16136. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16137. normals[indexLast] = normals[indexFirst];
  16138. normals[indexLast + 1] = normals[indexFirst + 1];
  16139. normals[indexLast + 2] = normals[indexFirst + 2];
  16140. }
  16141. }
  16142. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16143. }
  16144. return instance;
  16145. }
  16146. else {
  16147. var ribbon = new BABYLON.Mesh(name, scene);
  16148. ribbon.sideOrientation = sideOrientation;
  16149. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16150. if (closePath) {
  16151. ribbon._idx = vertexData._idx;
  16152. }
  16153. ribbon._closePath = closePath;
  16154. ribbon._closeArray = closeArray;
  16155. vertexData.applyToMesh(ribbon, updatable);
  16156. return ribbon;
  16157. }
  16158. };
  16159. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16160. var cylinder = new BABYLON.Mesh(name, scene);
  16161. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16162. vertexData.applyToMesh(cylinder, options.updatable);
  16163. return cylinder;
  16164. };
  16165. MeshBuilder.CreateTorus = function (name, options, scene) {
  16166. var torus = new BABYLON.Mesh(name, scene);
  16167. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16168. vertexData.applyToMesh(torus, options.updatable);
  16169. return torus;
  16170. };
  16171. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16172. var torusKnot = new BABYLON.Mesh(name, scene);
  16173. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16174. vertexData.applyToMesh(torusKnot, options.updatable);
  16175. return torusKnot;
  16176. };
  16177. MeshBuilder.CreateLines = function (name, options, scene) {
  16178. var instance = options.instance;
  16179. var points = options.points;
  16180. if (instance) {
  16181. var positionFunction = function (positions) {
  16182. var i = 0;
  16183. for (var p = 0; p < points.length; p++) {
  16184. positions[i] = points[p].x;
  16185. positions[i + 1] = points[p].y;
  16186. positions[i + 2] = points[p].z;
  16187. i += 3;
  16188. }
  16189. };
  16190. instance.updateMeshPositions(positionFunction, false);
  16191. return instance;
  16192. }
  16193. // lines creation
  16194. var lines = new BABYLON.LinesMesh(name, scene);
  16195. var vertexData = BABYLON.VertexData.CreateLines(options);
  16196. vertexData.applyToMesh(lines, options.updatable);
  16197. return lines;
  16198. };
  16199. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16200. var points = options.points;
  16201. var instance = options.instance;
  16202. var gapSize = options.gapSize;
  16203. var dashNb = options.dashNb;
  16204. var dashSize = options.dashSize;
  16205. if (instance) {
  16206. var positionFunction = function (positions) {
  16207. var curvect = BABYLON.Vector3.Zero();
  16208. var nbSeg = positions.length / 6;
  16209. var lg = 0;
  16210. var nb = 0;
  16211. var shft = 0;
  16212. var dashshft = 0;
  16213. var curshft = 0;
  16214. var p = 0;
  16215. var i = 0;
  16216. var j = 0;
  16217. for (i = 0; i < points.length - 1; i++) {
  16218. points[i + 1].subtractToRef(points[i], curvect);
  16219. lg += curvect.length();
  16220. }
  16221. shft = lg / nbSeg;
  16222. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16223. for (i = 0; i < points.length - 1; i++) {
  16224. points[i + 1].subtractToRef(points[i], curvect);
  16225. nb = Math.floor(curvect.length() / shft);
  16226. curvect.normalize();
  16227. j = 0;
  16228. while (j < nb && p < positions.length) {
  16229. curshft = shft * j;
  16230. positions[p] = points[i].x + curshft * curvect.x;
  16231. positions[p + 1] = points[i].y + curshft * curvect.y;
  16232. positions[p + 2] = points[i].z + curshft * curvect.z;
  16233. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16234. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16235. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16236. p += 6;
  16237. j++;
  16238. }
  16239. }
  16240. while (p < positions.length) {
  16241. positions[p] = points[i].x;
  16242. positions[p + 1] = points[i].y;
  16243. positions[p + 2] = points[i].z;
  16244. p += 3;
  16245. }
  16246. };
  16247. instance.updateMeshPositions(positionFunction, false);
  16248. return instance;
  16249. }
  16250. // dashed lines creation
  16251. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16252. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16253. vertexData.applyToMesh(dashedLines, options.updatable);
  16254. dashedLines.dashSize = dashSize;
  16255. dashedLines.gapSize = gapSize;
  16256. return dashedLines;
  16257. };
  16258. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16259. var path = options.path;
  16260. var shape = options.shape;
  16261. var scale = options.scale || 1;
  16262. var rotation = options.rotation || 0;
  16263. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16264. var updatable = options.updatable;
  16265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16266. var instance = options.instance;
  16267. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16268. };
  16269. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16270. var path = options.path;
  16271. var shape = options.shape;
  16272. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16273. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16274. var ribbonCloseArray = options.ribbonCloseArray || false;
  16275. var ribbonClosePath = options.ribbonClosePath || false;
  16276. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16277. var updatable = options.updatable;
  16278. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16279. var instance = options.instance;
  16280. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16281. };
  16282. MeshBuilder.CreateLathe = function (name, options, scene) {
  16283. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16284. var closed = (options.closed === undefined) ? true : options.closed;
  16285. var shape = options.shape;
  16286. var radius = options.radius || 1;
  16287. var tessellation = options.tessellation || 64;
  16288. var updatable = options.updatable;
  16289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16290. var pi2 = Math.PI * 2;
  16291. var shapeLathe = new Array();
  16292. // first rotatable point
  16293. var i = 0;
  16294. while (shape[i].x === 0) {
  16295. i++;
  16296. }
  16297. var pt = shape[i];
  16298. for (i = 0; i < shape.length; i++) {
  16299. shapeLathe.push(shape[i].subtract(pt));
  16300. }
  16301. // circle path
  16302. var step = pi2 / tessellation * arc;
  16303. var rotated;
  16304. var path = new Array();
  16305. ;
  16306. for (i = 0; i <= tessellation; i++) {
  16307. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16308. path.push(rotated);
  16309. }
  16310. if (closed) {
  16311. path.push(path[0]);
  16312. }
  16313. // extrusion
  16314. var scaleFunction = function () { return 1; };
  16315. var rotateFunction = function () { return 0; };
  16316. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16317. return lathe;
  16318. };
  16319. MeshBuilder.CreatePlane = function (name, options, scene) {
  16320. var plane = new BABYLON.Mesh(name, scene);
  16321. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16322. vertexData.applyToMesh(plane, options.updatable);
  16323. if (options.sourcePlane) {
  16324. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16325. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16326. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16327. plane.rotate(vectorProduct, product);
  16328. }
  16329. return plane;
  16330. };
  16331. MeshBuilder.CreateGround = function (name, options, scene) {
  16332. var ground = new BABYLON.GroundMesh(name, scene);
  16333. ground._setReady(false);
  16334. ground._subdivisions = options.subdivisions || 1;
  16335. var vertexData = BABYLON.VertexData.CreateGround(options);
  16336. vertexData.applyToMesh(ground, options.updatable);
  16337. ground._setReady(true);
  16338. return ground;
  16339. };
  16340. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16341. var tiledGround = new BABYLON.Mesh(name, scene);
  16342. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16343. vertexData.applyToMesh(tiledGround, options.updatable);
  16344. return tiledGround;
  16345. };
  16346. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16347. var width = options.width || 10;
  16348. var height = options.height || 10;
  16349. var subdivisions = options.subdivisions || 1;
  16350. var minHeight = options.minHeight;
  16351. var maxHeight = options.maxHeight || 10;
  16352. var updatable = options.updatable;
  16353. var onReady = options.onReady;
  16354. var ground = new BABYLON.GroundMesh(name, scene);
  16355. ground._subdivisions = subdivisions;
  16356. ground._setReady(false);
  16357. var onload = function (img) {
  16358. // Getting height map data
  16359. var canvas = document.createElement("canvas");
  16360. var context = canvas.getContext("2d");
  16361. var bufferWidth = img.width;
  16362. var bufferHeight = img.height;
  16363. canvas.width = bufferWidth;
  16364. canvas.height = bufferHeight;
  16365. context.drawImage(img, 0, 0);
  16366. // Create VertexData from map data
  16367. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16368. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16369. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16370. width: width, height: height,
  16371. subdivisions: subdivisions,
  16372. minHeight: minHeight, maxHeight: maxHeight,
  16373. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16374. });
  16375. vertexData.applyToMesh(ground, updatable);
  16376. ground._setReady(true);
  16377. //execute ready callback, if set
  16378. if (onReady) {
  16379. onReady(ground);
  16380. }
  16381. };
  16382. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16383. return ground;
  16384. };
  16385. MeshBuilder.CreateTube = function (name, options, scene) {
  16386. var path = options.path;
  16387. var radius = options.radius || 1;
  16388. var tessellation = options.tessellation || 64;
  16389. var radiusFunction = options.radiusFunction;
  16390. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16391. var updatable = options.updatable;
  16392. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16393. var instance = options.instance;
  16394. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16395. // tube geometry
  16396. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16397. var tangents = path3D.getTangents();
  16398. var normals = path3D.getNormals();
  16399. var distances = path3D.getDistances();
  16400. var pi2 = Math.PI * 2;
  16401. var step = pi2 / tessellation * arc;
  16402. var returnRadius = function () { return radius; };
  16403. var radiusFunctionFinal = radiusFunction || returnRadius;
  16404. var circlePath;
  16405. var rad;
  16406. var normal;
  16407. var rotated;
  16408. var rotationMatrix = BABYLON.Matrix.Zero();
  16409. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16410. for (var i = 0; i < path.length; i++) {
  16411. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16412. circlePath = Array(); // current circle array
  16413. normal = normals[i]; // current normal
  16414. for (var t = 0; t < tessellation; t++) {
  16415. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16416. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16417. circlePath.push(rotated);
  16418. }
  16419. circlePaths[index] = circlePath;
  16420. index++;
  16421. }
  16422. // cap
  16423. var capPath = function (nbPoints, pathIndex) {
  16424. var pointCap = Array();
  16425. for (var i = 0; i < nbPoints; i++) {
  16426. pointCap.push(path[pathIndex]);
  16427. }
  16428. return pointCap;
  16429. };
  16430. switch (cap) {
  16431. case BABYLON.Mesh.NO_CAP:
  16432. break;
  16433. case BABYLON.Mesh.CAP_START:
  16434. circlePaths[0] = capPath(tessellation, 0);
  16435. circlePaths[1] = circlePaths[2].slice(0);
  16436. break;
  16437. case BABYLON.Mesh.CAP_END:
  16438. circlePaths[index] = circlePaths[index - 1].slice(0);
  16439. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16440. break;
  16441. case BABYLON.Mesh.CAP_ALL:
  16442. circlePaths[0] = capPath(tessellation, 0);
  16443. circlePaths[1] = circlePaths[2].slice(0);
  16444. circlePaths[index] = circlePaths[index - 1].slice(0);
  16445. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16446. break;
  16447. default:
  16448. break;
  16449. }
  16450. return circlePaths;
  16451. };
  16452. var path3D;
  16453. var pathArray;
  16454. if (instance) {
  16455. var arc = options.arc || instance.arc;
  16456. path3D = (instance.path3D).update(path);
  16457. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16458. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16459. instance.path3D = path3D;
  16460. instance.pathArray = pathArray;
  16461. instance.arc = arc;
  16462. return instance;
  16463. }
  16464. // tube creation
  16465. path3D = new BABYLON.Path3D(path);
  16466. var newPathArray = new Array();
  16467. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16468. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16469. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16470. tube.pathArray = pathArray;
  16471. tube.path3D = path3D;
  16472. tube.tessellation = tessellation;
  16473. tube.cap = cap;
  16474. tube.arc = options.arc;
  16475. return tube;
  16476. };
  16477. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16478. var polyhedron = new BABYLON.Mesh(name, scene);
  16479. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16480. vertexData.applyToMesh(polyhedron, options.updatable);
  16481. return polyhedron;
  16482. };
  16483. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16484. var indices = sourceMesh.getIndices();
  16485. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16486. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16487. var position = options.position || BABYLON.Vector3.Zero();
  16488. var normal = options.normal || BABYLON.Vector3.Up();
  16489. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16490. var angle = options.angle || 0;
  16491. // Getting correct rotation
  16492. if (!normal) {
  16493. var target = new BABYLON.Vector3(0, 0, 1);
  16494. var camera = sourceMesh.getScene().activeCamera;
  16495. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16496. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16497. }
  16498. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16499. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16500. var pitch = Math.atan2(normal.y, len);
  16501. // Matrix
  16502. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16503. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16504. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16505. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16506. var vertexData = new BABYLON.VertexData();
  16507. vertexData.indices = [];
  16508. vertexData.positions = [];
  16509. vertexData.normals = [];
  16510. vertexData.uvs = [];
  16511. var currentVertexDataIndex = 0;
  16512. var extractDecalVector3 = function (indexId) {
  16513. var vertexId = indices[indexId];
  16514. var result = new BABYLON.PositionNormalVertex();
  16515. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16516. // Send vector to decal local world
  16517. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16518. // Get normal
  16519. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16520. return result;
  16521. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16522. var clip = function (vertices, axis) {
  16523. if (vertices.length === 0) {
  16524. return vertices;
  16525. }
  16526. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16527. var clipVertices = function (v0, v1) {
  16528. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16529. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16530. };
  16531. var result = new Array();
  16532. for (var index = 0; index < vertices.length; index += 3) {
  16533. var v1Out;
  16534. var v2Out;
  16535. var v3Out;
  16536. var total = 0;
  16537. var nV1, nV2, nV3, nV4;
  16538. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16539. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16540. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16541. v1Out = d1 > 0;
  16542. v2Out = d2 > 0;
  16543. v3Out = d3 > 0;
  16544. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16545. switch (total) {
  16546. case 0:
  16547. result.push(vertices[index]);
  16548. result.push(vertices[index + 1]);
  16549. result.push(vertices[index + 2]);
  16550. break;
  16551. case 1:
  16552. if (v1Out) {
  16553. nV1 = vertices[index + 1];
  16554. nV2 = vertices[index + 2];
  16555. nV3 = clipVertices(vertices[index], nV1);
  16556. nV4 = clipVertices(vertices[index], nV2);
  16557. }
  16558. if (v2Out) {
  16559. nV1 = vertices[index];
  16560. nV2 = vertices[index + 2];
  16561. nV3 = clipVertices(vertices[index + 1], nV1);
  16562. nV4 = clipVertices(vertices[index + 1], nV2);
  16563. result.push(nV3);
  16564. result.push(nV2.clone());
  16565. result.push(nV1.clone());
  16566. result.push(nV2.clone());
  16567. result.push(nV3.clone());
  16568. result.push(nV4);
  16569. break;
  16570. }
  16571. if (v3Out) {
  16572. nV1 = vertices[index];
  16573. nV2 = vertices[index + 1];
  16574. nV3 = clipVertices(vertices[index + 2], nV1);
  16575. nV4 = clipVertices(vertices[index + 2], nV2);
  16576. }
  16577. result.push(nV1.clone());
  16578. result.push(nV2.clone());
  16579. result.push(nV3);
  16580. result.push(nV4);
  16581. result.push(nV3.clone());
  16582. result.push(nV2.clone());
  16583. break;
  16584. case 2:
  16585. if (!v1Out) {
  16586. nV1 = vertices[index].clone();
  16587. nV2 = clipVertices(nV1, vertices[index + 1]);
  16588. nV3 = clipVertices(nV1, vertices[index + 2]);
  16589. result.push(nV1);
  16590. result.push(nV2);
  16591. result.push(nV3);
  16592. }
  16593. if (!v2Out) {
  16594. nV1 = vertices[index + 1].clone();
  16595. nV2 = clipVertices(nV1, vertices[index + 2]);
  16596. nV3 = clipVertices(nV1, vertices[index]);
  16597. result.push(nV1);
  16598. result.push(nV2);
  16599. result.push(nV3);
  16600. }
  16601. if (!v3Out) {
  16602. nV1 = vertices[index + 2].clone();
  16603. nV2 = clipVertices(nV1, vertices[index]);
  16604. nV3 = clipVertices(nV1, vertices[index + 1]);
  16605. result.push(nV1);
  16606. result.push(nV2);
  16607. result.push(nV3);
  16608. }
  16609. break;
  16610. case 3:
  16611. break;
  16612. }
  16613. }
  16614. return result;
  16615. };
  16616. for (var index = 0; index < indices.length; index += 3) {
  16617. var faceVertices = new Array();
  16618. faceVertices.push(extractDecalVector3(index));
  16619. faceVertices.push(extractDecalVector3(index + 1));
  16620. faceVertices.push(extractDecalVector3(index + 2));
  16621. // Clip
  16622. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16623. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16624. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16625. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16626. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16627. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16628. if (faceVertices.length === 0) {
  16629. continue;
  16630. }
  16631. // Add UVs and get back to world
  16632. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16633. var vertex = faceVertices[vIndex];
  16634. //TODO check for Int32Array
  16635. vertexData.indices.push(currentVertexDataIndex);
  16636. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16637. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16638. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16639. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16640. currentVertexDataIndex++;
  16641. }
  16642. }
  16643. // Return mesh
  16644. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16645. vertexData.applyToMesh(decal);
  16646. decal.position = position.clone();
  16647. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16648. return decal;
  16649. };
  16650. // Privates
  16651. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16652. // extrusion geometry
  16653. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16654. var tangents = path3D.getTangents();
  16655. var normals = path3D.getNormals();
  16656. var binormals = path3D.getBinormals();
  16657. var distances = path3D.getDistances();
  16658. var angle = 0;
  16659. var returnScale = function () { return scale; };
  16660. var returnRotation = function () { return rotation; };
  16661. var rotate = custom ? rotateFunction : returnRotation;
  16662. var scl = custom ? scaleFunction : returnScale;
  16663. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16664. var rotationMatrix = BABYLON.Matrix.Zero();
  16665. for (var i = 0; i < curve.length; i++) {
  16666. var shapePath = new Array();
  16667. var angleStep = rotate(i, distances[i]);
  16668. var scaleRatio = scl(i, distances[i]);
  16669. for (var p = 0; p < shape.length; p++) {
  16670. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16671. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16672. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16673. shapePath.push(rotated);
  16674. }
  16675. shapePaths[index] = shapePath;
  16676. angle += angleStep;
  16677. index++;
  16678. }
  16679. // cap
  16680. var capPath = function (shapePath) {
  16681. var pointCap = Array();
  16682. var barycenter = BABYLON.Vector3.Zero();
  16683. var i;
  16684. for (i = 0; i < shapePath.length; i++) {
  16685. barycenter.addInPlace(shapePath[i]);
  16686. }
  16687. barycenter.scaleInPlace(1 / shapePath.length);
  16688. for (i = 0; i < shapePath.length; i++) {
  16689. pointCap.push(barycenter);
  16690. }
  16691. return pointCap;
  16692. };
  16693. switch (cap) {
  16694. case BABYLON.Mesh.NO_CAP:
  16695. break;
  16696. case BABYLON.Mesh.CAP_START:
  16697. shapePaths[0] = capPath(shapePaths[2]);
  16698. shapePaths[1] = shapePaths[2].slice(0);
  16699. break;
  16700. case BABYLON.Mesh.CAP_END:
  16701. shapePaths[index] = shapePaths[index - 1];
  16702. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16703. break;
  16704. case BABYLON.Mesh.CAP_ALL:
  16705. shapePaths[0] = capPath(shapePaths[2]);
  16706. shapePaths[1] = shapePaths[2].slice(0);
  16707. shapePaths[index] = shapePaths[index - 1];
  16708. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16709. break;
  16710. default:
  16711. break;
  16712. }
  16713. return shapePaths;
  16714. };
  16715. var path3D;
  16716. var pathArray;
  16717. if (instance) {
  16718. path3D = (instance.path3D).update(curve);
  16719. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16720. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16721. return instance;
  16722. }
  16723. // extruded shape creation
  16724. path3D = new BABYLON.Path3D(curve);
  16725. var newShapePaths = new Array();
  16726. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16727. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16728. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16729. extrudedGeneric.pathArray = pathArray;
  16730. extrudedGeneric.path3D = path3D;
  16731. extrudedGeneric.cap = cap;
  16732. return extrudedGeneric;
  16733. };
  16734. return MeshBuilder;
  16735. })();
  16736. BABYLON.MeshBuilder = MeshBuilder;
  16737. })(BABYLON || (BABYLON = {}));
  16738. var BABYLON;
  16739. (function (BABYLON) {
  16740. var BaseTexture = (function () {
  16741. function BaseTexture(scene) {
  16742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16743. this.hasAlpha = false;
  16744. this.getAlphaFromRGB = false;
  16745. this.level = 1;
  16746. this.isCube = false;
  16747. this.isRenderTarget = false;
  16748. this.animations = new Array();
  16749. this.coordinatesIndex = 0;
  16750. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16751. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16752. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16753. this.anisotropicFilteringLevel = 4;
  16754. this._scene = scene;
  16755. this._scene.textures.push(this);
  16756. }
  16757. BaseTexture.prototype.getScene = function () {
  16758. return this._scene;
  16759. };
  16760. BaseTexture.prototype.getTextureMatrix = function () {
  16761. return null;
  16762. };
  16763. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16764. return null;
  16765. };
  16766. BaseTexture.prototype.getInternalTexture = function () {
  16767. return this._texture;
  16768. };
  16769. BaseTexture.prototype.isReady = function () {
  16770. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16771. return true;
  16772. }
  16773. if (this._texture) {
  16774. return this._texture.isReady;
  16775. }
  16776. return false;
  16777. };
  16778. BaseTexture.prototype.getSize = function () {
  16779. if (this._texture._width) {
  16780. return { width: this._texture._width, height: this._texture._height };
  16781. }
  16782. if (this._texture._size) {
  16783. return { width: this._texture._size, height: this._texture._size };
  16784. }
  16785. return { width: 0, height: 0 };
  16786. };
  16787. BaseTexture.prototype.getBaseSize = function () {
  16788. if (!this.isReady())
  16789. return { width: 0, height: 0 };
  16790. if (this._texture._size) {
  16791. return { width: this._texture._size, height: this._texture._size };
  16792. }
  16793. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16794. };
  16795. BaseTexture.prototype.scale = function (ratio) {
  16796. };
  16797. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16798. get: function () {
  16799. return false;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16805. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16806. for (var index = 0; index < texturesCache.length; index++) {
  16807. var texturesCacheEntry = texturesCache[index];
  16808. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16809. texturesCache.splice(index, 1);
  16810. return;
  16811. }
  16812. }
  16813. };
  16814. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16815. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16816. for (var index = 0; index < texturesCache.length; index++) {
  16817. var texturesCacheEntry = texturesCache[index];
  16818. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16819. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16820. texturesCacheEntry.references++;
  16821. return texturesCacheEntry;
  16822. }
  16823. }
  16824. }
  16825. return null;
  16826. };
  16827. BaseTexture.prototype.delayLoad = function () {
  16828. };
  16829. BaseTexture.prototype.clone = function () {
  16830. return null;
  16831. };
  16832. BaseTexture.prototype.releaseInternalTexture = function () {
  16833. if (this._texture) {
  16834. this._scene.getEngine().releaseInternalTexture(this._texture);
  16835. delete this._texture;
  16836. }
  16837. };
  16838. BaseTexture.prototype.dispose = function () {
  16839. // Animations
  16840. this.getScene().stopAnimation(this);
  16841. // Remove from scene
  16842. var index = this._scene.textures.indexOf(this);
  16843. if (index >= 0) {
  16844. this._scene.textures.splice(index, 1);
  16845. }
  16846. if (this._texture === undefined) {
  16847. return;
  16848. }
  16849. // Release
  16850. this.releaseInternalTexture();
  16851. // Callback
  16852. if (this.onDispose) {
  16853. this.onDispose();
  16854. }
  16855. };
  16856. BaseTexture.prototype.serialize = function () {
  16857. var serializationObject = {};
  16858. if (!this.name) {
  16859. return null;
  16860. }
  16861. serializationObject.name = this.name;
  16862. serializationObject.hasAlpha = this.hasAlpha;
  16863. serializationObject.level = this.level;
  16864. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16865. serializationObject.coordinatesMode = this.coordinatesMode;
  16866. serializationObject.wrapU = this.wrapU;
  16867. serializationObject.wrapV = this.wrapV;
  16868. // Animations
  16869. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16870. return serializationObject;
  16871. };
  16872. return BaseTexture;
  16873. })();
  16874. BABYLON.BaseTexture = BaseTexture;
  16875. })(BABYLON || (BABYLON = {}));
  16876. var BABYLON;
  16877. (function (BABYLON) {
  16878. var Texture = (function (_super) {
  16879. __extends(Texture, _super);
  16880. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16881. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16882. if (onLoad === void 0) { onLoad = null; }
  16883. if (onError === void 0) { onError = null; }
  16884. if (buffer === void 0) { buffer = null; }
  16885. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16886. _super.call(this, scene);
  16887. this.uOffset = 0;
  16888. this.vOffset = 0;
  16889. this.uScale = 1.0;
  16890. this.vScale = 1.0;
  16891. this.uAng = 0;
  16892. this.vAng = 0;
  16893. this.wAng = 0;
  16894. this.name = url;
  16895. this.url = url;
  16896. this._noMipmap = noMipmap;
  16897. this._invertY = invertY;
  16898. this._samplingMode = samplingMode;
  16899. this._buffer = buffer;
  16900. this._deleteBuffer = deleteBuffer;
  16901. if (!url) {
  16902. return;
  16903. }
  16904. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16905. if (!this._texture) {
  16906. if (!scene.useDelayedTextureLoading) {
  16907. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16908. if (deleteBuffer) {
  16909. delete this._buffer;
  16910. }
  16911. }
  16912. else {
  16913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16914. }
  16915. }
  16916. else {
  16917. BABYLON.Tools.SetImmediate(function () {
  16918. if (onLoad) {
  16919. onLoad();
  16920. }
  16921. });
  16922. }
  16923. }
  16924. Texture.prototype.delayLoad = function () {
  16925. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16926. return;
  16927. }
  16928. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16929. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16930. if (!this._texture) {
  16931. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16932. if (this._deleteBuffer) {
  16933. delete this._buffer;
  16934. }
  16935. }
  16936. };
  16937. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16938. if (!this._texture) {
  16939. return;
  16940. }
  16941. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16942. };
  16943. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16944. x *= this.uScale;
  16945. y *= this.vScale;
  16946. x -= 0.5 * this.uScale;
  16947. y -= 0.5 * this.vScale;
  16948. z -= 0.5;
  16949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16950. t.x += 0.5 * this.uScale + this.uOffset;
  16951. t.y += 0.5 * this.vScale + this.vOffset;
  16952. t.z += 0.5;
  16953. };
  16954. Texture.prototype.getTextureMatrix = function () {
  16955. if (this.uOffset === this._cachedUOffset &&
  16956. this.vOffset === this._cachedVOffset &&
  16957. this.uScale === this._cachedUScale &&
  16958. this.vScale === this._cachedVScale &&
  16959. this.uAng === this._cachedUAng &&
  16960. this.vAng === this._cachedVAng &&
  16961. this.wAng === this._cachedWAng) {
  16962. return this._cachedTextureMatrix;
  16963. }
  16964. this._cachedUOffset = this.uOffset;
  16965. this._cachedVOffset = this.vOffset;
  16966. this._cachedUScale = this.uScale;
  16967. this._cachedVScale = this.vScale;
  16968. this._cachedUAng = this.uAng;
  16969. this._cachedVAng = this.vAng;
  16970. this._cachedWAng = this.wAng;
  16971. if (!this._cachedTextureMatrix) {
  16972. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16973. this._rowGenerationMatrix = new BABYLON.Matrix();
  16974. this._t0 = BABYLON.Vector3.Zero();
  16975. this._t1 = BABYLON.Vector3.Zero();
  16976. this._t2 = BABYLON.Vector3.Zero();
  16977. }
  16978. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16979. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16980. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16981. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16982. this._t1.subtractInPlace(this._t0);
  16983. this._t2.subtractInPlace(this._t0);
  16984. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16985. this._cachedTextureMatrix.m[0] = this._t1.x;
  16986. this._cachedTextureMatrix.m[1] = this._t1.y;
  16987. this._cachedTextureMatrix.m[2] = this._t1.z;
  16988. this._cachedTextureMatrix.m[4] = this._t2.x;
  16989. this._cachedTextureMatrix.m[5] = this._t2.y;
  16990. this._cachedTextureMatrix.m[6] = this._t2.z;
  16991. this._cachedTextureMatrix.m[8] = this._t0.x;
  16992. this._cachedTextureMatrix.m[9] = this._t0.y;
  16993. this._cachedTextureMatrix.m[10] = this._t0.z;
  16994. return this._cachedTextureMatrix;
  16995. };
  16996. Texture.prototype.getReflectionTextureMatrix = function () {
  16997. if (this.uOffset === this._cachedUOffset &&
  16998. this.vOffset === this._cachedVOffset &&
  16999. this.uScale === this._cachedUScale &&
  17000. this.vScale === this._cachedVScale &&
  17001. this.coordinatesMode === this._cachedCoordinatesMode) {
  17002. return this._cachedTextureMatrix;
  17003. }
  17004. if (!this._cachedTextureMatrix) {
  17005. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17006. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17007. }
  17008. this._cachedCoordinatesMode = this.coordinatesMode;
  17009. switch (this.coordinatesMode) {
  17010. case Texture.PLANAR_MODE:
  17011. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17012. this._cachedTextureMatrix[0] = this.uScale;
  17013. this._cachedTextureMatrix[5] = this.vScale;
  17014. this._cachedTextureMatrix[12] = this.uOffset;
  17015. this._cachedTextureMatrix[13] = this.vOffset;
  17016. break;
  17017. case Texture.PROJECTION_MODE:
  17018. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17019. this._projectionModeMatrix.m[0] = 0.5;
  17020. this._projectionModeMatrix.m[5] = -0.5;
  17021. this._projectionModeMatrix.m[10] = 0.0;
  17022. this._projectionModeMatrix.m[12] = 0.5;
  17023. this._projectionModeMatrix.m[13] = 0.5;
  17024. this._projectionModeMatrix.m[14] = 1.0;
  17025. this._projectionModeMatrix.m[15] = 1.0;
  17026. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17027. break;
  17028. default:
  17029. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17030. break;
  17031. }
  17032. return this._cachedTextureMatrix;
  17033. };
  17034. Texture.prototype.clone = function () {
  17035. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17036. // Base texture
  17037. newTexture.hasAlpha = this.hasAlpha;
  17038. newTexture.level = this.level;
  17039. newTexture.wrapU = this.wrapU;
  17040. newTexture.wrapV = this.wrapV;
  17041. newTexture.coordinatesIndex = this.coordinatesIndex;
  17042. newTexture.coordinatesMode = this.coordinatesMode;
  17043. // Texture
  17044. newTexture.uOffset = this.uOffset;
  17045. newTexture.vOffset = this.vOffset;
  17046. newTexture.uScale = this.uScale;
  17047. newTexture.vScale = this.vScale;
  17048. newTexture.uAng = this.uAng;
  17049. newTexture.vAng = this.vAng;
  17050. newTexture.wAng = this.wAng;
  17051. return newTexture;
  17052. };
  17053. Texture.prototype.serialize = function () {
  17054. if (!this.name) {
  17055. return null;
  17056. }
  17057. var serializationObject = _super.prototype.serialize.call(this);
  17058. serializationObject.uOffset = this.uOffset;
  17059. serializationObject.vOffset = this.vOffset;
  17060. serializationObject.uScale = this.uScale;
  17061. serializationObject.vScale = this.vScale;
  17062. serializationObject.uAng = this.uAng;
  17063. serializationObject.vAng = this.vAng;
  17064. serializationObject.wAng = this.wAng;
  17065. return serializationObject;
  17066. };
  17067. // Statics
  17068. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17069. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17070. if (onLoad === void 0) { onLoad = null; }
  17071. if (onError === void 0) { onError = null; }
  17072. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17073. };
  17074. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17075. if (parsedTexture.isCube) {
  17076. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17077. }
  17078. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17079. return null;
  17080. }
  17081. var texture;
  17082. if (parsedTexture.mirrorPlane) {
  17083. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17084. texture._waitingRenderList = parsedTexture.renderList;
  17085. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17086. }
  17087. else if (parsedTexture.isRenderTarget) {
  17088. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17089. texture._waitingRenderList = parsedTexture.renderList;
  17090. }
  17091. else {
  17092. if (parsedTexture.base64String) {
  17093. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17094. }
  17095. else {
  17096. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17097. }
  17098. }
  17099. texture.name = parsedTexture.name;
  17100. texture.hasAlpha = parsedTexture.hasAlpha;
  17101. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17102. texture.level = parsedTexture.level;
  17103. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17104. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17105. texture.uOffset = parsedTexture.uOffset;
  17106. texture.vOffset = parsedTexture.vOffset;
  17107. texture.uScale = parsedTexture.uScale;
  17108. texture.vScale = parsedTexture.vScale;
  17109. texture.uAng = parsedTexture.uAng;
  17110. texture.vAng = parsedTexture.vAng;
  17111. texture.wAng = parsedTexture.wAng;
  17112. texture.wrapU = parsedTexture.wrapU;
  17113. texture.wrapV = parsedTexture.wrapV;
  17114. // Animations
  17115. if (parsedTexture.animations) {
  17116. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17117. var parsedAnimation = parsedTexture.animations[animationIndex];
  17118. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17119. }
  17120. }
  17121. return texture;
  17122. };
  17123. // Constants
  17124. Texture.NEAREST_SAMPLINGMODE = 1;
  17125. Texture.BILINEAR_SAMPLINGMODE = 2;
  17126. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17127. Texture.EXPLICIT_MODE = 0;
  17128. Texture.SPHERICAL_MODE = 1;
  17129. Texture.PLANAR_MODE = 2;
  17130. Texture.CUBIC_MODE = 3;
  17131. Texture.PROJECTION_MODE = 4;
  17132. Texture.SKYBOX_MODE = 5;
  17133. Texture.INVCUBIC_MODE = 6;
  17134. Texture.EQUIRECTANGULAR_MODE = 7;
  17135. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17136. Texture.CLAMP_ADDRESSMODE = 0;
  17137. Texture.WRAP_ADDRESSMODE = 1;
  17138. Texture.MIRROR_ADDRESSMODE = 2;
  17139. return Texture;
  17140. })(BABYLON.BaseTexture);
  17141. BABYLON.Texture = Texture;
  17142. })(BABYLON || (BABYLON = {}));
  17143. var BABYLON;
  17144. (function (BABYLON) {
  17145. var CubeTexture = (function (_super) {
  17146. __extends(CubeTexture, _super);
  17147. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17148. _super.call(this, scene);
  17149. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17150. this.name = rootUrl;
  17151. this.url = rootUrl;
  17152. this._noMipmap = noMipmap;
  17153. this.hasAlpha = false;
  17154. if (!rootUrl) {
  17155. return;
  17156. }
  17157. this._texture = this._getFromCache(rootUrl, noMipmap);
  17158. if (!extensions) {
  17159. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17160. }
  17161. this._extensions = extensions;
  17162. if (!this._texture) {
  17163. if (!scene.useDelayedTextureLoading) {
  17164. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17165. }
  17166. else {
  17167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17168. }
  17169. }
  17170. this.isCube = true;
  17171. this._textureMatrix = BABYLON.Matrix.Identity();
  17172. }
  17173. CubeTexture.prototype.clone = function () {
  17174. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17175. // Base texture
  17176. newTexture.level = this.level;
  17177. newTexture.wrapU = this.wrapU;
  17178. newTexture.wrapV = this.wrapV;
  17179. newTexture.coordinatesIndex = this.coordinatesIndex;
  17180. newTexture.coordinatesMode = this.coordinatesMode;
  17181. return newTexture;
  17182. };
  17183. // Methods
  17184. CubeTexture.prototype.delayLoad = function () {
  17185. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17186. return;
  17187. }
  17188. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17189. this._texture = this._getFromCache(this.url, this._noMipmap);
  17190. if (!this._texture) {
  17191. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17192. }
  17193. };
  17194. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17195. return this._textureMatrix;
  17196. };
  17197. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17198. var texture = null;
  17199. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17200. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17201. texture.name = parsedTexture.name;
  17202. texture.hasAlpha = parsedTexture.hasAlpha;
  17203. texture.level = parsedTexture.level;
  17204. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17205. }
  17206. return texture;
  17207. };
  17208. CubeTexture.prototype.serialize = function () {
  17209. if (!this.name) {
  17210. return null;
  17211. }
  17212. var serializationObject = {};
  17213. serializationObject.name = this.name;
  17214. serializationObject.hasAlpha = this.hasAlpha;
  17215. serializationObject.isCube = true;
  17216. serializationObject.level = this.level;
  17217. serializationObject.coordinatesMode = this.coordinatesMode;
  17218. return serializationObject;
  17219. };
  17220. return CubeTexture;
  17221. })(BABYLON.BaseTexture);
  17222. BABYLON.CubeTexture = CubeTexture;
  17223. })(BABYLON || (BABYLON = {}));
  17224. var BABYLON;
  17225. (function (BABYLON) {
  17226. var RenderTargetTexture = (function (_super) {
  17227. __extends(RenderTargetTexture, _super);
  17228. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17229. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17230. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17231. if (isCube === void 0) { isCube = false; }
  17232. _super.call(this, null, scene, !generateMipMaps);
  17233. this.isCube = isCube;
  17234. this.renderList = new Array();
  17235. this.renderParticles = true;
  17236. this.renderSprites = false;
  17237. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17238. this._currentRefreshId = -1;
  17239. this._refreshRate = 1;
  17240. this.name = name;
  17241. this.isRenderTarget = true;
  17242. this._size = size;
  17243. this._generateMipMaps = generateMipMaps;
  17244. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17245. if (isCube) {
  17246. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17247. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17248. this._textureMatrix = BABYLON.Matrix.Identity();
  17249. }
  17250. else {
  17251. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17252. }
  17253. // Rendering groups
  17254. this._renderingManager = new BABYLON.RenderingManager(scene);
  17255. }
  17256. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17257. get: function () {
  17258. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17259. },
  17260. enumerable: true,
  17261. configurable: true
  17262. });
  17263. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17264. get: function () {
  17265. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17271. get: function () {
  17272. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17273. },
  17274. enumerable: true,
  17275. configurable: true
  17276. });
  17277. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17278. this._currentRefreshId = -1;
  17279. };
  17280. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17281. get: function () {
  17282. return this._refreshRate;
  17283. },
  17284. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17285. set: function (value) {
  17286. this._refreshRate = value;
  17287. this.resetRefreshCounter();
  17288. },
  17289. enumerable: true,
  17290. configurable: true
  17291. });
  17292. RenderTargetTexture.prototype._shouldRender = function () {
  17293. if (this._currentRefreshId === -1) {
  17294. this._currentRefreshId = 1;
  17295. return true;
  17296. }
  17297. if (this.refreshRate === this._currentRefreshId) {
  17298. this._currentRefreshId = 1;
  17299. return true;
  17300. }
  17301. this._currentRefreshId++;
  17302. return false;
  17303. };
  17304. RenderTargetTexture.prototype.isReady = function () {
  17305. if (!this.getScene().renderTargetsEnabled) {
  17306. return false;
  17307. }
  17308. return _super.prototype.isReady.call(this);
  17309. };
  17310. RenderTargetTexture.prototype.getRenderSize = function () {
  17311. return this._size;
  17312. };
  17313. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17314. get: function () {
  17315. return true;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. RenderTargetTexture.prototype.scale = function (ratio) {
  17321. var newSize = this._size * ratio;
  17322. this.resize(newSize, this._generateMipMaps);
  17323. };
  17324. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17325. if (this.isCube) {
  17326. return this._textureMatrix;
  17327. }
  17328. return _super.prototype.getReflectionTextureMatrix.call(this);
  17329. };
  17330. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17331. this.releaseInternalTexture();
  17332. if (this.isCube) {
  17333. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17334. }
  17335. else {
  17336. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17337. }
  17338. };
  17339. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17340. var scene = this.getScene();
  17341. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17342. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17343. }
  17344. if (this._waitingRenderList) {
  17345. this.renderList = [];
  17346. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17347. var id = this._waitingRenderList[index];
  17348. this.renderList.push(scene.getMeshByID(id));
  17349. }
  17350. delete this._waitingRenderList;
  17351. }
  17352. if (this.renderList && this.renderList.length === 0) {
  17353. return;
  17354. }
  17355. // Prepare renderingManager
  17356. this._renderingManager.reset();
  17357. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17358. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17359. var mesh = currentRenderList[meshIndex];
  17360. if (mesh) {
  17361. if (!mesh.isReady()) {
  17362. // Reset _currentRefreshId
  17363. this.resetRefreshCounter();
  17364. continue;
  17365. }
  17366. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17367. mesh._activate(scene.getRenderId());
  17368. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17369. var subMesh = mesh.subMeshes[subIndex];
  17370. scene._activeIndices += subMesh.indexCount;
  17371. this._renderingManager.dispatch(subMesh);
  17372. }
  17373. }
  17374. }
  17375. }
  17376. if (this.isCube) {
  17377. for (var face = 0; face < 6; face++) {
  17378. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17379. }
  17380. }
  17381. else {
  17382. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17383. }
  17384. if (this.onAfterUnbind) {
  17385. this.onAfterUnbind();
  17386. }
  17387. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17388. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17389. }
  17390. scene.resetCachedMaterial();
  17391. };
  17392. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17393. var scene = this.getScene();
  17394. var engine = scene.getEngine();
  17395. // Bind
  17396. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17397. if (this.isCube) {
  17398. engine.bindFramebuffer(this._texture, faceIndex);
  17399. }
  17400. else {
  17401. engine.bindFramebuffer(this._texture);
  17402. }
  17403. }
  17404. if (this.onBeforeRender) {
  17405. this.onBeforeRender(faceIndex);
  17406. }
  17407. // Clear
  17408. if (this.onClear) {
  17409. this.onClear(engine);
  17410. }
  17411. else {
  17412. engine.clear(scene.clearColor, true, true);
  17413. }
  17414. if (!this._doNotChangeAspectRatio) {
  17415. scene.updateTransformMatrix(true);
  17416. }
  17417. // Render
  17418. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17419. if (useCameraPostProcess) {
  17420. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17421. }
  17422. if (!this._doNotChangeAspectRatio) {
  17423. scene.updateTransformMatrix(true);
  17424. }
  17425. if (this.onAfterRender) {
  17426. this.onAfterRender(faceIndex);
  17427. }
  17428. // Dump ?
  17429. if (dumpForDebug) {
  17430. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17431. }
  17432. // Unbind
  17433. if (!this.isCube || faceIndex === 5) {
  17434. if (this.isCube) {
  17435. if (faceIndex === 5) {
  17436. engine.generateMipMapsForCubemap(this._texture);
  17437. }
  17438. }
  17439. engine.unBindFramebuffer(this._texture, this.isCube);
  17440. }
  17441. };
  17442. RenderTargetTexture.prototype.clone = function () {
  17443. var textureSize = this.getSize();
  17444. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17445. // Base texture
  17446. newTexture.hasAlpha = this.hasAlpha;
  17447. newTexture.level = this.level;
  17448. // RenderTarget Texture
  17449. newTexture.coordinatesMode = this.coordinatesMode;
  17450. newTexture.renderList = this.renderList.slice(0);
  17451. return newTexture;
  17452. };
  17453. RenderTargetTexture.prototype.serialize = function () {
  17454. if (!this.name) {
  17455. return null;
  17456. }
  17457. var serializationObject = _super.prototype.serialize.call(this);
  17458. serializationObject.renderTargetSize = this.getRenderSize();
  17459. serializationObject.renderList = [];
  17460. for (var index = 0; index < this.renderList.length; index++) {
  17461. serializationObject.renderList.push(this.renderList[index].id);
  17462. }
  17463. return serializationObject;
  17464. };
  17465. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17466. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17467. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17468. return RenderTargetTexture;
  17469. })(BABYLON.Texture);
  17470. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17471. })(BABYLON || (BABYLON = {}));
  17472. var BABYLON;
  17473. (function (BABYLON) {
  17474. var ProceduralTexture = (function (_super) {
  17475. __extends(ProceduralTexture, _super);
  17476. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17478. _super.call(this, null, scene, !generateMipMaps);
  17479. this.isEnabled = true;
  17480. this._currentRefreshId = -1;
  17481. this._refreshRate = 1;
  17482. this._vertexDeclaration = [2];
  17483. this._vertexStrideSize = 2 * 4;
  17484. this._uniforms = new Array();
  17485. this._samplers = new Array();
  17486. this._textures = new Array();
  17487. this._floats = new Array();
  17488. this._floatsArrays = {};
  17489. this._colors3 = new Array();
  17490. this._colors4 = new Array();
  17491. this._vectors2 = new Array();
  17492. this._vectors3 = new Array();
  17493. this._matrices = new Array();
  17494. this._fallbackTextureUsed = false;
  17495. scene._proceduralTextures.push(this);
  17496. this.name = name;
  17497. this.isRenderTarget = true;
  17498. this._size = size;
  17499. this._generateMipMaps = generateMipMaps;
  17500. this.setFragment(fragment);
  17501. this._fallbackTexture = fallbackTexture;
  17502. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17503. // VBO
  17504. var vertices = [];
  17505. vertices.push(1, 1);
  17506. vertices.push(-1, 1);
  17507. vertices.push(-1, -1);
  17508. vertices.push(1, -1);
  17509. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17510. // Indices
  17511. var indices = [];
  17512. indices.push(0);
  17513. indices.push(1);
  17514. indices.push(2);
  17515. indices.push(0);
  17516. indices.push(2);
  17517. indices.push(3);
  17518. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17519. }
  17520. ProceduralTexture.prototype.reset = function () {
  17521. if (this._effect === undefined) {
  17522. return;
  17523. }
  17524. var engine = this.getScene().getEngine();
  17525. engine._releaseEffect(this._effect);
  17526. };
  17527. ProceduralTexture.prototype.isReady = function () {
  17528. var _this = this;
  17529. var engine = this.getScene().getEngine();
  17530. var shaders;
  17531. if (!this._fragment) {
  17532. return false;
  17533. }
  17534. if (this._fallbackTextureUsed) {
  17535. return true;
  17536. }
  17537. if (this._fragment.fragmentElement !== undefined) {
  17538. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17539. }
  17540. else {
  17541. shaders = { vertex: "procedural", fragment: this._fragment };
  17542. }
  17543. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17544. _this.releaseInternalTexture();
  17545. if (_this._fallbackTexture) {
  17546. _this._texture = _this._fallbackTexture._texture;
  17547. _this._texture.references++;
  17548. }
  17549. _this._fallbackTextureUsed = true;
  17550. });
  17551. return this._effect.isReady();
  17552. };
  17553. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17554. this._currentRefreshId = -1;
  17555. };
  17556. ProceduralTexture.prototype.setFragment = function (fragment) {
  17557. this._fragment = fragment;
  17558. };
  17559. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17560. get: function () {
  17561. return this._refreshRate;
  17562. },
  17563. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17564. set: function (value) {
  17565. this._refreshRate = value;
  17566. this.resetRefreshCounter();
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. ProceduralTexture.prototype._shouldRender = function () {
  17572. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17573. return false;
  17574. }
  17575. if (this._fallbackTextureUsed) {
  17576. return false;
  17577. }
  17578. if (this._currentRefreshId === -1) {
  17579. this._currentRefreshId = 1;
  17580. return true;
  17581. }
  17582. if (this.refreshRate === this._currentRefreshId) {
  17583. this._currentRefreshId = 1;
  17584. return true;
  17585. }
  17586. this._currentRefreshId++;
  17587. return false;
  17588. };
  17589. ProceduralTexture.prototype.getRenderSize = function () {
  17590. return this._size;
  17591. };
  17592. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17593. if (this._fallbackTextureUsed) {
  17594. return;
  17595. }
  17596. this.releaseInternalTexture();
  17597. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17598. };
  17599. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17600. if (this._uniforms.indexOf(uniformName) === -1) {
  17601. this._uniforms.push(uniformName);
  17602. }
  17603. };
  17604. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17605. if (this._samplers.indexOf(name) === -1) {
  17606. this._samplers.push(name);
  17607. }
  17608. this._textures[name] = texture;
  17609. return this;
  17610. };
  17611. ProceduralTexture.prototype.setFloat = function (name, value) {
  17612. this._checkUniform(name);
  17613. this._floats[name] = value;
  17614. return this;
  17615. };
  17616. ProceduralTexture.prototype.setFloats = function (name, value) {
  17617. this._checkUniform(name);
  17618. this._floatsArrays[name] = value;
  17619. return this;
  17620. };
  17621. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17622. this._checkUniform(name);
  17623. this._colors3[name] = value;
  17624. return this;
  17625. };
  17626. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17627. this._checkUniform(name);
  17628. this._colors4[name] = value;
  17629. return this;
  17630. };
  17631. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17632. this._checkUniform(name);
  17633. this._vectors2[name] = value;
  17634. return this;
  17635. };
  17636. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17637. this._checkUniform(name);
  17638. this._vectors3[name] = value;
  17639. return this;
  17640. };
  17641. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17642. this._checkUniform(name);
  17643. this._matrices[name] = value;
  17644. return this;
  17645. };
  17646. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17647. var scene = this.getScene();
  17648. var engine = scene.getEngine();
  17649. engine.bindFramebuffer(this._texture);
  17650. // Clear
  17651. engine.clear(scene.clearColor, true, true);
  17652. // Render
  17653. engine.enableEffect(this._effect);
  17654. engine.setState(false);
  17655. // Texture
  17656. for (var name in this._textures) {
  17657. this._effect.setTexture(name, this._textures[name]);
  17658. }
  17659. // Float
  17660. for (name in this._floats) {
  17661. this._effect.setFloat(name, this._floats[name]);
  17662. }
  17663. // Floats
  17664. for (name in this._floatsArrays) {
  17665. this._effect.setArray(name, this._floatsArrays[name]);
  17666. }
  17667. // Color3
  17668. for (name in this._colors3) {
  17669. this._effect.setColor3(name, this._colors3[name]);
  17670. }
  17671. // Color4
  17672. for (name in this._colors4) {
  17673. var color = this._colors4[name];
  17674. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17675. }
  17676. // Vector2
  17677. for (name in this._vectors2) {
  17678. this._effect.setVector2(name, this._vectors2[name]);
  17679. }
  17680. // Vector3
  17681. for (name in this._vectors3) {
  17682. this._effect.setVector3(name, this._vectors3[name]);
  17683. }
  17684. // Matrix
  17685. for (name in this._matrices) {
  17686. this._effect.setMatrix(name, this._matrices[name]);
  17687. }
  17688. // VBOs
  17689. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17690. // Draw order
  17691. engine.draw(true, 0, 6);
  17692. // Unbind
  17693. engine.unBindFramebuffer(this._texture);
  17694. };
  17695. ProceduralTexture.prototype.clone = function () {
  17696. var textureSize = this.getSize();
  17697. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17698. // Base texture
  17699. newTexture.hasAlpha = this.hasAlpha;
  17700. newTexture.level = this.level;
  17701. // RenderTarget Texture
  17702. newTexture.coordinatesMode = this.coordinatesMode;
  17703. return newTexture;
  17704. };
  17705. ProceduralTexture.prototype.dispose = function () {
  17706. var index = this.getScene()._proceduralTextures.indexOf(this);
  17707. if (index >= 0) {
  17708. this.getScene()._proceduralTextures.splice(index, 1);
  17709. }
  17710. _super.prototype.dispose.call(this);
  17711. };
  17712. return ProceduralTexture;
  17713. })(BABYLON.Texture);
  17714. BABYLON.ProceduralTexture = ProceduralTexture;
  17715. })(BABYLON || (BABYLON = {}));
  17716. var BABYLON;
  17717. (function (BABYLON) {
  17718. var MirrorTexture = (function (_super) {
  17719. __extends(MirrorTexture, _super);
  17720. function MirrorTexture(name, size, scene, generateMipMaps) {
  17721. var _this = this;
  17722. _super.call(this, name, size, scene, generateMipMaps, true);
  17723. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17724. this._transformMatrix = BABYLON.Matrix.Zero();
  17725. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17726. this.onBeforeRender = function () {
  17727. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17728. _this._savedViewMatrix = scene.getViewMatrix();
  17729. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17730. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17731. scene.clipPlane = _this.mirrorPlane;
  17732. scene.getEngine().cullBackFaces = false;
  17733. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17734. };
  17735. this.onAfterRender = function () {
  17736. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17737. scene.getEngine().cullBackFaces = true;
  17738. scene._mirroredCameraPosition = null;
  17739. delete scene.clipPlane;
  17740. };
  17741. }
  17742. MirrorTexture.prototype.clone = function () {
  17743. var textureSize = this.getSize();
  17744. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17745. // Base texture
  17746. newTexture.hasAlpha = this.hasAlpha;
  17747. newTexture.level = this.level;
  17748. // Mirror Texture
  17749. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17750. newTexture.renderList = this.renderList.slice(0);
  17751. return newTexture;
  17752. };
  17753. MirrorTexture.prototype.serialize = function () {
  17754. if (!this.name) {
  17755. return null;
  17756. }
  17757. var serializationObject = _super.prototype.serialize.call(this);
  17758. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17759. return serializationObject;
  17760. };
  17761. return MirrorTexture;
  17762. })(BABYLON.RenderTargetTexture);
  17763. BABYLON.MirrorTexture = MirrorTexture;
  17764. })(BABYLON || (BABYLON = {}));
  17765. var BABYLON;
  17766. (function (BABYLON) {
  17767. var DynamicTexture = (function (_super) {
  17768. __extends(DynamicTexture, _super);
  17769. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17771. _super.call(this, null, scene, !generateMipMaps);
  17772. this.name = name;
  17773. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17774. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17775. this._generateMipMaps = generateMipMaps;
  17776. if (options.getContext) {
  17777. this._canvas = options;
  17778. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17779. }
  17780. else {
  17781. this._canvas = document.createElement("canvas");
  17782. if (options.width) {
  17783. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17784. }
  17785. else {
  17786. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17787. }
  17788. }
  17789. var textureSize = this.getSize();
  17790. this._canvas.width = textureSize.width;
  17791. this._canvas.height = textureSize.height;
  17792. this._context = this._canvas.getContext("2d");
  17793. }
  17794. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17795. get: function () {
  17796. return true;
  17797. },
  17798. enumerable: true,
  17799. configurable: true
  17800. });
  17801. DynamicTexture.prototype.scale = function (ratio) {
  17802. var textureSize = this.getSize();
  17803. textureSize.width *= ratio;
  17804. textureSize.height *= ratio;
  17805. this._canvas.width = textureSize.width;
  17806. this._canvas.height = textureSize.height;
  17807. this.releaseInternalTexture();
  17808. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17809. };
  17810. DynamicTexture.prototype.getContext = function () {
  17811. return this._context;
  17812. };
  17813. DynamicTexture.prototype.clear = function () {
  17814. var size = this.getSize();
  17815. this._context.fillRect(0, 0, size.width, size.height);
  17816. };
  17817. DynamicTexture.prototype.update = function (invertY) {
  17818. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17819. };
  17820. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17821. if (update === void 0) { update = true; }
  17822. var size = this.getSize();
  17823. if (clearColor) {
  17824. this._context.fillStyle = clearColor;
  17825. this._context.fillRect(0, 0, size.width, size.height);
  17826. }
  17827. this._context.font = font;
  17828. if (x === null) {
  17829. var textSize = this._context.measureText(text);
  17830. x = (size.width - textSize.width) / 2;
  17831. }
  17832. this._context.fillStyle = color;
  17833. this._context.fillText(text, x, y);
  17834. if (update) {
  17835. this.update(invertY);
  17836. }
  17837. };
  17838. DynamicTexture.prototype.clone = function () {
  17839. var textureSize = this.getSize();
  17840. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17841. // Base texture
  17842. newTexture.hasAlpha = this.hasAlpha;
  17843. newTexture.level = this.level;
  17844. // Dynamic Texture
  17845. newTexture.wrapU = this.wrapU;
  17846. newTexture.wrapV = this.wrapV;
  17847. return newTexture;
  17848. };
  17849. return DynamicTexture;
  17850. })(BABYLON.Texture);
  17851. BABYLON.DynamicTexture = DynamicTexture;
  17852. })(BABYLON || (BABYLON = {}));
  17853. var BABYLON;
  17854. (function (BABYLON) {
  17855. var VideoTexture = (function (_super) {
  17856. __extends(VideoTexture, _super);
  17857. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17858. var _this = this;
  17859. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17860. if (invertY === void 0) { invertY = false; }
  17861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17862. _super.call(this, null, scene, !generateMipMaps, invertY);
  17863. this._autoLaunch = true;
  17864. this.name = name;
  17865. this.video = document.createElement("video");
  17866. this.video.autoplay = false;
  17867. this.video.loop = true;
  17868. this.video.addEventListener("canplaythrough", function () {
  17869. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17870. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17871. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17872. }
  17873. else {
  17874. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17875. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17876. generateMipMaps = false;
  17877. }
  17878. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17879. _this._texture.isReady = true;
  17880. });
  17881. urls.forEach(function (url) {
  17882. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17883. var source = document.createElement("source");
  17884. source.src = url;
  17885. _this.video.appendChild(source);
  17886. });
  17887. this._lastUpdate = BABYLON.Tools.Now;
  17888. }
  17889. VideoTexture.prototype.update = function () {
  17890. if (this._autoLaunch) {
  17891. this._autoLaunch = false;
  17892. this.video.play();
  17893. }
  17894. var now = BABYLON.Tools.Now;
  17895. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17896. return false;
  17897. }
  17898. this._lastUpdate = now;
  17899. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17900. return true;
  17901. };
  17902. return VideoTexture;
  17903. })(BABYLON.Texture);
  17904. BABYLON.VideoTexture = VideoTexture;
  17905. })(BABYLON || (BABYLON = {}));
  17906. var BABYLON;
  17907. (function (BABYLON) {
  17908. var CustomProceduralTexture = (function (_super) {
  17909. __extends(CustomProceduralTexture, _super);
  17910. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17911. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17912. this._animate = true;
  17913. this._time = 0;
  17914. this._texturePath = texturePath;
  17915. //Try to load json
  17916. this.loadJson(texturePath);
  17917. this.refreshRate = 1;
  17918. }
  17919. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17920. var _this = this;
  17921. var that = this;
  17922. function noConfigFile() {
  17923. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17924. try {
  17925. that.setFragment(that._texturePath);
  17926. }
  17927. catch (ex) {
  17928. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17929. }
  17930. }
  17931. var configFileUrl = jsonUrl + "/config.json";
  17932. var xhr = new XMLHttpRequest();
  17933. xhr.open("GET", configFileUrl, true);
  17934. xhr.addEventListener("load", function () {
  17935. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17936. try {
  17937. _this._config = JSON.parse(xhr.response);
  17938. _this.updateShaderUniforms();
  17939. _this.updateTextures();
  17940. _this.setFragment(_this._texturePath + "/custom");
  17941. _this._animate = _this._config.animate;
  17942. _this.refreshRate = _this._config.refreshrate;
  17943. }
  17944. catch (ex) {
  17945. noConfigFile();
  17946. }
  17947. }
  17948. else {
  17949. noConfigFile();
  17950. }
  17951. }, false);
  17952. xhr.addEventListener("error", function () {
  17953. noConfigFile();
  17954. }, false);
  17955. try {
  17956. xhr.send();
  17957. }
  17958. catch (ex) {
  17959. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17960. }
  17961. };
  17962. CustomProceduralTexture.prototype.isReady = function () {
  17963. if (!_super.prototype.isReady.call(this)) {
  17964. return false;
  17965. }
  17966. for (var name in this._textures) {
  17967. var texture = this._textures[name];
  17968. if (!texture.isReady()) {
  17969. return false;
  17970. }
  17971. }
  17972. return true;
  17973. };
  17974. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17975. if (this._animate) {
  17976. this._time += this.getScene().getAnimationRatio() * 0.03;
  17977. this.updateShaderUniforms();
  17978. }
  17979. _super.prototype.render.call(this, useCameraPostProcess);
  17980. };
  17981. CustomProceduralTexture.prototype.updateTextures = function () {
  17982. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17983. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17984. }
  17985. };
  17986. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17987. if (this._config) {
  17988. for (var j = 0; j < this._config.uniforms.length; j++) {
  17989. var uniform = this._config.uniforms[j];
  17990. switch (uniform.type) {
  17991. case "float":
  17992. this.setFloat(uniform.name, uniform.value);
  17993. break;
  17994. case "color3":
  17995. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17996. break;
  17997. case "color4":
  17998. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17999. break;
  18000. case "vector2":
  18001. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18002. break;
  18003. case "vector3":
  18004. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18005. break;
  18006. }
  18007. }
  18008. }
  18009. this.setFloat("time", this._time);
  18010. };
  18011. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18012. get: function () {
  18013. return this._animate;
  18014. },
  18015. set: function (value) {
  18016. this._animate = value;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. return CustomProceduralTexture;
  18022. })(BABYLON.ProceduralTexture);
  18023. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18024. })(BABYLON || (BABYLON = {}));
  18025. var BABYLON;
  18026. (function (BABYLON) {
  18027. var EffectFallbacks = (function () {
  18028. function EffectFallbacks() {
  18029. this._defines = {};
  18030. this._currentRank = 32;
  18031. this._maxRank = -1;
  18032. }
  18033. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18034. if (!this._defines[rank]) {
  18035. if (rank < this._currentRank) {
  18036. this._currentRank = rank;
  18037. }
  18038. if (rank > this._maxRank) {
  18039. this._maxRank = rank;
  18040. }
  18041. this._defines[rank] = new Array();
  18042. }
  18043. this._defines[rank].push(define);
  18044. };
  18045. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18046. this._meshRank = rank;
  18047. this._mesh = mesh;
  18048. if (rank > this._maxRank) {
  18049. this._maxRank = rank;
  18050. }
  18051. };
  18052. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18053. get: function () {
  18054. return this._currentRank <= this._maxRank;
  18055. },
  18056. enumerable: true,
  18057. configurable: true
  18058. });
  18059. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18060. var currentFallbacks = this._defines[this._currentRank];
  18061. for (var index = 0; index < currentFallbacks.length; index++) {
  18062. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18063. }
  18064. if (this._mesh && this._currentRank === this._meshRank) {
  18065. this._mesh.computeBonesUsingShaders = false;
  18066. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18067. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18068. }
  18069. this._currentRank++;
  18070. return currentDefines;
  18071. };
  18072. return EffectFallbacks;
  18073. })();
  18074. BABYLON.EffectFallbacks = EffectFallbacks;
  18075. var Effect = (function () {
  18076. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18077. var _this = this;
  18078. this._isReady = false;
  18079. this._compilationError = "";
  18080. this._valueCache = [];
  18081. this._engine = engine;
  18082. this.name = baseName;
  18083. this.defines = defines;
  18084. this._uniformsNames = uniformsNames.concat(samplers);
  18085. this._samplers = samplers;
  18086. this._attributesNames = attributesNames;
  18087. this.onError = onError;
  18088. this.onCompiled = onCompiled;
  18089. var vertexSource;
  18090. var fragmentSource;
  18091. if (baseName.vertexElement) {
  18092. vertexSource = document.getElementById(baseName.vertexElement);
  18093. if (!vertexSource) {
  18094. vertexSource = baseName.vertexElement;
  18095. }
  18096. }
  18097. else {
  18098. vertexSource = baseName.vertex || baseName;
  18099. }
  18100. if (baseName.fragmentElement) {
  18101. fragmentSource = document.getElementById(baseName.fragmentElement);
  18102. if (!fragmentSource) {
  18103. fragmentSource = baseName.fragmentElement;
  18104. }
  18105. }
  18106. else {
  18107. fragmentSource = baseName.fragment || baseName;
  18108. }
  18109. this._loadVertexShader(vertexSource, function (vertexCode) {
  18110. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18111. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18112. });
  18113. });
  18114. }
  18115. // Properties
  18116. Effect.prototype.isReady = function () {
  18117. return this._isReady;
  18118. };
  18119. Effect.prototype.getProgram = function () {
  18120. return this._program;
  18121. };
  18122. Effect.prototype.getAttributesNames = function () {
  18123. return this._attributesNames;
  18124. };
  18125. Effect.prototype.getAttributeLocation = function (index) {
  18126. return this._attributes[index];
  18127. };
  18128. Effect.prototype.getAttributeLocationByName = function (name) {
  18129. var index = this._attributesNames.indexOf(name);
  18130. return this._attributes[index];
  18131. };
  18132. Effect.prototype.getAttributesCount = function () {
  18133. return this._attributes.length;
  18134. };
  18135. Effect.prototype.getUniformIndex = function (uniformName) {
  18136. return this._uniformsNames.indexOf(uniformName);
  18137. };
  18138. Effect.prototype.getUniform = function (uniformName) {
  18139. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18140. };
  18141. Effect.prototype.getSamplers = function () {
  18142. return this._samplers;
  18143. };
  18144. Effect.prototype.getCompilationError = function () {
  18145. return this._compilationError;
  18146. };
  18147. // Methods
  18148. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18149. // DOM element ?
  18150. if (vertex instanceof HTMLElement) {
  18151. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18152. callback(vertexCode);
  18153. return;
  18154. }
  18155. // Is in local store ?
  18156. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18157. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18158. return;
  18159. }
  18160. var vertexShaderUrl;
  18161. if (vertex[0] === "." || vertex[0] === "/") {
  18162. vertexShaderUrl = vertex;
  18163. }
  18164. else {
  18165. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18166. }
  18167. // Vertex shader
  18168. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18169. };
  18170. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18171. // DOM element ?
  18172. if (fragment instanceof HTMLElement) {
  18173. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18174. callback(fragmentCode);
  18175. return;
  18176. }
  18177. // Is in local store ?
  18178. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18179. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18180. return;
  18181. }
  18182. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18183. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18184. return;
  18185. }
  18186. var fragmentShaderUrl;
  18187. if (fragment[0] === "." || fragment[0] === "/") {
  18188. fragmentShaderUrl = fragment;
  18189. }
  18190. else {
  18191. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18192. }
  18193. // Fragment shader
  18194. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18195. };
  18196. Effect.prototype._dumpShadersName = function () {
  18197. if (this.name.vertexElement) {
  18198. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18199. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18200. }
  18201. else if (this.name.vertex) {
  18202. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18203. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18204. }
  18205. else {
  18206. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18207. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18208. }
  18209. };
  18210. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18211. try {
  18212. var engine = this._engine;
  18213. if (!engine.getCaps().highPrecisionShaderSupported) {
  18214. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18215. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18216. }
  18217. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18218. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18219. this._attributes = engine.getAttributes(this._program, attributesNames);
  18220. for (var index = 0; index < this._samplers.length; index++) {
  18221. var sampler = this.getUniform(this._samplers[index]);
  18222. if (sampler == null) {
  18223. this._samplers.splice(index, 1);
  18224. index--;
  18225. }
  18226. }
  18227. engine.bindSamplers(this);
  18228. this._isReady = true;
  18229. if (this.onCompiled) {
  18230. this.onCompiled(this);
  18231. }
  18232. }
  18233. catch (e) {
  18234. // Is it a problem with precision?
  18235. if (e.message.indexOf("highp") !== -1) {
  18236. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18237. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18238. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18239. return;
  18240. }
  18241. // Let's go through fallbacks then
  18242. if (fallbacks && fallbacks.isMoreFallbacks) {
  18243. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18244. this._dumpShadersName();
  18245. defines = fallbacks.reduce(defines);
  18246. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18247. }
  18248. else {
  18249. BABYLON.Tools.Error("Unable to compile effect: ");
  18250. this._dumpShadersName();
  18251. BABYLON.Tools.Error("Defines: " + defines);
  18252. BABYLON.Tools.Error("Error: " + e.message);
  18253. this._compilationError = e.message;
  18254. if (this.onError) {
  18255. this.onError(this, this._compilationError);
  18256. }
  18257. }
  18258. }
  18259. };
  18260. Object.defineProperty(Effect.prototype, "isSupported", {
  18261. get: function () {
  18262. return this._compilationError === "";
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. Effect.prototype._bindTexture = function (channel, texture) {
  18268. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18269. };
  18270. Effect.prototype.setTexture = function (channel, texture) {
  18271. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18272. };
  18273. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18274. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18275. };
  18276. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18277. if (!this._valueCache[uniformName]) {
  18278. this._valueCache[uniformName] = new BABYLON.Matrix();
  18279. }
  18280. for (var index = 0; index < 16; index++) {
  18281. this._valueCache[uniformName].m[index] = matrix.m[index];
  18282. }
  18283. };
  18284. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18285. if (!this._valueCache[uniformName]) {
  18286. this._valueCache[uniformName] = [x, y];
  18287. return;
  18288. }
  18289. this._valueCache[uniformName][0] = x;
  18290. this._valueCache[uniformName][1] = y;
  18291. };
  18292. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18293. if (!this._valueCache[uniformName]) {
  18294. this._valueCache[uniformName] = [x, y, z];
  18295. return;
  18296. }
  18297. this._valueCache[uniformName][0] = x;
  18298. this._valueCache[uniformName][1] = y;
  18299. this._valueCache[uniformName][2] = z;
  18300. };
  18301. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18302. if (!this._valueCache[uniformName]) {
  18303. this._valueCache[uniformName] = [x, y, z, w];
  18304. return;
  18305. }
  18306. this._valueCache[uniformName][0] = x;
  18307. this._valueCache[uniformName][1] = y;
  18308. this._valueCache[uniformName][2] = z;
  18309. this._valueCache[uniformName][3] = w;
  18310. };
  18311. Effect.prototype.setArray = function (uniformName, array) {
  18312. this._engine.setArray(this.getUniform(uniformName), array);
  18313. return this;
  18314. };
  18315. Effect.prototype.setArray2 = function (uniformName, array) {
  18316. this._engine.setArray2(this.getUniform(uniformName), array);
  18317. return this;
  18318. };
  18319. Effect.prototype.setArray3 = function (uniformName, array) {
  18320. this._engine.setArray3(this.getUniform(uniformName), array);
  18321. return this;
  18322. };
  18323. Effect.prototype.setArray4 = function (uniformName, array) {
  18324. this._engine.setArray4(this.getUniform(uniformName), array);
  18325. return this;
  18326. };
  18327. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18328. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18329. return this;
  18330. };
  18331. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18332. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18333. return this;
  18334. this._cacheMatrix(uniformName, matrix);
  18335. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18336. return this;
  18337. };
  18338. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18339. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18340. return this;
  18341. };
  18342. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18343. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18344. return this;
  18345. };
  18346. Effect.prototype.setFloat = function (uniformName, value) {
  18347. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18348. return this;
  18349. this._valueCache[uniformName] = value;
  18350. this._engine.setFloat(this.getUniform(uniformName), value);
  18351. return this;
  18352. };
  18353. Effect.prototype.setBool = function (uniformName, bool) {
  18354. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18355. return this;
  18356. this._valueCache[uniformName] = bool;
  18357. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18358. return this;
  18359. };
  18360. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18361. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18362. return this;
  18363. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18364. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18365. return this;
  18366. };
  18367. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18368. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18369. return this;
  18370. this._cacheFloat2(uniformName, x, y);
  18371. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18372. return this;
  18373. };
  18374. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18375. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18376. return this;
  18377. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18378. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18379. return this;
  18380. };
  18381. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18382. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18383. return this;
  18384. this._cacheFloat3(uniformName, x, y, z);
  18385. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18386. return this;
  18387. };
  18388. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18389. 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)
  18390. return this;
  18391. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18392. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18393. return this;
  18394. };
  18395. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18396. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18397. return this;
  18398. this._cacheFloat4(uniformName, x, y, z, w);
  18399. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18400. return this;
  18401. };
  18402. Effect.prototype.setColor3 = function (uniformName, color3) {
  18403. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18404. return this;
  18405. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18406. this._engine.setColor3(this.getUniform(uniformName), color3);
  18407. return this;
  18408. };
  18409. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18410. 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)
  18411. return this;
  18412. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18413. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18414. return this;
  18415. };
  18416. // Statics
  18417. Effect.ShadersStore = {};
  18418. return Effect;
  18419. })();
  18420. BABYLON.Effect = Effect;
  18421. })(BABYLON || (BABYLON = {}));
  18422. var BABYLON;
  18423. (function (BABYLON) {
  18424. var MaterialDefines = (function () {
  18425. function MaterialDefines() {
  18426. }
  18427. MaterialDefines.prototype.isEqual = function (other) {
  18428. for (var index = 0; index < this._keys.length; index++) {
  18429. var prop = this._keys[index];
  18430. if (this[prop] !== other[prop]) {
  18431. return false;
  18432. }
  18433. }
  18434. return true;
  18435. };
  18436. MaterialDefines.prototype.cloneTo = function (other) {
  18437. for (var index = 0; index < this._keys.length; index++) {
  18438. var prop = this._keys[index];
  18439. other[prop] = this[prop];
  18440. }
  18441. };
  18442. MaterialDefines.prototype.reset = function () {
  18443. for (var index = 0; index < this._keys.length; index++) {
  18444. var prop = this._keys[index];
  18445. if (typeof (this[prop]) === "number") {
  18446. this[prop] = 0;
  18447. }
  18448. else {
  18449. this[prop] = false;
  18450. }
  18451. }
  18452. };
  18453. MaterialDefines.prototype.toString = function () {
  18454. var result = "";
  18455. for (var index = 0; index < this._keys.length; index++) {
  18456. var prop = this._keys[index];
  18457. if (typeof (this[prop]) === "number") {
  18458. result += "#define " + prop + " " + this[prop] + "\n";
  18459. }
  18460. else if (this[prop]) {
  18461. result += "#define " + prop + "\n";
  18462. }
  18463. }
  18464. return result;
  18465. };
  18466. return MaterialDefines;
  18467. })();
  18468. BABYLON.MaterialDefines = MaterialDefines;
  18469. var Material = (function () {
  18470. function Material(name, scene, doNotAdd) {
  18471. this.name = name;
  18472. this.checkReadyOnEveryCall = false;
  18473. this.checkReadyOnlyOnce = false;
  18474. this.state = "";
  18475. this.alpha = 1.0;
  18476. this.backFaceCulling = true;
  18477. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18478. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18479. this.disableDepthWrite = false;
  18480. this.fogEnabled = true;
  18481. this._wasPreviouslyReady = false;
  18482. this._fillMode = Material.TriangleFillMode;
  18483. this.pointSize = 1.0;
  18484. this.zOffset = 0;
  18485. this.id = name;
  18486. this._scene = scene;
  18487. if (!doNotAdd) {
  18488. scene.materials.push(this);
  18489. }
  18490. }
  18491. Object.defineProperty(Material, "TriangleFillMode", {
  18492. get: function () {
  18493. return Material._TriangleFillMode;
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Material, "WireFrameFillMode", {
  18499. get: function () {
  18500. return Material._WireFrameFillMode;
  18501. },
  18502. enumerable: true,
  18503. configurable: true
  18504. });
  18505. Object.defineProperty(Material, "PointFillMode", {
  18506. get: function () {
  18507. return Material._PointFillMode;
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18513. get: function () {
  18514. return Material._ClockWiseSideOrientation;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18520. get: function () {
  18521. return Material._CounterClockWiseSideOrientation;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Object.defineProperty(Material.prototype, "wireframe", {
  18527. get: function () {
  18528. return this._fillMode === Material.WireFrameFillMode;
  18529. },
  18530. set: function (value) {
  18531. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Material.prototype, "pointsCloud", {
  18537. get: function () {
  18538. return this._fillMode === Material.PointFillMode;
  18539. },
  18540. set: function (value) {
  18541. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Object.defineProperty(Material.prototype, "fillMode", {
  18547. get: function () {
  18548. return this._fillMode;
  18549. },
  18550. set: function (value) {
  18551. this._fillMode = value;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Material.prototype.isReady = function (mesh, useInstances) {
  18557. return true;
  18558. };
  18559. Material.prototype.getEffect = function () {
  18560. return this._effect;
  18561. };
  18562. Material.prototype.getScene = function () {
  18563. return this._scene;
  18564. };
  18565. Material.prototype.needAlphaBlending = function () {
  18566. return (this.alpha < 1.0);
  18567. };
  18568. Material.prototype.needAlphaTesting = function () {
  18569. return false;
  18570. };
  18571. Material.prototype.getAlphaTestTexture = function () {
  18572. return null;
  18573. };
  18574. Material.prototype.trackCreation = function (onCompiled, onError) {
  18575. };
  18576. Material.prototype.markDirty = function () {
  18577. this._wasPreviouslyReady = false;
  18578. };
  18579. Material.prototype._preBind = function () {
  18580. var engine = this._scene.getEngine();
  18581. engine.enableEffect(this._effect);
  18582. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18583. };
  18584. Material.prototype.bind = function (world, mesh) {
  18585. this._scene._cachedMaterial = this;
  18586. if (this.onBind) {
  18587. this.onBind(this, mesh);
  18588. }
  18589. if (this.disableDepthWrite) {
  18590. var engine = this._scene.getEngine();
  18591. this._cachedDepthWriteState = engine.getDepthWrite();
  18592. engine.setDepthWrite(false);
  18593. }
  18594. };
  18595. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18596. };
  18597. Material.prototype.unbind = function () {
  18598. if (this.disableDepthWrite) {
  18599. var engine = this._scene.getEngine();
  18600. engine.setDepthWrite(this._cachedDepthWriteState);
  18601. }
  18602. };
  18603. Material.prototype.clone = function (name) {
  18604. return null;
  18605. };
  18606. Material.prototype.getBindedMeshes = function () {
  18607. var result = new Array();
  18608. for (var index = 0; index < this._scene.meshes.length; index++) {
  18609. var mesh = this._scene.meshes[index];
  18610. if (mesh.material === this) {
  18611. result.push(mesh);
  18612. }
  18613. }
  18614. return result;
  18615. };
  18616. Material.prototype.dispose = function (forceDisposeEffect) {
  18617. // Animations
  18618. this.getScene().stopAnimation(this);
  18619. // Remove from scene
  18620. var index = this._scene.materials.indexOf(this);
  18621. if (index >= 0) {
  18622. this._scene.materials.splice(index, 1);
  18623. }
  18624. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18625. if (forceDisposeEffect && this._effect) {
  18626. this._scene.getEngine()._releaseEffect(this._effect);
  18627. this._effect = null;
  18628. }
  18629. // Remove from meshes
  18630. for (index = 0; index < this._scene.meshes.length; index++) {
  18631. var mesh = this._scene.meshes[index];
  18632. if (mesh.material === this) {
  18633. mesh.material = null;
  18634. }
  18635. }
  18636. // Callback
  18637. if (this.onDispose) {
  18638. this.onDispose();
  18639. }
  18640. };
  18641. Material.prototype.copyTo = function (other) {
  18642. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18643. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18644. other.alpha = this.alpha;
  18645. other.fillMode = this.fillMode;
  18646. other.backFaceCulling = this.backFaceCulling;
  18647. other.fogEnabled = this.fogEnabled;
  18648. other.wireframe = this.wireframe;
  18649. other.zOffset = this.zOffset;
  18650. other.alphaMode = this.alphaMode;
  18651. other.sideOrientation = this.sideOrientation;
  18652. other.disableDepthWrite = this.disableDepthWrite;
  18653. other.pointSize = this.pointSize;
  18654. other.pointsCloud = this.pointsCloud;
  18655. };
  18656. Material.prototype.serialize = function () {
  18657. var serializationObject = {};
  18658. serializationObject.name = this.name;
  18659. serializationObject.alpha = this.alpha;
  18660. serializationObject.id = this.id;
  18661. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18662. serializationObject.backFaceCulling = this.backFaceCulling;
  18663. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18664. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18665. return serializationObject;
  18666. };
  18667. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18668. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18669. multiMaterial.id = parsedMultiMaterial.id;
  18670. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18671. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18672. var subMatId = parsedMultiMaterial.materials[matIndex];
  18673. if (subMatId) {
  18674. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18675. }
  18676. else {
  18677. multiMaterial.subMaterials.push(null);
  18678. }
  18679. }
  18680. return multiMaterial;
  18681. };
  18682. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18683. if (!parsedMaterial.customType) {
  18684. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18685. }
  18686. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18687. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18688. ;
  18689. };
  18690. Material._TriangleFillMode = 0;
  18691. Material._WireFrameFillMode = 1;
  18692. Material._PointFillMode = 2;
  18693. Material._ClockWiseSideOrientation = 0;
  18694. Material._CounterClockWiseSideOrientation = 1;
  18695. return Material;
  18696. })();
  18697. BABYLON.Material = Material;
  18698. })(BABYLON || (BABYLON = {}));
  18699. var BABYLON;
  18700. (function (BABYLON) {
  18701. var maxSimultaneousLights = 4;
  18702. var FresnelParameters = (function () {
  18703. function FresnelParameters() {
  18704. this.isEnabled = true;
  18705. this.leftColor = BABYLON.Color3.White();
  18706. this.rightColor = BABYLON.Color3.Black();
  18707. this.bias = 0;
  18708. this.power = 1;
  18709. }
  18710. FresnelParameters.prototype.clone = function () {
  18711. var newFresnelParameters = new FresnelParameters();
  18712. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18713. return new FresnelParameters;
  18714. };
  18715. FresnelParameters.prototype.serialize = function () {
  18716. var serializationObject = {};
  18717. serializationObject.isEnabled = this.isEnabled;
  18718. serializationObject.leftColor = this.leftColor;
  18719. serializationObject.rightColor = this.rightColor;
  18720. serializationObject.bias = this.bias;
  18721. serializationObject.power = this.power;
  18722. return serializationObject;
  18723. };
  18724. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18725. var fresnelParameters = new FresnelParameters();
  18726. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18727. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18728. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18729. fresnelParameters.bias = parsedFresnelParameters.bias;
  18730. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18731. return fresnelParameters;
  18732. };
  18733. return FresnelParameters;
  18734. })();
  18735. BABYLON.FresnelParameters = FresnelParameters;
  18736. var StandardMaterialDefines = (function (_super) {
  18737. __extends(StandardMaterialDefines, _super);
  18738. function StandardMaterialDefines() {
  18739. _super.call(this);
  18740. this.DIFFUSE = false;
  18741. this.AMBIENT = false;
  18742. this.OPACITY = false;
  18743. this.OPACITYRGB = false;
  18744. this.REFLECTION = false;
  18745. this.EMISSIVE = false;
  18746. this.SPECULAR = false;
  18747. this.BUMP = false;
  18748. this.SPECULAROVERALPHA = false;
  18749. this.CLIPPLANE = false;
  18750. this.ALPHATEST = false;
  18751. this.ALPHAFROMDIFFUSE = false;
  18752. this.POINTSIZE = false;
  18753. this.FOG = false;
  18754. this.LIGHT0 = false;
  18755. this.LIGHT1 = false;
  18756. this.LIGHT2 = false;
  18757. this.LIGHT3 = false;
  18758. this.SPOTLIGHT0 = false;
  18759. this.SPOTLIGHT1 = false;
  18760. this.SPOTLIGHT2 = false;
  18761. this.SPOTLIGHT3 = false;
  18762. this.HEMILIGHT0 = false;
  18763. this.HEMILIGHT1 = false;
  18764. this.HEMILIGHT2 = false;
  18765. this.HEMILIGHT3 = false;
  18766. this.POINTLIGHT0 = false;
  18767. this.POINTLIGHT1 = false;
  18768. this.POINTLIGHT2 = false;
  18769. this.POINTLIGHT3 = false;
  18770. this.DIRLIGHT0 = false;
  18771. this.DIRLIGHT1 = false;
  18772. this.DIRLIGHT2 = false;
  18773. this.DIRLIGHT3 = false;
  18774. this.SPECULARTERM = false;
  18775. this.SHADOW0 = false;
  18776. this.SHADOW1 = false;
  18777. this.SHADOW2 = false;
  18778. this.SHADOW3 = false;
  18779. this.SHADOWS = false;
  18780. this.SHADOWVSM0 = false;
  18781. this.SHADOWVSM1 = false;
  18782. this.SHADOWVSM2 = false;
  18783. this.SHADOWVSM3 = false;
  18784. this.SHADOWPCF0 = false;
  18785. this.SHADOWPCF1 = false;
  18786. this.SHADOWPCF2 = false;
  18787. this.SHADOWPCF3 = false;
  18788. this.DIFFUSEFRESNEL = false;
  18789. this.OPACITYFRESNEL = false;
  18790. this.REFLECTIONFRESNEL = false;
  18791. this.EMISSIVEFRESNEL = false;
  18792. this.FRESNEL = false;
  18793. this.NORMAL = false;
  18794. this.UV1 = false;
  18795. this.UV2 = false;
  18796. this.VERTEXCOLOR = false;
  18797. this.VERTEXALPHA = false;
  18798. this.NUM_BONE_INFLUENCERS = 0;
  18799. this.BonesPerMesh = 0;
  18800. this.INSTANCES = false;
  18801. this.GLOSSINESS = false;
  18802. this.ROUGHNESS = false;
  18803. this.EMISSIVEASILLUMINATION = false;
  18804. this.LINKEMISSIVEWITHDIFFUSE = false;
  18805. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18806. this.LIGHTMAP = false;
  18807. this.USELIGHTMAPASSHADOWMAP = false;
  18808. this.REFLECTIONMAP_3D = false;
  18809. this.REFLECTIONMAP_SPHERICAL = false;
  18810. this.REFLECTIONMAP_PLANAR = false;
  18811. this.REFLECTIONMAP_CUBIC = false;
  18812. this.REFLECTIONMAP_PROJECTION = false;
  18813. this.REFLECTIONMAP_SKYBOX = false;
  18814. this.REFLECTIONMAP_EXPLICIT = false;
  18815. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18816. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18817. this.INVERTCUBICMAP = false;
  18818. this.LOGARITHMICDEPTH = false;
  18819. this._keys = Object.keys(this);
  18820. }
  18821. return StandardMaterialDefines;
  18822. })(BABYLON.MaterialDefines);
  18823. var StandardMaterial = (function (_super) {
  18824. __extends(StandardMaterial, _super);
  18825. function StandardMaterial(name, scene) {
  18826. var _this = this;
  18827. _super.call(this, name, scene);
  18828. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18829. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18830. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18831. this.specularPower = 64;
  18832. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18833. this.useAlphaFromDiffuseTexture = false;
  18834. this.useEmissiveAsIllumination = false;
  18835. this.linkEmissiveWithDiffuse = false;
  18836. this.useReflectionFresnelFromSpecular = false;
  18837. this.useSpecularOverAlpha = true;
  18838. this.disableLighting = false;
  18839. this.roughness = 0;
  18840. this.useLightmapAsShadowmap = false;
  18841. this.useGlossinessFromSpecularMapAlpha = false;
  18842. this._renderTargets = new BABYLON.SmartArray(16);
  18843. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18844. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18845. this._defines = new StandardMaterialDefines();
  18846. this._cachedDefines = new StandardMaterialDefines();
  18847. this._cachedDefines.BonesPerMesh = -1;
  18848. this.getRenderTargetTextures = function () {
  18849. _this._renderTargets.reset();
  18850. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18851. _this._renderTargets.push(_this.reflectionTexture);
  18852. }
  18853. return _this._renderTargets;
  18854. };
  18855. }
  18856. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18857. get: function () {
  18858. return this._useLogarithmicDepth;
  18859. },
  18860. set: function (value) {
  18861. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18862. },
  18863. enumerable: true,
  18864. configurable: true
  18865. });
  18866. StandardMaterial.prototype.needAlphaBlending = function () {
  18867. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18868. };
  18869. StandardMaterial.prototype.needAlphaTesting = function () {
  18870. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18871. };
  18872. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18873. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18874. };
  18875. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18876. return this.diffuseTexture;
  18877. };
  18878. // Methods
  18879. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18880. if (!mesh) {
  18881. return true;
  18882. }
  18883. if (this._defines.INSTANCES !== useInstances) {
  18884. return false;
  18885. }
  18886. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18887. return true;
  18888. }
  18889. return false;
  18890. };
  18891. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18892. var lightIndex = 0;
  18893. var needNormals = false;
  18894. for (var index = 0; index < scene.lights.length; index++) {
  18895. var light = scene.lights[index];
  18896. if (!light.isEnabled()) {
  18897. continue;
  18898. }
  18899. // Excluded check
  18900. if (light._excludedMeshesIds.length > 0) {
  18901. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18902. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18903. if (excludedMesh) {
  18904. light.excludedMeshes.push(excludedMesh);
  18905. }
  18906. }
  18907. light._excludedMeshesIds = [];
  18908. }
  18909. // Included check
  18910. if (light._includedOnlyMeshesIds.length > 0) {
  18911. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18912. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18913. if (includedOnlyMesh) {
  18914. light.includedOnlyMeshes.push(includedOnlyMesh);
  18915. }
  18916. }
  18917. light._includedOnlyMeshesIds = [];
  18918. }
  18919. if (!light.canAffectMesh(mesh)) {
  18920. continue;
  18921. }
  18922. needNormals = true;
  18923. defines["LIGHT" + lightIndex] = true;
  18924. var type;
  18925. if (light instanceof BABYLON.SpotLight) {
  18926. type = "SPOTLIGHT" + lightIndex;
  18927. }
  18928. else if (light instanceof BABYLON.HemisphericLight) {
  18929. type = "HEMILIGHT" + lightIndex;
  18930. }
  18931. else if (light instanceof BABYLON.PointLight) {
  18932. type = "POINTLIGHT" + lightIndex;
  18933. }
  18934. else {
  18935. type = "DIRLIGHT" + lightIndex;
  18936. }
  18937. defines[type] = true;
  18938. // Specular
  18939. if (!light.specular.equalsFloats(0, 0, 0)) {
  18940. defines["SPECULARTERM"] = true;
  18941. }
  18942. // Shadows
  18943. if (scene.shadowsEnabled) {
  18944. var shadowGenerator = light.getShadowGenerator();
  18945. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18946. defines["SHADOW" + lightIndex] = true;
  18947. defines["SHADOWS"] = true;
  18948. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18949. defines["SHADOWVSM" + lightIndex] = true;
  18950. }
  18951. if (shadowGenerator.usePoissonSampling) {
  18952. defines["SHADOWPCF" + lightIndex] = true;
  18953. }
  18954. }
  18955. }
  18956. lightIndex++;
  18957. if (lightIndex === maxSimultaneousLights)
  18958. break;
  18959. }
  18960. return needNormals;
  18961. };
  18962. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18963. var lightIndex = 0;
  18964. for (var index = 0; index < scene.lights.length; index++) {
  18965. var light = scene.lights[index];
  18966. if (!light.isEnabled()) {
  18967. continue;
  18968. }
  18969. if (!light.canAffectMesh(mesh)) {
  18970. continue;
  18971. }
  18972. if (light instanceof BABYLON.PointLight) {
  18973. // Point Light
  18974. light.transferToEffect(effect, "vLightData" + lightIndex);
  18975. }
  18976. else if (light instanceof BABYLON.DirectionalLight) {
  18977. // Directional Light
  18978. light.transferToEffect(effect, "vLightData" + lightIndex);
  18979. }
  18980. else if (light instanceof BABYLON.SpotLight) {
  18981. // Spot Light
  18982. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18983. }
  18984. else if (light instanceof BABYLON.HemisphericLight) {
  18985. // Hemispheric Light
  18986. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18987. }
  18988. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18989. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18990. if (defines["SPECULARTERM"]) {
  18991. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18992. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18993. }
  18994. // Shadows
  18995. if (scene.shadowsEnabled) {
  18996. var shadowGenerator = light.getShadowGenerator();
  18997. if (mesh.receiveShadows && shadowGenerator) {
  18998. if (!light.needCube()) {
  18999. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19000. }
  19001. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19002. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19003. }
  19004. }
  19005. lightIndex++;
  19006. if (lightIndex === maxSimultaneousLights)
  19007. break;
  19008. }
  19009. };
  19010. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19011. if (this.checkReadyOnlyOnce) {
  19012. if (this._wasPreviouslyReady) {
  19013. return true;
  19014. }
  19015. }
  19016. var scene = this.getScene();
  19017. if (!this.checkReadyOnEveryCall) {
  19018. if (this._renderId === scene.getRenderId()) {
  19019. if (this._checkCache(scene, mesh, useInstances)) {
  19020. return true;
  19021. }
  19022. }
  19023. }
  19024. var engine = scene.getEngine();
  19025. var needNormals = false;
  19026. var needUVs = false;
  19027. this._defines.reset();
  19028. // Textures
  19029. if (scene.texturesEnabled) {
  19030. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19031. if (!this.diffuseTexture.isReady()) {
  19032. return false;
  19033. }
  19034. else {
  19035. needUVs = true;
  19036. this._defines.DIFFUSE = true;
  19037. }
  19038. }
  19039. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19040. if (!this.ambientTexture.isReady()) {
  19041. return false;
  19042. }
  19043. else {
  19044. needUVs = true;
  19045. this._defines.AMBIENT = true;
  19046. }
  19047. }
  19048. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19049. if (!this.opacityTexture.isReady()) {
  19050. return false;
  19051. }
  19052. else {
  19053. needUVs = true;
  19054. this._defines.OPACITY = true;
  19055. if (this.opacityTexture.getAlphaFromRGB) {
  19056. this._defines.OPACITYRGB = true;
  19057. }
  19058. }
  19059. }
  19060. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19061. if (!this.reflectionTexture.isReady()) {
  19062. return false;
  19063. }
  19064. else {
  19065. needNormals = true;
  19066. this._defines.REFLECTION = true;
  19067. if (this.roughness > 0) {
  19068. this._defines.ROUGHNESS = true;
  19069. }
  19070. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19071. this._defines.INVERTCUBICMAP = true;
  19072. }
  19073. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19074. switch (this.reflectionTexture.coordinatesMode) {
  19075. case BABYLON.Texture.CUBIC_MODE:
  19076. case BABYLON.Texture.INVCUBIC_MODE:
  19077. this._defines.REFLECTIONMAP_CUBIC = true;
  19078. break;
  19079. case BABYLON.Texture.EXPLICIT_MODE:
  19080. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19081. break;
  19082. case BABYLON.Texture.PLANAR_MODE:
  19083. this._defines.REFLECTIONMAP_PLANAR = true;
  19084. break;
  19085. case BABYLON.Texture.PROJECTION_MODE:
  19086. this._defines.REFLECTIONMAP_PROJECTION = true;
  19087. break;
  19088. case BABYLON.Texture.SKYBOX_MODE:
  19089. this._defines.REFLECTIONMAP_SKYBOX = true;
  19090. break;
  19091. case BABYLON.Texture.SPHERICAL_MODE:
  19092. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19093. break;
  19094. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19095. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19096. break;
  19097. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19098. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19099. break;
  19100. }
  19101. }
  19102. }
  19103. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19104. if (!this.emissiveTexture.isReady()) {
  19105. return false;
  19106. }
  19107. else {
  19108. needUVs = true;
  19109. this._defines.EMISSIVE = true;
  19110. }
  19111. }
  19112. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19113. if (!this.lightmapTexture.isReady()) {
  19114. return false;
  19115. }
  19116. else {
  19117. needUVs = true;
  19118. this._defines.LIGHTMAP = true;
  19119. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19120. }
  19121. }
  19122. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19123. if (!this.specularTexture.isReady()) {
  19124. return false;
  19125. }
  19126. else {
  19127. needUVs = true;
  19128. this._defines.SPECULAR = true;
  19129. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19130. }
  19131. }
  19132. }
  19133. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19134. if (!this.bumpTexture.isReady()) {
  19135. return false;
  19136. }
  19137. else {
  19138. needUVs = true;
  19139. this._defines.BUMP = true;
  19140. }
  19141. }
  19142. // Effect
  19143. if (scene.clipPlane) {
  19144. this._defines.CLIPPLANE = true;
  19145. }
  19146. if (engine.getAlphaTesting()) {
  19147. this._defines.ALPHATEST = true;
  19148. }
  19149. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19150. this._defines.ALPHAFROMDIFFUSE = true;
  19151. }
  19152. if (this.useEmissiveAsIllumination) {
  19153. this._defines.EMISSIVEASILLUMINATION = true;
  19154. }
  19155. if (this.linkEmissiveWithDiffuse) {
  19156. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19157. }
  19158. if (this.useReflectionFresnelFromSpecular) {
  19159. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19160. }
  19161. if (this.useLogarithmicDepth) {
  19162. this._defines.LOGARITHMICDEPTH = true;
  19163. }
  19164. // Point size
  19165. if (this.pointsCloud || scene.forcePointsCloud) {
  19166. this._defines.POINTSIZE = true;
  19167. }
  19168. // Fog
  19169. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19170. this._defines.FOG = true;
  19171. }
  19172. if (scene.lightsEnabled && !this.disableLighting) {
  19173. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19174. }
  19175. if (StandardMaterial.FresnelEnabled) {
  19176. // Fresnel
  19177. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19178. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19179. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19180. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19181. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19182. this._defines.DIFFUSEFRESNEL = true;
  19183. }
  19184. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19185. this._defines.OPACITYFRESNEL = true;
  19186. }
  19187. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19188. this._defines.REFLECTIONFRESNEL = true;
  19189. }
  19190. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19191. this._defines.EMISSIVEFRESNEL = true;
  19192. }
  19193. needNormals = true;
  19194. this._defines.FRESNEL = true;
  19195. }
  19196. }
  19197. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19198. this._defines.SPECULAROVERALPHA = true;
  19199. }
  19200. // Attribs
  19201. if (mesh) {
  19202. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19203. this._defines.NORMAL = true;
  19204. }
  19205. if (needUVs) {
  19206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19207. this._defines.UV1 = true;
  19208. }
  19209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19210. this._defines.UV2 = true;
  19211. }
  19212. }
  19213. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19214. this._defines.VERTEXCOLOR = true;
  19215. if (mesh.hasVertexAlpha) {
  19216. this._defines.VERTEXALPHA = true;
  19217. }
  19218. }
  19219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19220. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19221. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19222. }
  19223. // Instances
  19224. if (useInstances) {
  19225. this._defines.INSTANCES = true;
  19226. }
  19227. }
  19228. // Get correct effect
  19229. if (!this._defines.isEqual(this._cachedDefines)) {
  19230. this._defines.cloneTo(this._cachedDefines);
  19231. scene.resetCachedMaterial();
  19232. // Fallbacks
  19233. var fallbacks = new BABYLON.EffectFallbacks();
  19234. if (this._defines.REFLECTION) {
  19235. fallbacks.addFallback(0, "REFLECTION");
  19236. }
  19237. if (this._defines.SPECULAR) {
  19238. fallbacks.addFallback(0, "SPECULAR");
  19239. }
  19240. if (this._defines.BUMP) {
  19241. fallbacks.addFallback(0, "BUMP");
  19242. }
  19243. if (this._defines.SPECULAROVERALPHA) {
  19244. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19245. }
  19246. if (this._defines.FOG) {
  19247. fallbacks.addFallback(1, "FOG");
  19248. }
  19249. if (this._defines.POINTSIZE) {
  19250. fallbacks.addFallback(0, "POINTSIZE");
  19251. }
  19252. if (this._defines.LOGARITHMICDEPTH) {
  19253. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19254. }
  19255. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19256. if (!this._defines["LIGHT" + lightIndex]) {
  19257. continue;
  19258. }
  19259. if (lightIndex > 0) {
  19260. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19261. }
  19262. if (this._defines["SHADOW" + lightIndex]) {
  19263. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19264. }
  19265. if (this._defines["SHADOWPCF" + lightIndex]) {
  19266. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19267. }
  19268. if (this._defines["SHADOWVSM" + lightIndex]) {
  19269. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19270. }
  19271. }
  19272. if (this._defines.SPECULARTERM) {
  19273. fallbacks.addFallback(0, "SPECULARTERM");
  19274. }
  19275. if (this._defines.DIFFUSEFRESNEL) {
  19276. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19277. }
  19278. if (this._defines.OPACITYFRESNEL) {
  19279. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19280. }
  19281. if (this._defines.REFLECTIONFRESNEL) {
  19282. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19283. }
  19284. if (this._defines.EMISSIVEFRESNEL) {
  19285. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19286. }
  19287. if (this._defines.FRESNEL) {
  19288. fallbacks.addFallback(4, "FRESNEL");
  19289. }
  19290. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19291. fallbacks.addCPUSkinningFallback(0, mesh);
  19292. }
  19293. //Attributes
  19294. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19295. if (this._defines.NORMAL) {
  19296. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19297. }
  19298. if (this._defines.UV1) {
  19299. attribs.push(BABYLON.VertexBuffer.UVKind);
  19300. }
  19301. if (this._defines.UV2) {
  19302. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19303. }
  19304. if (this._defines.VERTEXCOLOR) {
  19305. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19306. }
  19307. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19310. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19313. }
  19314. }
  19315. if (this._defines.INSTANCES) {
  19316. attribs.push("world0");
  19317. attribs.push("world1");
  19318. attribs.push("world2");
  19319. attribs.push("world3");
  19320. }
  19321. // Legacy browser patch
  19322. var shaderName = "default";
  19323. if (!scene.getEngine().getCaps().standardDerivatives) {
  19324. shaderName = "legacydefault";
  19325. }
  19326. var join = this._defines.toString();
  19327. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19328. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19329. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19330. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19331. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19332. "vFogInfos", "vFogColor", "pointSize",
  19333. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19334. "mBones",
  19335. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19336. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19337. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19338. "logarithmicDepthConstant"
  19339. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19340. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19341. ], join, fallbacks, this.onCompiled, this.onError);
  19342. }
  19343. if (!this._effect.isReady()) {
  19344. return false;
  19345. }
  19346. this._renderId = scene.getRenderId();
  19347. this._wasPreviouslyReady = true;
  19348. if (mesh) {
  19349. if (!mesh._materialDefines) {
  19350. mesh._materialDefines = new StandardMaterialDefines();
  19351. }
  19352. this._defines.cloneTo(mesh._materialDefines);
  19353. }
  19354. return true;
  19355. };
  19356. StandardMaterial.prototype.unbind = function () {
  19357. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19358. this._effect.setTexture("reflection2DSampler", null);
  19359. }
  19360. _super.prototype.unbind.call(this);
  19361. };
  19362. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19363. this._effect.setMatrix("world", world);
  19364. };
  19365. StandardMaterial.prototype.bind = function (world, mesh) {
  19366. var scene = this.getScene();
  19367. // Matrices
  19368. this.bindOnlyWorldMatrix(world);
  19369. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19370. // Bones
  19371. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19372. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19373. }
  19374. if (scene.getCachedMaterial() !== this) {
  19375. if (StandardMaterial.FresnelEnabled) {
  19376. // Fresnel
  19377. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19378. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19379. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19380. }
  19381. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19382. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19383. }
  19384. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19385. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19386. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19387. }
  19388. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19389. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19390. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19391. }
  19392. }
  19393. // Textures
  19394. if (scene.texturesEnabled) {
  19395. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19396. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19397. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19398. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19399. }
  19400. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19401. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19402. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19403. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19404. }
  19405. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19406. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19407. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19408. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19409. }
  19410. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19411. if (this.reflectionTexture.isCube) {
  19412. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19413. }
  19414. else {
  19415. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19416. }
  19417. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19418. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19419. }
  19420. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19421. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19422. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19423. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19424. }
  19425. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19426. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19427. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19428. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19429. }
  19430. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19431. this._effect.setTexture("specularSampler", this.specularTexture);
  19432. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19433. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19434. }
  19435. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19436. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19437. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19438. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19439. }
  19440. }
  19441. // Clip plane
  19442. if (scene.clipPlane) {
  19443. var clipPlane = scene.clipPlane;
  19444. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19445. }
  19446. // Point size
  19447. if (this.pointsCloud) {
  19448. this._effect.setFloat("pointSize", this.pointSize);
  19449. }
  19450. // Colors
  19451. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19452. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19453. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19454. if (this._defines.SPECULARTERM) {
  19455. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19456. }
  19457. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19458. }
  19459. // Diffuse
  19460. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19461. // Lights
  19462. if (scene.lightsEnabled && !this.disableLighting) {
  19463. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19464. }
  19465. // View
  19466. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19467. this._effect.setMatrix("view", scene.getViewMatrix());
  19468. }
  19469. // Fog
  19470. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19471. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19472. this._effect.setColor3("vFogColor", scene.fogColor);
  19473. }
  19474. // Log. depth
  19475. if (this._defines.LOGARITHMICDEPTH) {
  19476. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19477. }
  19478. _super.prototype.bind.call(this, world, mesh);
  19479. };
  19480. StandardMaterial.prototype.getAnimatables = function () {
  19481. var results = [];
  19482. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19483. results.push(this.diffuseTexture);
  19484. }
  19485. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19486. results.push(this.ambientTexture);
  19487. }
  19488. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19489. results.push(this.opacityTexture);
  19490. }
  19491. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19492. results.push(this.reflectionTexture);
  19493. }
  19494. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19495. results.push(this.emissiveTexture);
  19496. }
  19497. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19498. results.push(this.specularTexture);
  19499. }
  19500. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19501. results.push(this.bumpTexture);
  19502. }
  19503. return results;
  19504. };
  19505. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19506. if (this.diffuseTexture) {
  19507. this.diffuseTexture.dispose();
  19508. }
  19509. if (this.ambientTexture) {
  19510. this.ambientTexture.dispose();
  19511. }
  19512. if (this.opacityTexture) {
  19513. this.opacityTexture.dispose();
  19514. }
  19515. if (this.reflectionTexture) {
  19516. this.reflectionTexture.dispose();
  19517. }
  19518. if (this.emissiveTexture) {
  19519. this.emissiveTexture.dispose();
  19520. }
  19521. if (this.specularTexture) {
  19522. this.specularTexture.dispose();
  19523. }
  19524. if (this.bumpTexture) {
  19525. this.bumpTexture.dispose();
  19526. }
  19527. _super.prototype.dispose.call(this, forceDisposeEffect);
  19528. };
  19529. StandardMaterial.prototype.clone = function (name) {
  19530. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19531. // Base material
  19532. this.copyTo(newStandardMaterial);
  19533. // Standard material
  19534. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19535. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19536. }
  19537. if (this.ambientTexture && this.ambientTexture.clone) {
  19538. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19539. }
  19540. if (this.opacityTexture && this.opacityTexture.clone) {
  19541. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19542. }
  19543. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19544. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19545. }
  19546. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19547. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19548. }
  19549. if (this.specularTexture && this.specularTexture.clone) {
  19550. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19551. }
  19552. if (this.bumpTexture && this.bumpTexture.clone) {
  19553. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19554. }
  19555. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19556. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19557. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19558. }
  19559. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19560. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19561. newStandardMaterial.specularColor = this.specularColor.clone();
  19562. newStandardMaterial.specularPower = this.specularPower;
  19563. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19564. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19565. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19566. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19567. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19568. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19569. newStandardMaterial.roughness = this.roughness;
  19570. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19571. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19572. }
  19573. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19574. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19575. }
  19576. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19577. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19578. }
  19579. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19580. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19581. }
  19582. return newStandardMaterial;
  19583. };
  19584. StandardMaterial.prototype.serialize = function () {
  19585. var serializationObject = _super.prototype.serialize.call(this);
  19586. serializationObject.ambient = this.ambientColor.asArray();
  19587. serializationObject.diffuse = this.diffuseColor.asArray();
  19588. serializationObject.specular = this.specularColor.asArray();
  19589. serializationObject.specularPower = this.specularPower;
  19590. serializationObject.emissive = this.emissiveColor.asArray();
  19591. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19592. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19593. if (this.diffuseTexture) {
  19594. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19595. }
  19596. if (this.diffuseFresnelParameters) {
  19597. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19598. }
  19599. if (this.ambientTexture) {
  19600. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19601. }
  19602. if (this.opacityTexture) {
  19603. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19604. }
  19605. if (this.opacityFresnelParameters) {
  19606. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19607. }
  19608. if (this.reflectionTexture) {
  19609. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19610. }
  19611. if (this.reflectionFresnelParameters) {
  19612. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19613. }
  19614. if (this.emissiveTexture) {
  19615. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19616. }
  19617. if (this.lightmapTexture) {
  19618. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19619. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19620. }
  19621. if (this.emissiveFresnelParameters) {
  19622. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19623. }
  19624. if (this.specularTexture) {
  19625. serializationObject.specularTexture = this.specularTexture.serialize();
  19626. }
  19627. if (this.bumpTexture) {
  19628. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19629. }
  19630. return serializationObject;
  19631. };
  19632. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19633. var material = new StandardMaterial(source.name, scene);
  19634. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19635. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19636. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19637. material.specularPower = source.specularPower;
  19638. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19639. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19640. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19641. material.alpha = source.alpha;
  19642. material.id = source.id;
  19643. if (source.disableDepthWrite) {
  19644. material.disableDepthWrite = source.disableDepthWrite;
  19645. }
  19646. BABYLON.Tags.AddTagsTo(material, source.tags);
  19647. material.backFaceCulling = source.backFaceCulling;
  19648. material.wireframe = source.wireframe;
  19649. if (source.diffuseTexture) {
  19650. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19651. }
  19652. if (source.diffuseFresnelParameters) {
  19653. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19654. }
  19655. if (source.ambientTexture) {
  19656. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19657. }
  19658. if (source.opacityTexture) {
  19659. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19660. }
  19661. if (source.opacityFresnelParameters) {
  19662. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19663. }
  19664. if (source.reflectionTexture) {
  19665. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19666. }
  19667. if (source.reflectionFresnelParameters) {
  19668. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19669. }
  19670. if (source.emissiveTexture) {
  19671. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19672. }
  19673. if (source.lightmapTexture) {
  19674. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19675. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19676. }
  19677. if (source.emissiveFresnelParameters) {
  19678. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19679. }
  19680. if (source.specularTexture) {
  19681. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19682. }
  19683. if (source.bumpTexture) {
  19684. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19685. }
  19686. if (source.checkReadyOnlyOnce) {
  19687. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19688. }
  19689. return material;
  19690. };
  19691. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19692. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19693. // Statics
  19694. // Flags used to enable or disable a type of texture for all Standard Materials
  19695. StandardMaterial.DiffuseTextureEnabled = true;
  19696. StandardMaterial.AmbientTextureEnabled = true;
  19697. StandardMaterial.OpacityTextureEnabled = true;
  19698. StandardMaterial.ReflectionTextureEnabled = true;
  19699. StandardMaterial.EmissiveTextureEnabled = true;
  19700. StandardMaterial.SpecularTextureEnabled = true;
  19701. StandardMaterial.BumpTextureEnabled = true;
  19702. StandardMaterial.FresnelEnabled = true;
  19703. StandardMaterial.LightmapEnabled = true;
  19704. return StandardMaterial;
  19705. })(BABYLON.Material);
  19706. BABYLON.StandardMaterial = StandardMaterial;
  19707. })(BABYLON || (BABYLON = {}));
  19708. var BABYLON;
  19709. (function (BABYLON) {
  19710. var MultiMaterial = (function (_super) {
  19711. __extends(MultiMaterial, _super);
  19712. function MultiMaterial(name, scene) {
  19713. _super.call(this, name, scene, true);
  19714. this.subMaterials = new Array();
  19715. scene.multiMaterials.push(this);
  19716. }
  19717. // Properties
  19718. MultiMaterial.prototype.getSubMaterial = function (index) {
  19719. if (index < 0 || index >= this.subMaterials.length) {
  19720. return this.getScene().defaultMaterial;
  19721. }
  19722. return this.subMaterials[index];
  19723. };
  19724. // Methods
  19725. MultiMaterial.prototype.isReady = function (mesh) {
  19726. for (var index = 0; index < this.subMaterials.length; index++) {
  19727. var subMaterial = this.subMaterials[index];
  19728. if (subMaterial) {
  19729. if (!this.subMaterials[index].isReady(mesh)) {
  19730. return false;
  19731. }
  19732. }
  19733. }
  19734. return true;
  19735. };
  19736. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19737. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19738. for (var index = 0; index < this.subMaterials.length; index++) {
  19739. var subMaterial = null;
  19740. if (cloneChildren) {
  19741. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19742. }
  19743. else {
  19744. subMaterial = this.subMaterials[index];
  19745. }
  19746. newMultiMaterial.subMaterials.push(subMaterial);
  19747. }
  19748. return newMultiMaterial;
  19749. };
  19750. MultiMaterial.prototype.serialize = function () {
  19751. var serializationObject = {};
  19752. serializationObject.name = this.name;
  19753. serializationObject.id = this.id;
  19754. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19755. serializationObject.materials = [];
  19756. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19757. var subMat = this.subMaterials[matIndex];
  19758. if (subMat) {
  19759. serializationObject.materials.push(subMat.id);
  19760. }
  19761. else {
  19762. serializationObject.materials.push(null);
  19763. }
  19764. }
  19765. return serializationObject;
  19766. };
  19767. return MultiMaterial;
  19768. })(BABYLON.Material);
  19769. BABYLON.MultiMaterial = MultiMaterial;
  19770. })(BABYLON || (BABYLON = {}));
  19771. var BABYLON;
  19772. (function (BABYLON) {
  19773. var SceneLoader = (function () {
  19774. function SceneLoader() {
  19775. }
  19776. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19777. get: function () {
  19778. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19779. },
  19780. set: function (value) {
  19781. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19787. get: function () {
  19788. return SceneLoader._ShowLoadingScreen;
  19789. },
  19790. set: function (value) {
  19791. SceneLoader._ShowLoadingScreen = value;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19797. var dotPosition = sceneFilename.lastIndexOf(".");
  19798. var queryStringPosition = sceneFilename.indexOf("?");
  19799. if (queryStringPosition === -1) {
  19800. queryStringPosition = sceneFilename.length;
  19801. }
  19802. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19803. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19804. var plugin = this._registeredPlugins[index];
  19805. if (plugin.extensions.indexOf(extension) !== -1) {
  19806. return plugin;
  19807. }
  19808. }
  19809. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19810. };
  19811. // Public functions
  19812. SceneLoader.RegisterPlugin = function (plugin) {
  19813. plugin.extensions = plugin.extensions.toLowerCase();
  19814. SceneLoader._registeredPlugins.push(plugin);
  19815. };
  19816. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19817. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19818. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19819. return;
  19820. }
  19821. var loadingToken = {};
  19822. scene._addPendingData(loadingToken);
  19823. var manifestChecked = function (success) {
  19824. scene.database = database;
  19825. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19826. var importMeshFromData = function (data) {
  19827. var meshes = [];
  19828. var particleSystems = [];
  19829. var skeletons = [];
  19830. try {
  19831. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19832. if (onerror) {
  19833. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19834. }
  19835. scene._removePendingData(loadingToken);
  19836. return;
  19837. }
  19838. }
  19839. catch (e) {
  19840. if (onerror) {
  19841. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19842. }
  19843. scene._removePendingData(loadingToken);
  19844. return;
  19845. }
  19846. if (onsuccess) {
  19847. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19848. onsuccess(meshes, particleSystems, skeletons);
  19849. scene._removePendingData(loadingToken);
  19850. }
  19851. };
  19852. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19853. // Direct load
  19854. importMeshFromData(sceneFilename.substr(5));
  19855. return;
  19856. }
  19857. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19858. importMeshFromData(data);
  19859. }, progressCallBack, database);
  19860. };
  19861. if (scene.getEngine().enableOfflineSupport) {
  19862. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19863. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19864. }
  19865. else {
  19866. manifestChecked(true);
  19867. }
  19868. };
  19869. /**
  19870. * Load a scene
  19871. * @param rootUrl a string that defines the root url for scene and resources
  19872. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19873. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19874. */
  19875. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19876. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19877. };
  19878. /**
  19879. * Append a scene
  19880. * @param rootUrl a string that defines the root url for scene and resources
  19881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19882. * @param scene is the instance of BABYLON.Scene to append to
  19883. */
  19884. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19885. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19886. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19887. return;
  19888. }
  19889. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19890. var database;
  19891. var loadingToken = {};
  19892. scene._addPendingData(loadingToken);
  19893. if (SceneLoader.ShowLoadingScreen) {
  19894. scene.getEngine().displayLoadingUI();
  19895. }
  19896. var loadSceneFromData = function (data) {
  19897. scene.database = database;
  19898. if (!plugin.load(scene, data, rootUrl)) {
  19899. if (onerror) {
  19900. onerror(scene);
  19901. }
  19902. scene._removePendingData(loadingToken);
  19903. scene.getEngine().hideLoadingUI();
  19904. return;
  19905. }
  19906. if (onsuccess) {
  19907. onsuccess(scene);
  19908. }
  19909. scene._removePendingData(loadingToken);
  19910. if (SceneLoader.ShowLoadingScreen) {
  19911. scene.executeWhenReady(function () {
  19912. scene.getEngine().hideLoadingUI();
  19913. });
  19914. }
  19915. };
  19916. var manifestChecked = function (success) {
  19917. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19918. };
  19919. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19920. // Direct load
  19921. loadSceneFromData(sceneFilename.substr(5));
  19922. return;
  19923. }
  19924. if (rootUrl.indexOf("file:") === -1) {
  19925. if (scene.getEngine().enableOfflineSupport) {
  19926. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19927. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19928. }
  19929. else {
  19930. manifestChecked(true);
  19931. }
  19932. }
  19933. else {
  19934. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19935. }
  19936. };
  19937. // Flags
  19938. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19939. SceneLoader._ShowLoadingScreen = true;
  19940. // Members
  19941. SceneLoader._registeredPlugins = new Array();
  19942. return SceneLoader;
  19943. })();
  19944. BABYLON.SceneLoader = SceneLoader;
  19945. ;
  19946. })(BABYLON || (BABYLON = {}));
  19947. var BABYLON;
  19948. (function (BABYLON) {
  19949. var Internals;
  19950. (function (Internals) {
  19951. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19952. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  19953. var parsedMaterial = parsedData.materials[index];
  19954. if (parsedMaterial.id === id) {
  19955. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  19956. }
  19957. }
  19958. return null;
  19959. };
  19960. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19961. names = (names instanceof Array) ? names : [names];
  19962. for (var i in names) {
  19963. if (mesh.name === names[i]) {
  19964. hierarchyIds.push(mesh.id);
  19965. return true;
  19966. }
  19967. }
  19968. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19969. hierarchyIds.push(mesh.id);
  19970. return true;
  19971. }
  19972. return false;
  19973. };
  19974. BABYLON.SceneLoader.RegisterPlugin({
  19975. extensions: ".babylon",
  19976. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19977. var parsedData = JSON.parse(data);
  19978. var loadedSkeletonsIds = [];
  19979. var loadedMaterialsIds = [];
  19980. var hierarchyIds = [];
  19981. var index;
  19982. var cache;
  19983. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  19984. var parsedMesh = parsedData.meshes[index];
  19985. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19986. if (meshesNames instanceof Array) {
  19987. // Remove found mesh name from list.
  19988. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19989. }
  19990. //Geometry?
  19991. if (parsedMesh.geometryId) {
  19992. //does the file contain geometries?
  19993. if (parsedData.geometries) {
  19994. //find the correct geometry and add it to the scene
  19995. var found = false;
  19996. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19997. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19998. return;
  19999. }
  20000. else {
  20001. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20002. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20003. switch (geometryType) {
  20004. case "boxes":
  20005. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20006. break;
  20007. case "spheres":
  20008. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20009. break;
  20010. case "cylinders":
  20011. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20012. break;
  20013. case "toruses":
  20014. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20015. break;
  20016. case "grounds":
  20017. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20018. break;
  20019. case "planes":
  20020. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20021. break;
  20022. case "torusKnots":
  20023. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20024. break;
  20025. case "vertexData":
  20026. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20027. break;
  20028. }
  20029. found = true;
  20030. }
  20031. });
  20032. }
  20033. });
  20034. if (!found) {
  20035. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20036. }
  20037. }
  20038. }
  20039. // Material ?
  20040. if (parsedMesh.materialId) {
  20041. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20042. if (!materialFound && parsedData.multiMaterials) {
  20043. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20044. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20045. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20046. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20047. var subMatId = parsedMultiMaterial.materials[matIndex];
  20048. loadedMaterialsIds.push(subMatId);
  20049. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20050. }
  20051. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20052. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20053. materialFound = true;
  20054. break;
  20055. }
  20056. }
  20057. }
  20058. if (!materialFound) {
  20059. loadedMaterialsIds.push(parsedMesh.materialId);
  20060. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20061. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20062. }
  20063. }
  20064. }
  20065. // Skeleton ?
  20066. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20067. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20068. if (!skeletonAlreadyLoaded) {
  20069. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20070. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20071. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20072. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20073. loadedSkeletonsIds.push(parsedSkeleton.id);
  20074. }
  20075. }
  20076. }
  20077. }
  20078. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20079. meshes.push(mesh);
  20080. }
  20081. }
  20082. // Connecting parents
  20083. var currentMesh;
  20084. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20085. currentMesh = scene.meshes[index];
  20086. if (currentMesh._waitingParentId) {
  20087. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20088. currentMesh._waitingParentId = undefined;
  20089. }
  20090. }
  20091. // freeze world matrix application
  20092. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20093. currentMesh = scene.meshes[index];
  20094. if (currentMesh._waitingFreezeWorldMatrix) {
  20095. currentMesh.freezeWorldMatrix();
  20096. currentMesh._waitingFreezeWorldMatrix = undefined;
  20097. }
  20098. }
  20099. // Particles
  20100. if (parsedData.particleSystems) {
  20101. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20102. var parsedParticleSystem = parsedData.particleSystems[index];
  20103. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20104. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20105. }
  20106. }
  20107. }
  20108. return true;
  20109. },
  20110. load: function (scene, data, rootUrl) {
  20111. var parsedData = JSON.parse(data);
  20112. // Scene
  20113. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20114. scene.autoClear = parsedData.autoClear;
  20115. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20116. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20117. if (parsedData.gravity) {
  20118. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20119. }
  20120. // Fog
  20121. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20122. scene.fogMode = parsedData.fogMode;
  20123. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20124. scene.fogStart = parsedData.fogStart;
  20125. scene.fogEnd = parsedData.fogEnd;
  20126. scene.fogDensity = parsedData.fogDensity;
  20127. }
  20128. //Physics
  20129. if (parsedData.physicsEnabled) {
  20130. var physicsPlugin;
  20131. if (parsedData.physicsEngine === "cannon") {
  20132. physicsPlugin = new BABYLON.CannonJSPlugin();
  20133. }
  20134. else if (parsedData.physicsEngine === "oimo") {
  20135. physicsPlugin = new BABYLON.OimoJSPlugin();
  20136. }
  20137. //else - default engine, which is currently oimo
  20138. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20139. scene.enablePhysics(physicsGravity, physicsPlugin);
  20140. }
  20141. //collisions, if defined. otherwise, default is true
  20142. if (parsedData.collisionsEnabled != undefined) {
  20143. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20144. }
  20145. scene.workerCollisions = !!parsedData.workerCollisions;
  20146. var index;
  20147. var cache;
  20148. // Lights
  20149. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20150. var parsedLight = parsedData.lights[index];
  20151. BABYLON.Light.Parse(parsedLight, scene);
  20152. }
  20153. // Materials
  20154. if (parsedData.materials) {
  20155. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20156. var parsedMaterial = parsedData.materials[index];
  20157. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20158. }
  20159. }
  20160. if (parsedData.multiMaterials) {
  20161. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20162. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20163. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20164. }
  20165. }
  20166. // Skeletons
  20167. if (parsedData.skeletons) {
  20168. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20169. var parsedSkeleton = parsedData.skeletons[index];
  20170. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20171. }
  20172. }
  20173. // Geometries
  20174. var geometries = parsedData.geometries;
  20175. if (geometries) {
  20176. // Boxes
  20177. var boxes = geometries.boxes;
  20178. if (boxes) {
  20179. for (index = 0, cache = boxes.length; index < cache; index++) {
  20180. var parsedBox = boxes[index];
  20181. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20182. }
  20183. }
  20184. // Spheres
  20185. var spheres = geometries.spheres;
  20186. if (spheres) {
  20187. for (index = 0, cache = spheres.length; index < cache; index++) {
  20188. var parsedSphere = spheres[index];
  20189. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20190. }
  20191. }
  20192. // Cylinders
  20193. var cylinders = geometries.cylinders;
  20194. if (cylinders) {
  20195. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20196. var parsedCylinder = cylinders[index];
  20197. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20198. }
  20199. }
  20200. // Toruses
  20201. var toruses = geometries.toruses;
  20202. if (toruses) {
  20203. for (index = 0, cache = toruses.length; index < cache; index++) {
  20204. var parsedTorus = toruses[index];
  20205. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20206. }
  20207. }
  20208. // Grounds
  20209. var grounds = geometries.grounds;
  20210. if (grounds) {
  20211. for (index = 0, cache = grounds.length; index < cache; index++) {
  20212. var parsedGround = grounds[index];
  20213. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20214. }
  20215. }
  20216. // Planes
  20217. var planes = geometries.planes;
  20218. if (planes) {
  20219. for (index = 0, cache = planes.length; index < cache; index++) {
  20220. var parsedPlane = planes[index];
  20221. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20222. }
  20223. }
  20224. // TorusKnots
  20225. var torusKnots = geometries.torusKnots;
  20226. if (torusKnots) {
  20227. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20228. var parsedTorusKnot = torusKnots[index];
  20229. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20230. }
  20231. }
  20232. // VertexData
  20233. var vertexData = geometries.vertexData;
  20234. if (vertexData) {
  20235. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20236. var parsedVertexData = vertexData[index];
  20237. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20238. }
  20239. }
  20240. }
  20241. // Meshes
  20242. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20243. var parsedMesh = parsedData.meshes[index];
  20244. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20245. }
  20246. // Cameras
  20247. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20248. var parsedCamera = parsedData.cameras[index];
  20249. BABYLON.Camera.Parse(parsedCamera, scene);
  20250. }
  20251. if (parsedData.activeCameraID) {
  20252. scene.setActiveCameraByID(parsedData.activeCameraID);
  20253. }
  20254. // Browsing all the graph to connect the dots
  20255. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20256. var camera = scene.cameras[index];
  20257. if (camera._waitingParentId) {
  20258. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20259. camera._waitingParentId = undefined;
  20260. }
  20261. }
  20262. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20263. var light = scene.lights[index];
  20264. if (light._waitingParentId) {
  20265. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20266. light._waitingParentId = undefined;
  20267. }
  20268. }
  20269. // Sounds
  20270. if (BABYLON.AudioEngine && parsedData.sounds) {
  20271. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20272. var parsedSound = parsedData.sounds[index];
  20273. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20274. BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20275. }
  20276. else {
  20277. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20278. }
  20279. }
  20280. }
  20281. // Connect parents & children and parse actions
  20282. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20283. var mesh = scene.meshes[index];
  20284. if (mesh._waitingParentId) {
  20285. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20286. mesh._waitingParentId = undefined;
  20287. }
  20288. if (mesh._waitingActions) {
  20289. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20290. mesh._waitingActions = undefined;
  20291. }
  20292. }
  20293. // freeze world matrix application
  20294. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20295. var currentMesh = scene.meshes[index];
  20296. if (currentMesh._waitingFreezeWorldMatrix) {
  20297. currentMesh.freezeWorldMatrix();
  20298. currentMesh._waitingFreezeWorldMatrix = undefined;
  20299. }
  20300. }
  20301. // Particles Systems
  20302. if (parsedData.particleSystems) {
  20303. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20304. var parsedParticleSystem = parsedData.particleSystems[index];
  20305. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20306. }
  20307. }
  20308. // Lens flares
  20309. if (parsedData.lensFlareSystems) {
  20310. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20311. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20312. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20313. }
  20314. }
  20315. // Shadows
  20316. if (parsedData.shadowGenerators) {
  20317. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20318. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20319. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20320. }
  20321. }
  20322. // Actions (scene)
  20323. if (parsedData.actions) {
  20324. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20325. }
  20326. // Finish
  20327. return true;
  20328. }
  20329. });
  20330. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20331. })(BABYLON || (BABYLON = {}));
  20332. var BABYLON;
  20333. (function (BABYLON) {
  20334. var SpriteManager = (function () {
  20335. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20337. this.name = name;
  20338. this.cellSize = cellSize;
  20339. this.sprites = new Array();
  20340. this.renderingGroupId = 0;
  20341. this.layerMask = 0x0FFFFFFF;
  20342. this.fogEnabled = true;
  20343. this.isPickable = false;
  20344. this._vertexDeclaration = [4, 4, 4, 4];
  20345. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20346. this._capacity = capacity;
  20347. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20348. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20349. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20350. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20351. this._scene = scene;
  20352. this._scene.spriteManagers.push(this);
  20353. // VBO
  20354. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20355. var indices = [];
  20356. var index = 0;
  20357. for (var count = 0; count < capacity; count++) {
  20358. indices.push(index);
  20359. indices.push(index + 1);
  20360. indices.push(index + 2);
  20361. indices.push(index);
  20362. indices.push(index + 2);
  20363. indices.push(index + 3);
  20364. index += 4;
  20365. }
  20366. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20367. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20368. // Effects
  20369. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20370. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20371. }
  20372. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20373. var arrayOffset = index * 16;
  20374. if (offsetX === 0)
  20375. offsetX = this._epsilon;
  20376. else if (offsetX === 1)
  20377. offsetX = 1 - this._epsilon;
  20378. if (offsetY === 0)
  20379. offsetY = this._epsilon;
  20380. else if (offsetY === 1)
  20381. offsetY = 1 - this._epsilon;
  20382. this._vertices[arrayOffset] = sprite.position.x;
  20383. this._vertices[arrayOffset + 1] = sprite.position.y;
  20384. this._vertices[arrayOffset + 2] = sprite.position.z;
  20385. this._vertices[arrayOffset + 3] = sprite.angle;
  20386. this._vertices[arrayOffset + 4] = sprite.width;
  20387. this._vertices[arrayOffset + 5] = sprite.height;
  20388. this._vertices[arrayOffset + 6] = offsetX;
  20389. this._vertices[arrayOffset + 7] = offsetY;
  20390. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20391. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20392. var offset = (sprite.cellIndex / rowSize) >> 0;
  20393. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20394. this._vertices[arrayOffset + 11] = offset;
  20395. // Color
  20396. this._vertices[arrayOffset + 12] = sprite.color.r;
  20397. this._vertices[arrayOffset + 13] = sprite.color.g;
  20398. this._vertices[arrayOffset + 14] = sprite.color.b;
  20399. this._vertices[arrayOffset + 15] = sprite.color.a;
  20400. };
  20401. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20402. var count = Math.min(this._capacity, this.sprites.length);
  20403. var min = BABYLON.Vector3.Zero();
  20404. var max = BABYLON.Vector3.Zero();
  20405. var distance = Number.MAX_VALUE;
  20406. var currentSprite;
  20407. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20408. var cameraView = camera.getViewMatrix();
  20409. for (var index = 0; index < count; index++) {
  20410. var sprite = this.sprites[index];
  20411. if (!sprite) {
  20412. continue;
  20413. }
  20414. if (predicate) {
  20415. if (!predicate(sprite)) {
  20416. continue;
  20417. }
  20418. }
  20419. else if (!sprite.isPickable) {
  20420. continue;
  20421. }
  20422. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20423. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20424. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20425. if (ray.intersectsBoxMinMax(min, max)) {
  20426. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20427. if (distance > currentDistance) {
  20428. distance = currentDistance;
  20429. currentSprite = sprite;
  20430. if (fastCheck) {
  20431. break;
  20432. }
  20433. }
  20434. }
  20435. }
  20436. if (currentSprite) {
  20437. var result = new BABYLON.PickingInfo();
  20438. result.hit = true;
  20439. result.pickedSprite = currentSprite;
  20440. result.distance = distance;
  20441. return result;
  20442. }
  20443. return null;
  20444. };
  20445. SpriteManager.prototype.render = function () {
  20446. // Check
  20447. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20448. return;
  20449. var engine = this._scene.getEngine();
  20450. var baseSize = this._spriteTexture.getBaseSize();
  20451. // Sprites
  20452. var deltaTime = engine.getDeltaTime();
  20453. var max = Math.min(this._capacity, this.sprites.length);
  20454. var rowSize = baseSize.width / this.cellSize;
  20455. var offset = 0;
  20456. for (var index = 0; index < max; index++) {
  20457. var sprite = this.sprites[index];
  20458. if (!sprite) {
  20459. continue;
  20460. }
  20461. sprite._animate(deltaTime);
  20462. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20463. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20464. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20465. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20466. }
  20467. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20468. // Render
  20469. var effect = this._effectBase;
  20470. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20471. effect = this._effectFog;
  20472. }
  20473. engine.enableEffect(effect);
  20474. var viewMatrix = this._scene.getViewMatrix();
  20475. effect.setTexture("diffuseSampler", this._spriteTexture);
  20476. effect.setMatrix("view", viewMatrix);
  20477. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20478. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20479. // Fog
  20480. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20481. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20482. effect.setColor3("vFogColor", this._scene.fogColor);
  20483. }
  20484. // VBOs
  20485. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20486. // Draw order
  20487. engine.setDepthFunctionToLessOrEqual();
  20488. effect.setBool("alphaTest", true);
  20489. engine.setColorWrite(false);
  20490. engine.draw(true, 0, max * 6);
  20491. engine.setColorWrite(true);
  20492. effect.setBool("alphaTest", false);
  20493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20494. engine.draw(true, 0, max * 6);
  20495. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20496. };
  20497. SpriteManager.prototype.dispose = function () {
  20498. if (this._vertexBuffer) {
  20499. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20500. this._vertexBuffer = null;
  20501. }
  20502. if (this._indexBuffer) {
  20503. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20504. this._indexBuffer = null;
  20505. }
  20506. if (this._spriteTexture) {
  20507. this._spriteTexture.dispose();
  20508. this._spriteTexture = null;
  20509. }
  20510. // Remove from scene
  20511. var index = this._scene.spriteManagers.indexOf(this);
  20512. this._scene.spriteManagers.splice(index, 1);
  20513. // Callback
  20514. if (this.onDispose) {
  20515. this.onDispose();
  20516. }
  20517. };
  20518. return SpriteManager;
  20519. })();
  20520. BABYLON.SpriteManager = SpriteManager;
  20521. })(BABYLON || (BABYLON = {}));
  20522. var BABYLON;
  20523. (function (BABYLON) {
  20524. var Sprite = (function () {
  20525. function Sprite(name, manager) {
  20526. this.name = name;
  20527. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20528. this.width = 1.0;
  20529. this.height = 1.0;
  20530. this.angle = 0;
  20531. this.cellIndex = 0;
  20532. this.invertU = 0;
  20533. this.invertV = 0;
  20534. this.animations = new Array();
  20535. this.isPickable = false;
  20536. this._animationStarted = false;
  20537. this._loopAnimation = false;
  20538. this._fromIndex = 0;
  20539. this._toIndex = 0;
  20540. this._delay = 0;
  20541. this._direction = 1;
  20542. this._frameCount = 0;
  20543. this._time = 0;
  20544. this._manager = manager;
  20545. this._manager.sprites.push(this);
  20546. this.position = BABYLON.Vector3.Zero();
  20547. }
  20548. Object.defineProperty(Sprite.prototype, "size", {
  20549. get: function () {
  20550. return this.width;
  20551. },
  20552. set: function (value) {
  20553. this.width = value;
  20554. this.height = value;
  20555. },
  20556. enumerable: true,
  20557. configurable: true
  20558. });
  20559. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20560. this._fromIndex = from;
  20561. this._toIndex = to;
  20562. this._loopAnimation = loop;
  20563. this._delay = delay;
  20564. this._animationStarted = true;
  20565. this._direction = from < to ? 1 : -1;
  20566. this.cellIndex = from;
  20567. this._time = 0;
  20568. };
  20569. Sprite.prototype.stopAnimation = function () {
  20570. this._animationStarted = false;
  20571. };
  20572. Sprite.prototype._animate = function (deltaTime) {
  20573. if (!this._animationStarted)
  20574. return;
  20575. this._time += deltaTime;
  20576. if (this._time > this._delay) {
  20577. this._time = this._time % this._delay;
  20578. this.cellIndex += this._direction;
  20579. if (this.cellIndex == this._toIndex) {
  20580. if (this._loopAnimation) {
  20581. this.cellIndex = this._fromIndex;
  20582. }
  20583. else {
  20584. this._animationStarted = false;
  20585. if (this.disposeWhenFinishedAnimating) {
  20586. this.dispose();
  20587. }
  20588. }
  20589. }
  20590. }
  20591. };
  20592. Sprite.prototype.dispose = function () {
  20593. for (var i = 0; i < this._manager.sprites.length; i++) {
  20594. if (this._manager.sprites[i] == this) {
  20595. this._manager.sprites.splice(i, 1);
  20596. }
  20597. }
  20598. };
  20599. return Sprite;
  20600. })();
  20601. BABYLON.Sprite = Sprite;
  20602. })(BABYLON || (BABYLON = {}));
  20603. var BABYLON;
  20604. (function (BABYLON) {
  20605. var Layer = (function () {
  20606. function Layer(name, imgUrl, scene, isBackground, color) {
  20607. this.name = name;
  20608. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20609. this._vertexDeclaration = [2];
  20610. this._vertexStrideSize = 2 * 4;
  20611. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20612. this.isBackground = isBackground === undefined ? true : isBackground;
  20613. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20614. this._scene = scene;
  20615. this._scene.layers.push(this);
  20616. // VBO
  20617. var vertices = [];
  20618. vertices.push(1, 1);
  20619. vertices.push(-1, 1);
  20620. vertices.push(-1, -1);
  20621. vertices.push(1, -1);
  20622. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20623. // Indices
  20624. var indices = [];
  20625. indices.push(0);
  20626. indices.push(1);
  20627. indices.push(2);
  20628. indices.push(0);
  20629. indices.push(2);
  20630. indices.push(3);
  20631. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20632. // Effects
  20633. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20634. }
  20635. Layer.prototype.render = function () {
  20636. // Check
  20637. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20638. return;
  20639. var engine = this._scene.getEngine();
  20640. // Render
  20641. engine.enableEffect(this._effect);
  20642. engine.setState(false);
  20643. // Texture
  20644. this._effect.setTexture("textureSampler", this.texture);
  20645. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20646. // Color
  20647. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20648. // VBOs
  20649. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20650. // Draw order
  20651. engine.setAlphaMode(this.alphaBlendingMode);
  20652. engine.draw(true, 0, 6);
  20653. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20654. };
  20655. Layer.prototype.dispose = function () {
  20656. if (this._vertexBuffer) {
  20657. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20658. this._vertexBuffer = null;
  20659. }
  20660. if (this._indexBuffer) {
  20661. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20662. this._indexBuffer = null;
  20663. }
  20664. if (this.texture) {
  20665. this.texture.dispose();
  20666. this.texture = null;
  20667. }
  20668. // Remove from scene
  20669. var index = this._scene.layers.indexOf(this);
  20670. this._scene.layers.splice(index, 1);
  20671. // Callback
  20672. if (this.onDispose) {
  20673. this.onDispose();
  20674. }
  20675. };
  20676. return Layer;
  20677. })();
  20678. BABYLON.Layer = Layer;
  20679. })(BABYLON || (BABYLON = {}));
  20680. var BABYLON;
  20681. (function (BABYLON) {
  20682. var Particle = (function () {
  20683. function Particle() {
  20684. this.position = BABYLON.Vector3.Zero();
  20685. this.direction = BABYLON.Vector3.Zero();
  20686. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20687. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20688. this.lifeTime = 1.0;
  20689. this.age = 0;
  20690. this.size = 0;
  20691. this.angle = 0;
  20692. this.angularSpeed = 0;
  20693. }
  20694. Particle.prototype.copyTo = function (other) {
  20695. other.position.copyFrom(this.position);
  20696. other.direction.copyFrom(this.direction);
  20697. other.color.copyFrom(this.color);
  20698. other.colorStep.copyFrom(this.colorStep);
  20699. other.lifeTime = this.lifeTime;
  20700. other.age = this.age;
  20701. other.size = this.size;
  20702. other.angle = this.angle;
  20703. other.angularSpeed = this.angularSpeed;
  20704. };
  20705. return Particle;
  20706. })();
  20707. BABYLON.Particle = Particle;
  20708. })(BABYLON || (BABYLON = {}));
  20709. var BABYLON;
  20710. (function (BABYLON) {
  20711. var randomNumber = function (min, max) {
  20712. if (min === max) {
  20713. return (min);
  20714. }
  20715. var random = Math.random();
  20716. return ((random * (max - min)) + min);
  20717. };
  20718. var ParticleSystem = (function () {
  20719. function ParticleSystem(name, capacity, scene, customEffect) {
  20720. var _this = this;
  20721. this.name = name;
  20722. this.renderingGroupId = 0;
  20723. this.emitter = null;
  20724. this.emitRate = 10;
  20725. this.manualEmitCount = -1;
  20726. this.updateSpeed = 0.01;
  20727. this.targetStopDuration = 0;
  20728. this.disposeOnStop = false;
  20729. this.minEmitPower = 1;
  20730. this.maxEmitPower = 1;
  20731. this.minLifeTime = 1;
  20732. this.maxLifeTime = 1;
  20733. this.minSize = 1;
  20734. this.maxSize = 1;
  20735. this.minAngularSpeed = 0;
  20736. this.maxAngularSpeed = 0;
  20737. this.layerMask = 0x0FFFFFFF;
  20738. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20739. this.forceDepthWrite = false;
  20740. this.gravity = BABYLON.Vector3.Zero();
  20741. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20742. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20743. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20744. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20745. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20746. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20747. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20748. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20749. this.particles = new Array();
  20750. this._vertexDeclaration = [3, 4, 4];
  20751. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20752. this._stockParticles = new Array();
  20753. this._newPartsExcess = 0;
  20754. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20755. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20756. this._scaledDirection = BABYLON.Vector3.Zero();
  20757. this._scaledGravity = BABYLON.Vector3.Zero();
  20758. this._currentRenderId = -1;
  20759. this._started = false;
  20760. this._stopped = false;
  20761. this._actualFrame = 0;
  20762. this.id = name;
  20763. this._capacity = capacity;
  20764. this._scene = scene;
  20765. this._customEffect = customEffect;
  20766. scene.particleSystems.push(this);
  20767. // VBO
  20768. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20769. var indices = [];
  20770. var index = 0;
  20771. for (var count = 0; count < capacity; count++) {
  20772. indices.push(index);
  20773. indices.push(index + 1);
  20774. indices.push(index + 2);
  20775. indices.push(index);
  20776. indices.push(index + 2);
  20777. indices.push(index + 3);
  20778. index += 4;
  20779. }
  20780. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20781. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20782. // Default behaviors
  20783. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20784. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20785. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20786. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20787. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20788. };
  20789. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20790. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20791. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20792. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20793. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20794. };
  20795. this.updateFunction = function (particles) {
  20796. for (var index = 0; index < particles.length; index++) {
  20797. var particle = particles[index];
  20798. particle.age += _this._scaledUpdateSpeed;
  20799. if (particle.age >= particle.lifeTime) {
  20800. _this.recycleParticle(particle);
  20801. index--;
  20802. continue;
  20803. }
  20804. else {
  20805. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20806. particle.color.addInPlace(_this._scaledColorStep);
  20807. if (particle.color.a < 0)
  20808. particle.color.a = 0;
  20809. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20810. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20811. particle.position.addInPlace(_this._scaledDirection);
  20812. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20813. particle.direction.addInPlace(_this._scaledGravity);
  20814. }
  20815. }
  20816. };
  20817. }
  20818. ParticleSystem.prototype.recycleParticle = function (particle) {
  20819. var lastParticle = this.particles.pop();
  20820. if (lastParticle !== particle) {
  20821. lastParticle.copyTo(particle);
  20822. this._stockParticles.push(lastParticle);
  20823. }
  20824. };
  20825. ParticleSystem.prototype.getCapacity = function () {
  20826. return this._capacity;
  20827. };
  20828. ParticleSystem.prototype.isAlive = function () {
  20829. return this._alive;
  20830. };
  20831. ParticleSystem.prototype.isStarted = function () {
  20832. return this._started;
  20833. };
  20834. ParticleSystem.prototype.start = function () {
  20835. this._started = true;
  20836. this._stopped = false;
  20837. this._actualFrame = 0;
  20838. };
  20839. ParticleSystem.prototype.stop = function () {
  20840. this._stopped = true;
  20841. };
  20842. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20843. var offset = index * 11;
  20844. this._vertices[offset] = particle.position.x;
  20845. this._vertices[offset + 1] = particle.position.y;
  20846. this._vertices[offset + 2] = particle.position.z;
  20847. this._vertices[offset + 3] = particle.color.r;
  20848. this._vertices[offset + 4] = particle.color.g;
  20849. this._vertices[offset + 5] = particle.color.b;
  20850. this._vertices[offset + 6] = particle.color.a;
  20851. this._vertices[offset + 7] = particle.angle;
  20852. this._vertices[offset + 8] = particle.size;
  20853. this._vertices[offset + 9] = offsetX;
  20854. this._vertices[offset + 10] = offsetY;
  20855. };
  20856. ParticleSystem.prototype._update = function (newParticles) {
  20857. // Update current
  20858. this._alive = this.particles.length > 0;
  20859. this.updateFunction(this.particles);
  20860. // Add new ones
  20861. var worldMatrix;
  20862. if (this.emitter.position) {
  20863. worldMatrix = this.emitter.getWorldMatrix();
  20864. }
  20865. else {
  20866. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20867. }
  20868. var particle;
  20869. for (var index = 0; index < newParticles; index++) {
  20870. if (this.particles.length === this._capacity) {
  20871. break;
  20872. }
  20873. if (this._stockParticles.length !== 0) {
  20874. particle = this._stockParticles.pop();
  20875. particle.age = 0;
  20876. }
  20877. else {
  20878. particle = new BABYLON.Particle();
  20879. }
  20880. this.particles.push(particle);
  20881. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20882. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  20883. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20884. particle.size = randomNumber(this.minSize, this.maxSize);
  20885. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20886. this.startPositionFunction(worldMatrix, particle.position, particle);
  20887. var step = randomNumber(0, 1.0);
  20888. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20889. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20890. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20891. }
  20892. };
  20893. ParticleSystem.prototype._getEffect = function () {
  20894. if (this._customEffect) {
  20895. return this._customEffect;
  20896. }
  20897. ;
  20898. var defines = [];
  20899. if (this._scene.clipPlane) {
  20900. defines.push("#define CLIPPLANE");
  20901. }
  20902. // Effect
  20903. var join = defines.join("\n");
  20904. if (this._cachedDefines !== join) {
  20905. this._cachedDefines = join;
  20906. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20907. }
  20908. return this._effect;
  20909. };
  20910. ParticleSystem.prototype.animate = function () {
  20911. if (!this._started)
  20912. return;
  20913. var effect = this._getEffect();
  20914. // Check
  20915. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20916. return;
  20917. if (this._currentRenderId === this._scene.getRenderId()) {
  20918. return;
  20919. }
  20920. this._currentRenderId = this._scene.getRenderId();
  20921. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20922. // determine the number of particles we need to create
  20923. var emitCout;
  20924. if (this.manualEmitCount > -1) {
  20925. emitCout = this.manualEmitCount;
  20926. this.manualEmitCount = 0;
  20927. }
  20928. else {
  20929. emitCout = this.emitRate;
  20930. }
  20931. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20932. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20933. if (this._newPartsExcess > 1.0) {
  20934. newParticles += this._newPartsExcess >> 0;
  20935. this._newPartsExcess -= this._newPartsExcess >> 0;
  20936. }
  20937. this._alive = false;
  20938. if (!this._stopped) {
  20939. this._actualFrame += this._scaledUpdateSpeed;
  20940. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20941. this.stop();
  20942. }
  20943. else {
  20944. newParticles = 0;
  20945. }
  20946. this._update(newParticles);
  20947. // Stopped?
  20948. if (this._stopped) {
  20949. if (!this._alive) {
  20950. this._started = false;
  20951. if (this.disposeOnStop) {
  20952. this._scene._toBeDisposed.push(this);
  20953. }
  20954. }
  20955. }
  20956. // Update VBO
  20957. var offset = 0;
  20958. for (var index = 0; index < this.particles.length; index++) {
  20959. var particle = this.particles[index];
  20960. this._appendParticleVertex(offset++, particle, 0, 0);
  20961. this._appendParticleVertex(offset++, particle, 1, 0);
  20962. this._appendParticleVertex(offset++, particle, 1, 1);
  20963. this._appendParticleVertex(offset++, particle, 0, 1);
  20964. }
  20965. var engine = this._scene.getEngine();
  20966. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20967. };
  20968. ParticleSystem.prototype.render = function () {
  20969. var effect = this._getEffect();
  20970. // Check
  20971. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20972. return 0;
  20973. var engine = this._scene.getEngine();
  20974. // Render
  20975. engine.enableEffect(effect);
  20976. engine.setState(false);
  20977. var viewMatrix = this._scene.getViewMatrix();
  20978. effect.setTexture("diffuseSampler", this.particleTexture);
  20979. effect.setMatrix("view", viewMatrix);
  20980. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20981. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20982. if (this._scene.clipPlane) {
  20983. var clipPlane = this._scene.clipPlane;
  20984. var invView = viewMatrix.clone();
  20985. invView.invert();
  20986. effect.setMatrix("invView", invView);
  20987. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20988. }
  20989. // VBOs
  20990. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20991. // Draw order
  20992. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20993. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  20994. }
  20995. else {
  20996. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20997. }
  20998. if (this.forceDepthWrite) {
  20999. engine.setDepthWrite(true);
  21000. }
  21001. engine.draw(true, 0, this.particles.length * 6);
  21002. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21003. return this.particles.length;
  21004. };
  21005. ParticleSystem.prototype.dispose = function () {
  21006. if (this._vertexBuffer) {
  21007. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21008. this._vertexBuffer = null;
  21009. }
  21010. if (this._indexBuffer) {
  21011. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21012. this._indexBuffer = null;
  21013. }
  21014. if (this.particleTexture) {
  21015. this.particleTexture.dispose();
  21016. this.particleTexture = null;
  21017. }
  21018. // Remove from scene
  21019. var index = this._scene.particleSystems.indexOf(this);
  21020. this._scene.particleSystems.splice(index, 1);
  21021. // Callback
  21022. if (this.onDispose) {
  21023. this.onDispose();
  21024. }
  21025. };
  21026. // Clone
  21027. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21028. var result = new ParticleSystem(name, this._capacity, this._scene);
  21029. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21030. if (newEmitter === undefined) {
  21031. newEmitter = this.emitter;
  21032. }
  21033. result.emitter = newEmitter;
  21034. if (this.particleTexture) {
  21035. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21036. }
  21037. result.start();
  21038. return result;
  21039. };
  21040. ParticleSystem.prototype.serialize = function () {
  21041. var serializationObject = {};
  21042. serializationObject.name = this.name;
  21043. if (this.emitter.position) {
  21044. serializationObject.emitterId = this.emitter.id;
  21045. }
  21046. else {
  21047. serializationObject.emitter = this.emitter.asArray();
  21048. ;
  21049. }
  21050. serializationObject.capacity = this.getCapacity();
  21051. if (this.particleTexture) {
  21052. serializationObject.textureName = this.particleTexture.name;
  21053. }
  21054. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21055. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21056. serializationObject.minSize = this.minSize;
  21057. serializationObject.maxSize = this.maxSize;
  21058. serializationObject.minEmitPower = this.minEmitPower;
  21059. serializationObject.maxEmitPower = this.maxEmitPower;
  21060. serializationObject.minLifeTime = this.minLifeTime;
  21061. serializationObject.maxLifeTime = this.maxLifeTime;
  21062. serializationObject.emitRate = this.emitRate;
  21063. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21064. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21065. serializationObject.gravity = this.gravity.asArray();
  21066. serializationObject.direction1 = this.direction1.asArray();
  21067. serializationObject.direction2 = this.direction2.asArray();
  21068. serializationObject.color1 = this.color1.asArray();
  21069. serializationObject.color2 = this.color2.asArray();
  21070. serializationObject.colorDead = this.colorDead.asArray();
  21071. serializationObject.updateSpeed = this.updateSpeed;
  21072. serializationObject.targetStopDuration = this.targetStopDuration;
  21073. serializationObject.textureMask = this.textureMask.asArray();
  21074. serializationObject.blendMode = this.blendMode;
  21075. return serializationObject;
  21076. };
  21077. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21078. var name = parsedParticleSystem.name;
  21079. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21080. if (parsedParticleSystem.textureName) {
  21081. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21082. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21083. }
  21084. if (parsedParticleSystem.emitterId) {
  21085. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21086. }
  21087. else {
  21088. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21089. }
  21090. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21091. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21092. particleSystem.minSize = parsedParticleSystem.minSize;
  21093. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21094. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21095. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21096. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21097. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21098. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21099. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21100. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21101. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21102. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21103. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21104. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21105. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21106. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21107. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21108. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21109. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21110. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21111. particleSystem.start();
  21112. return particleSystem;
  21113. };
  21114. // Statics
  21115. ParticleSystem.BLENDMODE_ONEONE = 0;
  21116. ParticleSystem.BLENDMODE_STANDARD = 1;
  21117. return ParticleSystem;
  21118. })();
  21119. BABYLON.ParticleSystem = ParticleSystem;
  21120. })(BABYLON || (BABYLON = {}));
  21121. var BABYLON;
  21122. (function (BABYLON) {
  21123. var AnimationRange = (function () {
  21124. function AnimationRange(name, from, to) {
  21125. this.name = name;
  21126. this.from = from;
  21127. this.to = to;
  21128. }
  21129. return AnimationRange;
  21130. })();
  21131. BABYLON.AnimationRange = AnimationRange;
  21132. /**
  21133. * Composed of a frame, and an action function
  21134. */
  21135. var AnimationEvent = (function () {
  21136. function AnimationEvent(frame, action, onlyOnce) {
  21137. this.frame = frame;
  21138. this.action = action;
  21139. this.onlyOnce = onlyOnce;
  21140. this.isDone = false;
  21141. }
  21142. return AnimationEvent;
  21143. })();
  21144. BABYLON.AnimationEvent = AnimationEvent;
  21145. var Animation = (function () {
  21146. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21147. this.name = name;
  21148. this.targetProperty = targetProperty;
  21149. this.framePerSecond = framePerSecond;
  21150. this.dataType = dataType;
  21151. this.loopMode = loopMode;
  21152. this._offsetsCache = {};
  21153. this._highLimitsCache = {};
  21154. this._stopped = false;
  21155. // The set of event that will be linked to this animation
  21156. this._events = new Array();
  21157. this.allowMatricesInterpolation = false;
  21158. this._ranges = new Array();
  21159. this.targetPropertyPath = targetProperty.split(".");
  21160. this.dataType = dataType;
  21161. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21162. }
  21163. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21164. var dataType = undefined;
  21165. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21166. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21167. }
  21168. else if (from instanceof BABYLON.Quaternion) {
  21169. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21170. }
  21171. else if (from instanceof BABYLON.Vector3) {
  21172. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21173. }
  21174. else if (from instanceof BABYLON.Vector2) {
  21175. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21176. }
  21177. else if (from instanceof BABYLON.Color3) {
  21178. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21179. }
  21180. if (dataType == undefined) {
  21181. return null;
  21182. }
  21183. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21184. var keys = [];
  21185. keys.push({ frame: 0, value: from });
  21186. keys.push({ frame: totalFrame, value: to });
  21187. animation.setKeys(keys);
  21188. if (easingFunction !== undefined) {
  21189. animation.setEasingFunction(easingFunction);
  21190. }
  21191. return animation;
  21192. };
  21193. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21194. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21195. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21196. };
  21197. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21198. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21199. node.animations.push(animation);
  21200. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21201. };
  21202. // Methods
  21203. /**
  21204. * Add an event to this animation.
  21205. */
  21206. Animation.prototype.addEvent = function (event) {
  21207. this._events.push(event);
  21208. };
  21209. /**
  21210. * Remove all events found at the given frame
  21211. * @param frame
  21212. */
  21213. Animation.prototype.removeEvents = function (frame) {
  21214. for (var index = 0; index < this._events.length; index++) {
  21215. if (this._events[index].frame === frame) {
  21216. this._events.splice(index, 1);
  21217. index--;
  21218. }
  21219. }
  21220. };
  21221. Animation.prototype.createRange = function (name, from, to) {
  21222. this._ranges.push(new AnimationRange(name, from, to));
  21223. };
  21224. Animation.prototype.deleteRange = function (name) {
  21225. for (var index = 0; index < this._ranges.length; index++) {
  21226. if (this._ranges[index].name === name) {
  21227. this._ranges.splice(index, 1);
  21228. return;
  21229. }
  21230. }
  21231. };
  21232. Animation.prototype.getRange = function (name) {
  21233. for (var index = 0; index < this._ranges.length; index++) {
  21234. if (this._ranges[index].name === name) {
  21235. return this._ranges[index];
  21236. }
  21237. }
  21238. return null;
  21239. };
  21240. Animation.prototype.reset = function () {
  21241. this._offsetsCache = {};
  21242. this._highLimitsCache = {};
  21243. this.currentFrame = 0;
  21244. };
  21245. Animation.prototype.isStopped = function () {
  21246. return this._stopped;
  21247. };
  21248. Animation.prototype.getKeys = function () {
  21249. return this._keys;
  21250. };
  21251. Animation.prototype.getEasingFunction = function () {
  21252. return this._easingFunction;
  21253. };
  21254. Animation.prototype.setEasingFunction = function (easingFunction) {
  21255. this._easingFunction = easingFunction;
  21256. };
  21257. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21258. return startValue + (endValue - startValue) * gradient;
  21259. };
  21260. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21261. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21262. };
  21263. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21264. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21265. };
  21266. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21267. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21268. };
  21269. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21270. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21271. };
  21272. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21273. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21274. };
  21275. Animation.prototype.clone = function () {
  21276. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21277. if (this._keys) {
  21278. clone.setKeys(this._keys);
  21279. }
  21280. return clone;
  21281. };
  21282. Animation.prototype.setKeys = function (values) {
  21283. this._keys = values.slice(0);
  21284. this._offsetsCache = {};
  21285. this._highLimitsCache = {};
  21286. };
  21287. Animation.prototype._getKeyValue = function (value) {
  21288. if (typeof value === "function") {
  21289. return value();
  21290. }
  21291. return value;
  21292. };
  21293. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21294. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21295. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21296. }
  21297. this.currentFrame = currentFrame;
  21298. // Try to get a hash to find the right key
  21299. 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));
  21300. if (this._keys[startKey].frame >= currentFrame) {
  21301. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21302. startKey--;
  21303. }
  21304. }
  21305. for (var key = startKey; key < this._keys.length; key++) {
  21306. if (this._keys[key + 1].frame >= currentFrame) {
  21307. var startValue = this._getKeyValue(this._keys[key].value);
  21308. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21309. // gradient : percent of currentFrame between the frame inf and the frame sup
  21310. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21311. // check for easingFunction and correction of gradient
  21312. if (this._easingFunction != null) {
  21313. gradient = this._easingFunction.ease(gradient);
  21314. }
  21315. switch (this.dataType) {
  21316. // Float
  21317. case Animation.ANIMATIONTYPE_FLOAT:
  21318. switch (loopMode) {
  21319. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21320. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21321. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21322. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21323. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21324. }
  21325. break;
  21326. // Quaternion
  21327. case Animation.ANIMATIONTYPE_QUATERNION:
  21328. var quaternion = null;
  21329. switch (loopMode) {
  21330. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21331. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21332. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21333. break;
  21334. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21335. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21336. break;
  21337. }
  21338. return quaternion;
  21339. // Vector3
  21340. case Animation.ANIMATIONTYPE_VECTOR3:
  21341. switch (loopMode) {
  21342. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21343. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21344. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21345. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21346. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21347. }
  21348. // Vector2
  21349. case Animation.ANIMATIONTYPE_VECTOR2:
  21350. switch (loopMode) {
  21351. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21352. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21353. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21354. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21355. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21356. }
  21357. // Color3
  21358. case Animation.ANIMATIONTYPE_COLOR3:
  21359. switch (loopMode) {
  21360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21362. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21363. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21364. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21365. }
  21366. // Matrix
  21367. case Animation.ANIMATIONTYPE_MATRIX:
  21368. switch (loopMode) {
  21369. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21370. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21371. if (this.allowMatricesInterpolation) {
  21372. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21373. }
  21374. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21375. return startValue;
  21376. }
  21377. default:
  21378. break;
  21379. }
  21380. break;
  21381. }
  21382. }
  21383. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21384. };
  21385. Animation.prototype.setValue = function (currentValue) {
  21386. // Set value
  21387. if (this.targetPropertyPath.length > 1) {
  21388. var property = this._target[this.targetPropertyPath[0]];
  21389. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21390. property = property[this.targetPropertyPath[index]];
  21391. }
  21392. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21393. }
  21394. else {
  21395. this._target[this.targetPropertyPath[0]] = currentValue;
  21396. }
  21397. if (this._target.markAsDirty) {
  21398. this._target.markAsDirty(this.targetProperty);
  21399. }
  21400. };
  21401. Animation.prototype.goToFrame = function (frame) {
  21402. if (frame < this._keys[0].frame) {
  21403. frame = this._keys[0].frame;
  21404. }
  21405. else if (frame > this._keys[this._keys.length - 1].frame) {
  21406. frame = this._keys[this._keys.length - 1].frame;
  21407. }
  21408. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21409. this.setValue(currentValue);
  21410. };
  21411. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21412. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21413. this._stopped = true;
  21414. return false;
  21415. }
  21416. var returnValue = true;
  21417. // Adding a start key at frame 0 if missing
  21418. if (this._keys[0].frame !== 0) {
  21419. var newKey = { frame: 0, value: this._keys[0].value };
  21420. this._keys.splice(0, 0, newKey);
  21421. }
  21422. // Check limits
  21423. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21424. from = this._keys[0].frame;
  21425. }
  21426. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21427. to = this._keys[this._keys.length - 1].frame;
  21428. }
  21429. // Compute ratio
  21430. var range = to - from;
  21431. var offsetValue;
  21432. // ratio represents the frame delta between from and to
  21433. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21434. var highLimitValue = 0;
  21435. if (ratio > range && !loop) {
  21436. returnValue = false;
  21437. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21438. }
  21439. else {
  21440. // Get max value if required
  21441. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21442. var keyOffset = to.toString() + from.toString();
  21443. if (!this._offsetsCache[keyOffset]) {
  21444. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21445. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21446. switch (this.dataType) {
  21447. // Float
  21448. case Animation.ANIMATIONTYPE_FLOAT:
  21449. this._offsetsCache[keyOffset] = toValue - fromValue;
  21450. break;
  21451. // Quaternion
  21452. case Animation.ANIMATIONTYPE_QUATERNION:
  21453. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21454. break;
  21455. // Vector3
  21456. case Animation.ANIMATIONTYPE_VECTOR3:
  21457. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21458. // Vector2
  21459. case Animation.ANIMATIONTYPE_VECTOR2:
  21460. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21461. // Color3
  21462. case Animation.ANIMATIONTYPE_COLOR3:
  21463. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21464. default:
  21465. break;
  21466. }
  21467. this._highLimitsCache[keyOffset] = toValue;
  21468. }
  21469. highLimitValue = this._highLimitsCache[keyOffset];
  21470. offsetValue = this._offsetsCache[keyOffset];
  21471. }
  21472. }
  21473. if (offsetValue === undefined) {
  21474. switch (this.dataType) {
  21475. // Float
  21476. case Animation.ANIMATIONTYPE_FLOAT:
  21477. offsetValue = 0;
  21478. break;
  21479. // Quaternion
  21480. case Animation.ANIMATIONTYPE_QUATERNION:
  21481. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21482. break;
  21483. // Vector3
  21484. case Animation.ANIMATIONTYPE_VECTOR3:
  21485. offsetValue = BABYLON.Vector3.Zero();
  21486. break;
  21487. // Vector2
  21488. case Animation.ANIMATIONTYPE_VECTOR2:
  21489. offsetValue = BABYLON.Vector2.Zero();
  21490. break;
  21491. // Color3
  21492. case Animation.ANIMATIONTYPE_COLOR3:
  21493. offsetValue = BABYLON.Color3.Black();
  21494. }
  21495. }
  21496. // Compute value
  21497. var repeatCount = (ratio / range) >> 0;
  21498. var currentFrame = returnValue ? from + ratio % range : to;
  21499. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21500. // Check events
  21501. for (var index = 0; index < this._events.length; index++) {
  21502. if (currentFrame >= this._events[index].frame) {
  21503. var event = this._events[index];
  21504. if (!event.isDone) {
  21505. // If event should be done only once, remove it.
  21506. if (event.onlyOnce) {
  21507. this._events.splice(index, 1);
  21508. index--;
  21509. }
  21510. event.isDone = true;
  21511. event.action();
  21512. } // Don't do anything if the event has already be done.
  21513. }
  21514. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21515. // reset event, the animation is looping
  21516. this._events[index].isDone = false;
  21517. }
  21518. }
  21519. // Set value
  21520. this.setValue(currentValue);
  21521. if (!returnValue) {
  21522. this._stopped = true;
  21523. }
  21524. return returnValue;
  21525. };
  21526. Animation.prototype.serialize = function () {
  21527. var serializationObject = {};
  21528. serializationObject.name = this.name;
  21529. serializationObject.property = this.targetProperty;
  21530. serializationObject.framePerSecond = this.framePerSecond;
  21531. serializationObject.dataType = this.dataType;
  21532. serializationObject.loopBehavior = this.loopMode;
  21533. var dataType = this.dataType;
  21534. serializationObject.keys = [];
  21535. var keys = this.getKeys();
  21536. for (var index = 0; index < keys.length; index++) {
  21537. var animationKey = keys[index];
  21538. var key = {};
  21539. key.frame = animationKey.frame;
  21540. switch (dataType) {
  21541. case Animation.ANIMATIONTYPE_FLOAT:
  21542. key.values = [animationKey.value];
  21543. break;
  21544. case Animation.ANIMATIONTYPE_QUATERNION:
  21545. case Animation.ANIMATIONTYPE_MATRIX:
  21546. case Animation.ANIMATIONTYPE_VECTOR3:
  21547. key.values = animationKey.value.asArray();
  21548. break;
  21549. }
  21550. serializationObject.keys.push(key);
  21551. }
  21552. return serializationObject;
  21553. };
  21554. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21555. get: function () {
  21556. return Animation._ANIMATIONTYPE_FLOAT;
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21562. get: function () {
  21563. return Animation._ANIMATIONTYPE_VECTOR3;
  21564. },
  21565. enumerable: true,
  21566. configurable: true
  21567. });
  21568. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21569. get: function () {
  21570. return Animation._ANIMATIONTYPE_VECTOR2;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21576. get: function () {
  21577. return Animation._ANIMATIONTYPE_QUATERNION;
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21583. get: function () {
  21584. return Animation._ANIMATIONTYPE_MATRIX;
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21590. get: function () {
  21591. return Animation._ANIMATIONTYPE_COLOR3;
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21597. get: function () {
  21598. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21604. get: function () {
  21605. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21606. },
  21607. enumerable: true,
  21608. configurable: true
  21609. });
  21610. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21611. get: function () {
  21612. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Animation.Parse = function (parsedAnimation) {
  21618. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21619. var dataType = parsedAnimation.dataType;
  21620. var keys = [];
  21621. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21622. var key = parsedAnimation.keys[index];
  21623. var data;
  21624. switch (dataType) {
  21625. case Animation.ANIMATIONTYPE_FLOAT:
  21626. data = key.values[0];
  21627. break;
  21628. case Animation.ANIMATIONTYPE_QUATERNION:
  21629. data = BABYLON.Quaternion.FromArray(key.values);
  21630. break;
  21631. case Animation.ANIMATIONTYPE_MATRIX:
  21632. data = BABYLON.Matrix.FromArray(key.values);
  21633. break;
  21634. case Animation.ANIMATIONTYPE_VECTOR3:
  21635. default:
  21636. data = BABYLON.Vector3.FromArray(key.values);
  21637. break;
  21638. }
  21639. keys.push({
  21640. frame: key.frame,
  21641. value: data
  21642. });
  21643. }
  21644. animation.setKeys(keys);
  21645. return animation;
  21646. };
  21647. Animation.AppendSerializedAnimations = function (source, destination) {
  21648. if (source.animations) {
  21649. destination.animations = [];
  21650. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21651. var animation = source.animations[animationIndex];
  21652. destination.animations.push(animation.serialize());
  21653. }
  21654. }
  21655. };
  21656. // Statics
  21657. Animation._ANIMATIONTYPE_FLOAT = 0;
  21658. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21659. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21660. Animation._ANIMATIONTYPE_MATRIX = 3;
  21661. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21662. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21663. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21664. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21665. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21666. return Animation;
  21667. })();
  21668. BABYLON.Animation = Animation;
  21669. })(BABYLON || (BABYLON = {}));
  21670. var BABYLON;
  21671. (function (BABYLON) {
  21672. var Animatable = (function () {
  21673. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21674. if (fromFrame === void 0) { fromFrame = 0; }
  21675. if (toFrame === void 0) { toFrame = 100; }
  21676. if (loopAnimation === void 0) { loopAnimation = false; }
  21677. if (speedRatio === void 0) { speedRatio = 1.0; }
  21678. this.target = target;
  21679. this.fromFrame = fromFrame;
  21680. this.toFrame = toFrame;
  21681. this.loopAnimation = loopAnimation;
  21682. this.speedRatio = speedRatio;
  21683. this.onAnimationEnd = onAnimationEnd;
  21684. this._animations = new Array();
  21685. this._paused = false;
  21686. this.animationStarted = false;
  21687. if (animations) {
  21688. this.appendAnimations(target, animations);
  21689. }
  21690. this._scene = scene;
  21691. scene._activeAnimatables.push(this);
  21692. }
  21693. // Methods
  21694. Animatable.prototype.getAnimations = function () {
  21695. return this._animations;
  21696. };
  21697. Animatable.prototype.appendAnimations = function (target, animations) {
  21698. for (var index = 0; index < animations.length; index++) {
  21699. var animation = animations[index];
  21700. animation._target = target;
  21701. this._animations.push(animation);
  21702. }
  21703. };
  21704. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21705. var animations = this._animations;
  21706. for (var index = 0; index < animations.length; index++) {
  21707. if (animations[index].targetProperty === property) {
  21708. return animations[index];
  21709. }
  21710. }
  21711. return null;
  21712. };
  21713. Animatable.prototype.reset = function () {
  21714. var animations = this._animations;
  21715. for (var index = 0; index < animations.length; index++) {
  21716. animations[index].reset();
  21717. }
  21718. this._localDelayOffset = null;
  21719. this._pausedDelay = null;
  21720. };
  21721. Animatable.prototype.goToFrame = function (frame) {
  21722. var animations = this._animations;
  21723. for (var index = 0; index < animations.length; index++) {
  21724. animations[index].goToFrame(frame);
  21725. }
  21726. };
  21727. Animatable.prototype.pause = function () {
  21728. if (this._paused) {
  21729. return;
  21730. }
  21731. this._paused = true;
  21732. };
  21733. Animatable.prototype.restart = function () {
  21734. this._paused = false;
  21735. };
  21736. Animatable.prototype.stop = function () {
  21737. var index = this._scene._activeAnimatables.indexOf(this);
  21738. if (index > -1) {
  21739. this._scene._activeAnimatables.splice(index, 1);
  21740. }
  21741. if (this.onAnimationEnd) {
  21742. this.onAnimationEnd();
  21743. }
  21744. };
  21745. Animatable.prototype._animate = function (delay) {
  21746. if (this._paused) {
  21747. this.animationStarted = false;
  21748. if (!this._pausedDelay) {
  21749. this._pausedDelay = delay;
  21750. }
  21751. return true;
  21752. }
  21753. if (!this._localDelayOffset) {
  21754. this._localDelayOffset = delay;
  21755. }
  21756. else if (this._pausedDelay) {
  21757. this._localDelayOffset += delay - this._pausedDelay;
  21758. this._pausedDelay = null;
  21759. }
  21760. // Animating
  21761. var running = false;
  21762. var animations = this._animations;
  21763. var index;
  21764. for (index = 0; index < animations.length; index++) {
  21765. var animation = animations[index];
  21766. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21767. running = running || isRunning;
  21768. }
  21769. this.animationStarted = running;
  21770. if (!running) {
  21771. // Remove from active animatables
  21772. index = this._scene._activeAnimatables.indexOf(this);
  21773. this._scene._activeAnimatables.splice(index, 1);
  21774. }
  21775. if (!running && this.onAnimationEnd) {
  21776. this.onAnimationEnd();
  21777. }
  21778. return running;
  21779. };
  21780. return Animatable;
  21781. })();
  21782. BABYLON.Animatable = Animatable;
  21783. })(BABYLON || (BABYLON = {}));
  21784. var BABYLON;
  21785. (function (BABYLON) {
  21786. var EasingFunction = (function () {
  21787. function EasingFunction() {
  21788. // Properties
  21789. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21790. }
  21791. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21792. get: function () {
  21793. return EasingFunction._EASINGMODE_EASEIN;
  21794. },
  21795. enumerable: true,
  21796. configurable: true
  21797. });
  21798. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21799. get: function () {
  21800. return EasingFunction._EASINGMODE_EASEOUT;
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21806. get: function () {
  21807. return EasingFunction._EASINGMODE_EASEINOUT;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21813. var n = Math.min(Math.max(easingMode, 0), 2);
  21814. this._easingMode = n;
  21815. };
  21816. EasingFunction.prototype.getEasingMode = function () {
  21817. return this._easingMode;
  21818. };
  21819. EasingFunction.prototype.easeInCore = function (gradient) {
  21820. throw new Error('You must implement this method');
  21821. };
  21822. EasingFunction.prototype.ease = function (gradient) {
  21823. switch (this._easingMode) {
  21824. case EasingFunction.EASINGMODE_EASEIN:
  21825. return this.easeInCore(gradient);
  21826. case EasingFunction.EASINGMODE_EASEOUT:
  21827. return (1 - this.easeInCore(1 - gradient));
  21828. }
  21829. if (gradient >= 0.5) {
  21830. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21831. }
  21832. return (this.easeInCore(gradient * 2) * 0.5);
  21833. };
  21834. //Statics
  21835. EasingFunction._EASINGMODE_EASEIN = 0;
  21836. EasingFunction._EASINGMODE_EASEOUT = 1;
  21837. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21838. return EasingFunction;
  21839. })();
  21840. BABYLON.EasingFunction = EasingFunction;
  21841. var CircleEase = (function (_super) {
  21842. __extends(CircleEase, _super);
  21843. function CircleEase() {
  21844. _super.apply(this, arguments);
  21845. }
  21846. CircleEase.prototype.easeInCore = function (gradient) {
  21847. gradient = Math.max(0, Math.min(1, gradient));
  21848. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21849. };
  21850. return CircleEase;
  21851. })(EasingFunction);
  21852. BABYLON.CircleEase = CircleEase;
  21853. var BackEase = (function (_super) {
  21854. __extends(BackEase, _super);
  21855. function BackEase(amplitude) {
  21856. if (amplitude === void 0) { amplitude = 1; }
  21857. _super.call(this);
  21858. this.amplitude = amplitude;
  21859. }
  21860. BackEase.prototype.easeInCore = function (gradient) {
  21861. var num = Math.max(0, this.amplitude);
  21862. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21863. };
  21864. return BackEase;
  21865. })(EasingFunction);
  21866. BABYLON.BackEase = BackEase;
  21867. var BounceEase = (function (_super) {
  21868. __extends(BounceEase, _super);
  21869. function BounceEase(bounces, bounciness) {
  21870. if (bounces === void 0) { bounces = 3; }
  21871. if (bounciness === void 0) { bounciness = 2; }
  21872. _super.call(this);
  21873. this.bounces = bounces;
  21874. this.bounciness = bounciness;
  21875. }
  21876. BounceEase.prototype.easeInCore = function (gradient) {
  21877. var y = Math.max(0.0, this.bounces);
  21878. var bounciness = this.bounciness;
  21879. if (bounciness <= 1.0) {
  21880. bounciness = 1.001;
  21881. }
  21882. var num9 = Math.pow(bounciness, y);
  21883. var num5 = 1.0 - bounciness;
  21884. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21885. var num15 = gradient * num4;
  21886. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21887. var num3 = Math.floor(num65);
  21888. var num13 = num3 + 1.0;
  21889. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21890. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21891. var num7 = (num8 + num12) * 0.5;
  21892. var num6 = gradient - num7;
  21893. var num2 = num7 - num8;
  21894. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21895. };
  21896. return BounceEase;
  21897. })(EasingFunction);
  21898. BABYLON.BounceEase = BounceEase;
  21899. var CubicEase = (function (_super) {
  21900. __extends(CubicEase, _super);
  21901. function CubicEase() {
  21902. _super.apply(this, arguments);
  21903. }
  21904. CubicEase.prototype.easeInCore = function (gradient) {
  21905. return (gradient * gradient * gradient);
  21906. };
  21907. return CubicEase;
  21908. })(EasingFunction);
  21909. BABYLON.CubicEase = CubicEase;
  21910. var ElasticEase = (function (_super) {
  21911. __extends(ElasticEase, _super);
  21912. function ElasticEase(oscillations, springiness) {
  21913. if (oscillations === void 0) { oscillations = 3; }
  21914. if (springiness === void 0) { springiness = 3; }
  21915. _super.call(this);
  21916. this.oscillations = oscillations;
  21917. this.springiness = springiness;
  21918. }
  21919. ElasticEase.prototype.easeInCore = function (gradient) {
  21920. var num2;
  21921. var num3 = Math.max(0.0, this.oscillations);
  21922. var num = Math.max(0.0, this.springiness);
  21923. if (num == 0) {
  21924. num2 = gradient;
  21925. }
  21926. else {
  21927. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21928. }
  21929. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21930. };
  21931. return ElasticEase;
  21932. })(EasingFunction);
  21933. BABYLON.ElasticEase = ElasticEase;
  21934. var ExponentialEase = (function (_super) {
  21935. __extends(ExponentialEase, _super);
  21936. function ExponentialEase(exponent) {
  21937. if (exponent === void 0) { exponent = 2; }
  21938. _super.call(this);
  21939. this.exponent = exponent;
  21940. }
  21941. ExponentialEase.prototype.easeInCore = function (gradient) {
  21942. if (this.exponent <= 0) {
  21943. return gradient;
  21944. }
  21945. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21946. };
  21947. return ExponentialEase;
  21948. })(EasingFunction);
  21949. BABYLON.ExponentialEase = ExponentialEase;
  21950. var PowerEase = (function (_super) {
  21951. __extends(PowerEase, _super);
  21952. function PowerEase(power) {
  21953. if (power === void 0) { power = 2; }
  21954. _super.call(this);
  21955. this.power = power;
  21956. }
  21957. PowerEase.prototype.easeInCore = function (gradient) {
  21958. var y = Math.max(0.0, this.power);
  21959. return Math.pow(gradient, y);
  21960. };
  21961. return PowerEase;
  21962. })(EasingFunction);
  21963. BABYLON.PowerEase = PowerEase;
  21964. var QuadraticEase = (function (_super) {
  21965. __extends(QuadraticEase, _super);
  21966. function QuadraticEase() {
  21967. _super.apply(this, arguments);
  21968. }
  21969. QuadraticEase.prototype.easeInCore = function (gradient) {
  21970. return (gradient * gradient);
  21971. };
  21972. return QuadraticEase;
  21973. })(EasingFunction);
  21974. BABYLON.QuadraticEase = QuadraticEase;
  21975. var QuarticEase = (function (_super) {
  21976. __extends(QuarticEase, _super);
  21977. function QuarticEase() {
  21978. _super.apply(this, arguments);
  21979. }
  21980. QuarticEase.prototype.easeInCore = function (gradient) {
  21981. return (gradient * gradient * gradient * gradient);
  21982. };
  21983. return QuarticEase;
  21984. })(EasingFunction);
  21985. BABYLON.QuarticEase = QuarticEase;
  21986. var QuinticEase = (function (_super) {
  21987. __extends(QuinticEase, _super);
  21988. function QuinticEase() {
  21989. _super.apply(this, arguments);
  21990. }
  21991. QuinticEase.prototype.easeInCore = function (gradient) {
  21992. return (gradient * gradient * gradient * gradient * gradient);
  21993. };
  21994. return QuinticEase;
  21995. })(EasingFunction);
  21996. BABYLON.QuinticEase = QuinticEase;
  21997. var SineEase = (function (_super) {
  21998. __extends(SineEase, _super);
  21999. function SineEase() {
  22000. _super.apply(this, arguments);
  22001. }
  22002. SineEase.prototype.easeInCore = function (gradient) {
  22003. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22004. };
  22005. return SineEase;
  22006. })(EasingFunction);
  22007. BABYLON.SineEase = SineEase;
  22008. var BezierCurveEase = (function (_super) {
  22009. __extends(BezierCurveEase, _super);
  22010. function BezierCurveEase(x1, y1, x2, y2) {
  22011. if (x1 === void 0) { x1 = 0; }
  22012. if (y1 === void 0) { y1 = 0; }
  22013. if (x2 === void 0) { x2 = 1; }
  22014. if (y2 === void 0) { y2 = 1; }
  22015. _super.call(this);
  22016. this.x1 = x1;
  22017. this.y1 = y1;
  22018. this.x2 = x2;
  22019. this.y2 = y2;
  22020. }
  22021. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22022. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22023. };
  22024. return BezierCurveEase;
  22025. })(EasingFunction);
  22026. BABYLON.BezierCurveEase = BezierCurveEase;
  22027. })(BABYLON || (BABYLON = {}));
  22028. var BABYLON;
  22029. (function (BABYLON) {
  22030. var Bone = (function (_super) {
  22031. __extends(Bone, _super);
  22032. function Bone(name, skeleton, parentBone, matrix) {
  22033. _super.call(this, name, skeleton.getScene());
  22034. this.name = name;
  22035. this.children = new Array();
  22036. this.animations = new Array();
  22037. this._worldTransform = new BABYLON.Matrix();
  22038. this._absoluteTransform = new BABYLON.Matrix();
  22039. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22040. this._skeleton = skeleton;
  22041. this._matrix = matrix;
  22042. this._baseMatrix = matrix;
  22043. skeleton.bones.push(this);
  22044. if (parentBone) {
  22045. this._parent = parentBone;
  22046. parentBone.children.push(this);
  22047. }
  22048. else {
  22049. this._parent = null;
  22050. }
  22051. this._updateDifferenceMatrix();
  22052. }
  22053. // Members
  22054. Bone.prototype.getParent = function () {
  22055. return this._parent;
  22056. };
  22057. Bone.prototype.getLocalMatrix = function () {
  22058. return this._matrix;
  22059. };
  22060. Bone.prototype.getBaseMatrix = function () {
  22061. return this._baseMatrix;
  22062. };
  22063. Bone.prototype.getWorldMatrix = function () {
  22064. return this._worldTransform;
  22065. };
  22066. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22067. return this._invertedAbsoluteTransform;
  22068. };
  22069. Bone.prototype.getAbsoluteMatrix = function () {
  22070. var matrix = this._matrix.clone();
  22071. var parent = this._parent;
  22072. while (parent) {
  22073. matrix = matrix.multiply(parent.getLocalMatrix());
  22074. parent = parent.getParent();
  22075. }
  22076. return matrix;
  22077. };
  22078. // Methods
  22079. Bone.prototype.updateMatrix = function (matrix) {
  22080. this._matrix = matrix;
  22081. this._skeleton._markAsDirty();
  22082. this._updateDifferenceMatrix();
  22083. };
  22084. Bone.prototype._updateDifferenceMatrix = function () {
  22085. if (this._parent) {
  22086. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22087. }
  22088. else {
  22089. this._absoluteTransform.copyFrom(this._matrix);
  22090. }
  22091. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22092. for (var index = 0; index < this.children.length; index++) {
  22093. this.children[index]._updateDifferenceMatrix();
  22094. }
  22095. };
  22096. Bone.prototype.markAsDirty = function () {
  22097. this._currentRenderId++;
  22098. this._skeleton._markAsDirty();
  22099. };
  22100. return Bone;
  22101. })(BABYLON.Node);
  22102. BABYLON.Bone = Bone;
  22103. })(BABYLON || (BABYLON = {}));
  22104. var BABYLON;
  22105. (function (BABYLON) {
  22106. var Skeleton = (function () {
  22107. function Skeleton(name, id, scene) {
  22108. this.name = name;
  22109. this.id = id;
  22110. this.bones = new Array();
  22111. this._isDirty = true;
  22112. this._identity = BABYLON.Matrix.Identity();
  22113. this._ranges = new Array();
  22114. this.bones = [];
  22115. this._scene = scene;
  22116. scene.skeletons.push(this);
  22117. this.prepare();
  22118. //make sure it will recalculate the matrix next time prepare is called.
  22119. this._isDirty = true;
  22120. }
  22121. // Members
  22122. Skeleton.prototype.getTransformMatrices = function () {
  22123. return this._transformMatrices;
  22124. };
  22125. Skeleton.prototype.getScene = function () {
  22126. return this._scene;
  22127. };
  22128. // Methods
  22129. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22130. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22131. };
  22132. Skeleton.prototype.deleteAnimationRange = function (name) {
  22133. for (var index = 0; index < this._ranges.length; index++) {
  22134. if (this._ranges[index].name === name) {
  22135. this._ranges.splice(index, 1);
  22136. return;
  22137. }
  22138. }
  22139. };
  22140. Skeleton.prototype.getAnimationRange = function (name) {
  22141. for (var index = 0; index < this._ranges.length; index++) {
  22142. if (this._ranges[index].name === name) {
  22143. return this._ranges[index];
  22144. }
  22145. }
  22146. return null;
  22147. };
  22148. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22149. var range = this.getAnimationRange(name);
  22150. if (!range) {
  22151. return null;
  22152. }
  22153. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22154. };
  22155. Skeleton.prototype._markAsDirty = function () {
  22156. this._isDirty = true;
  22157. };
  22158. Skeleton.prototype.prepare = function () {
  22159. if (!this._isDirty) {
  22160. return;
  22161. }
  22162. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22163. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22164. }
  22165. for (var index = 0; index < this.bones.length; index++) {
  22166. var bone = this.bones[index];
  22167. var parentBone = bone.getParent();
  22168. if (parentBone) {
  22169. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22170. }
  22171. else {
  22172. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22173. }
  22174. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22175. }
  22176. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22177. this._isDirty = false;
  22178. this._scene._activeBones += this.bones.length;
  22179. };
  22180. Skeleton.prototype.getAnimatables = function () {
  22181. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22182. this._animatables = [];
  22183. for (var index = 0; index < this.bones.length; index++) {
  22184. this._animatables.push(this.bones[index]);
  22185. }
  22186. }
  22187. return this._animatables;
  22188. };
  22189. Skeleton.prototype.clone = function (name, id) {
  22190. var result = new Skeleton(name, id || name, this._scene);
  22191. for (var index = 0; index < this.bones.length; index++) {
  22192. var source = this.bones[index];
  22193. var parentBone = null;
  22194. if (source.getParent()) {
  22195. var parentIndex = this.bones.indexOf(source.getParent());
  22196. parentBone = result.bones[parentIndex];
  22197. }
  22198. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22199. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22200. }
  22201. return result;
  22202. };
  22203. Skeleton.prototype.dispose = function () {
  22204. // Animations
  22205. this.getScene().stopAnimation(this);
  22206. // Remove from scene
  22207. this.getScene().removeSkeleton(this);
  22208. };
  22209. Skeleton.prototype.serialize = function () {
  22210. var serializationObject = {};
  22211. serializationObject.name = this.name;
  22212. serializationObject.id = this.id;
  22213. serializationObject.bones = [];
  22214. for (var index = 0; index < this.bones.length; index++) {
  22215. var bone = this.bones[index];
  22216. var serializedBone = {
  22217. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22218. name: bone.name,
  22219. matrix: bone.getLocalMatrix().toArray()
  22220. };
  22221. serializationObject.bones.push(serializedBone);
  22222. if (bone.animations && bone.animations.length > 0) {
  22223. serializedBone.animation = bone.animations[0].serialize();
  22224. }
  22225. }
  22226. return serializationObject;
  22227. };
  22228. Skeleton.Parse = function (parsedSkeleton, scene) {
  22229. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22230. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22231. var parsedBone = parsedSkeleton.bones[index];
  22232. var parentBone = null;
  22233. if (parsedBone.parentBoneIndex > -1) {
  22234. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22235. }
  22236. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22237. if (parsedBone.animation) {
  22238. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22239. }
  22240. }
  22241. return skeleton;
  22242. };
  22243. return Skeleton;
  22244. })();
  22245. BABYLON.Skeleton = Skeleton;
  22246. })(BABYLON || (BABYLON = {}));
  22247. var BABYLON;
  22248. (function (BABYLON) {
  22249. var PostProcess = (function () {
  22250. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22252. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22253. this.name = name;
  22254. this.width = -1;
  22255. this.height = -1;
  22256. this._reusable = false;
  22257. this._textures = new BABYLON.SmartArray(2);
  22258. this._currentRenderTextureInd = 0;
  22259. if (camera != null) {
  22260. this._camera = camera;
  22261. this._scene = camera.getScene();
  22262. camera.attachPostProcess(this);
  22263. this._engine = this._scene.getEngine();
  22264. }
  22265. else {
  22266. this._engine = engine;
  22267. }
  22268. this._renderRatio = ratio;
  22269. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22270. this._reusable = reusable || false;
  22271. this._textureType = textureType;
  22272. this._samplers = samplers || [];
  22273. this._samplers.push("textureSampler");
  22274. this._fragmentUrl = fragmentUrl;
  22275. this._parameters = parameters || [];
  22276. this.updateEffect(defines);
  22277. }
  22278. PostProcess.prototype.updateEffect = function (defines) {
  22279. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22280. };
  22281. PostProcess.prototype.isReusable = function () {
  22282. return this._reusable;
  22283. };
  22284. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22285. camera = camera || this._camera;
  22286. var scene = camera.getScene();
  22287. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22288. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22289. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22290. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22291. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22292. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22293. if (this._textures.length > 0) {
  22294. for (var i = 0; i < this._textures.length; i++) {
  22295. this._engine._releaseTexture(this._textures.data[i]);
  22296. }
  22297. this._textures.reset();
  22298. }
  22299. this.width = desiredWidth;
  22300. this.height = desiredHeight;
  22301. 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 }));
  22302. if (this._reusable) {
  22303. 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 }));
  22304. }
  22305. if (this.onSizeChanged) {
  22306. this.onSizeChanged();
  22307. }
  22308. }
  22309. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22310. if (this.onActivate) {
  22311. this.onActivate(camera);
  22312. }
  22313. // Clear
  22314. if (this.clearColor) {
  22315. this._engine.clear(this.clearColor, true, true);
  22316. }
  22317. else {
  22318. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22319. }
  22320. if (this._reusable) {
  22321. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22322. }
  22323. };
  22324. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22325. get: function () {
  22326. return this._effect.isSupported;
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. PostProcess.prototype.apply = function () {
  22332. // Check
  22333. if (!this._effect.isReady())
  22334. return null;
  22335. // States
  22336. this._engine.enableEffect(this._effect);
  22337. this._engine.setState(false);
  22338. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22339. this._engine.setDepthBuffer(false);
  22340. this._engine.setDepthWrite(false);
  22341. // Texture
  22342. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22343. // Parameters
  22344. if (this.onApply) {
  22345. this.onApply(this._effect);
  22346. }
  22347. return this._effect;
  22348. };
  22349. PostProcess.prototype.dispose = function (camera) {
  22350. camera = camera || this._camera;
  22351. if (this._textures.length > 0) {
  22352. for (var i = 0; i < this._textures.length; i++) {
  22353. this._engine._releaseTexture(this._textures.data[i]);
  22354. }
  22355. this._textures.reset();
  22356. }
  22357. if (!camera) {
  22358. return;
  22359. }
  22360. camera.detachPostProcess(this);
  22361. var index = camera._postProcesses.indexOf(this);
  22362. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22363. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22364. }
  22365. };
  22366. return PostProcess;
  22367. })();
  22368. BABYLON.PostProcess = PostProcess;
  22369. })(BABYLON || (BABYLON = {}));
  22370. var BABYLON;
  22371. (function (BABYLON) {
  22372. var PostProcessManager = (function () {
  22373. function PostProcessManager(scene) {
  22374. this._vertexDeclaration = [2];
  22375. this._vertexStrideSize = 2 * 4;
  22376. this._scene = scene;
  22377. }
  22378. PostProcessManager.prototype._prepareBuffers = function () {
  22379. if (this._vertexBuffer) {
  22380. return;
  22381. }
  22382. // VBO
  22383. var vertices = [];
  22384. vertices.push(1, 1);
  22385. vertices.push(-1, 1);
  22386. vertices.push(-1, -1);
  22387. vertices.push(1, -1);
  22388. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22389. // Indices
  22390. var indices = [];
  22391. indices.push(0);
  22392. indices.push(1);
  22393. indices.push(2);
  22394. indices.push(0);
  22395. indices.push(2);
  22396. indices.push(3);
  22397. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22398. };
  22399. // Methods
  22400. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22401. var postProcesses = this._scene.activeCamera._postProcesses;
  22402. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22403. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22404. return false;
  22405. }
  22406. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22407. return true;
  22408. };
  22409. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22410. var engine = this._scene.getEngine();
  22411. for (var index = 0; index < postProcesses.length; index++) {
  22412. if (index < postProcesses.length - 1) {
  22413. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22414. }
  22415. else {
  22416. if (targetTexture) {
  22417. engine.bindFramebuffer(targetTexture);
  22418. }
  22419. else {
  22420. engine.restoreDefaultFramebuffer();
  22421. }
  22422. }
  22423. var pp = postProcesses[index];
  22424. var effect = pp.apply();
  22425. if (effect) {
  22426. if (pp.onBeforeRender) {
  22427. pp.onBeforeRender(effect);
  22428. }
  22429. // VBOs
  22430. this._prepareBuffers();
  22431. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22432. // Draw order
  22433. engine.draw(true, 0, 6);
  22434. if (pp.onAfterRender) {
  22435. pp.onAfterRender(effect);
  22436. }
  22437. }
  22438. }
  22439. // Restore depth buffer
  22440. engine.setDepthBuffer(true);
  22441. engine.setDepthWrite(true);
  22442. };
  22443. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22444. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22445. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22446. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22447. return;
  22448. }
  22449. var engine = this._scene.getEngine();
  22450. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22451. if (index < postProcessesTakenIndices.length - 1) {
  22452. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22453. }
  22454. else {
  22455. if (targetTexture) {
  22456. engine.bindFramebuffer(targetTexture, faceIndex);
  22457. }
  22458. else {
  22459. engine.restoreDefaultFramebuffer();
  22460. }
  22461. }
  22462. if (doNotPresent) {
  22463. break;
  22464. }
  22465. var pp = postProcesses[postProcessesTakenIndices[index]];
  22466. var effect = pp.apply();
  22467. if (effect) {
  22468. if (pp.onBeforeRender) {
  22469. pp.onBeforeRender(effect);
  22470. }
  22471. // VBOs
  22472. this._prepareBuffers();
  22473. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22474. // Draw order
  22475. engine.draw(true, 0, 6);
  22476. if (pp.onAfterRender) {
  22477. pp.onAfterRender(effect);
  22478. }
  22479. }
  22480. }
  22481. // Restore depth buffer
  22482. engine.setDepthBuffer(true);
  22483. engine.setDepthWrite(true);
  22484. };
  22485. PostProcessManager.prototype.dispose = function () {
  22486. if (this._vertexBuffer) {
  22487. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22488. this._vertexBuffer = null;
  22489. }
  22490. if (this._indexBuffer) {
  22491. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22492. this._indexBuffer = null;
  22493. }
  22494. };
  22495. return PostProcessManager;
  22496. })();
  22497. BABYLON.PostProcessManager = PostProcessManager;
  22498. })(BABYLON || (BABYLON = {}));
  22499. var BABYLON;
  22500. (function (BABYLON) {
  22501. var PassPostProcess = (function (_super) {
  22502. __extends(PassPostProcess, _super);
  22503. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22504. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22505. }
  22506. return PassPostProcess;
  22507. })(BABYLON.PostProcess);
  22508. BABYLON.PassPostProcess = PassPostProcess;
  22509. })(BABYLON || (BABYLON = {}));
  22510. var BABYLON;
  22511. (function (BABYLON) {
  22512. var PhysicsEngine = (function () {
  22513. function PhysicsEngine(plugin) {
  22514. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22515. }
  22516. PhysicsEngine.prototype._initialize = function (gravity) {
  22517. this._currentPlugin.initialize();
  22518. this._setGravity(gravity);
  22519. };
  22520. PhysicsEngine.prototype._runOneStep = function (delta) {
  22521. if (delta > 0.1) {
  22522. delta = 0.1;
  22523. }
  22524. else if (delta <= 0) {
  22525. delta = 1.0 / 60.0;
  22526. }
  22527. this._currentPlugin.runOneStep(delta);
  22528. };
  22529. PhysicsEngine.prototype._setGravity = function (gravity) {
  22530. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22531. this._currentPlugin.setGravity(this.gravity);
  22532. };
  22533. PhysicsEngine.prototype._getGravity = function () {
  22534. return this._currentPlugin.getGravity();
  22535. };
  22536. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22537. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22538. };
  22539. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22540. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22541. };
  22542. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22543. this._currentPlugin.unregisterMesh(mesh);
  22544. };
  22545. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22546. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22547. };
  22548. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22549. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22550. };
  22551. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22552. this._currentPlugin.updateBodyPosition(mesh);
  22553. };
  22554. PhysicsEngine.prototype.dispose = function () {
  22555. this._currentPlugin.dispose();
  22556. };
  22557. PhysicsEngine.prototype.isSupported = function () {
  22558. return this._currentPlugin.isSupported();
  22559. };
  22560. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22561. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22562. };
  22563. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22564. return this._currentPlugin.name;
  22565. };
  22566. // Statics
  22567. PhysicsEngine.NoImpostor = 0;
  22568. PhysicsEngine.SphereImpostor = 1;
  22569. PhysicsEngine.BoxImpostor = 2;
  22570. PhysicsEngine.PlaneImpostor = 3;
  22571. PhysicsEngine.MeshImpostor = 4;
  22572. PhysicsEngine.CapsuleImpostor = 5;
  22573. PhysicsEngine.ConeImpostor = 6;
  22574. PhysicsEngine.CylinderImpostor = 7;
  22575. PhysicsEngine.ConvexHullImpostor = 8;
  22576. PhysicsEngine.HeightmapImpostor = 9;
  22577. PhysicsEngine.Epsilon = 0.001;
  22578. return PhysicsEngine;
  22579. })();
  22580. BABYLON.PhysicsEngine = PhysicsEngine;
  22581. })(BABYLON || (BABYLON = {}));
  22582. var BABYLON;
  22583. (function (BABYLON) {
  22584. var VertexData = (function () {
  22585. function VertexData() {
  22586. }
  22587. VertexData.prototype.set = function (data, kind) {
  22588. switch (kind) {
  22589. case BABYLON.VertexBuffer.PositionKind:
  22590. this.positions = data;
  22591. break;
  22592. case BABYLON.VertexBuffer.NormalKind:
  22593. this.normals = data;
  22594. break;
  22595. case BABYLON.VertexBuffer.UVKind:
  22596. this.uvs = data;
  22597. break;
  22598. case BABYLON.VertexBuffer.UV2Kind:
  22599. this.uvs2 = data;
  22600. break;
  22601. case BABYLON.VertexBuffer.UV3Kind:
  22602. this.uvs3 = data;
  22603. break;
  22604. case BABYLON.VertexBuffer.UV4Kind:
  22605. this.uvs4 = data;
  22606. break;
  22607. case BABYLON.VertexBuffer.UV5Kind:
  22608. this.uvs5 = data;
  22609. break;
  22610. case BABYLON.VertexBuffer.UV6Kind:
  22611. this.uvs6 = data;
  22612. break;
  22613. case BABYLON.VertexBuffer.ColorKind:
  22614. this.colors = data;
  22615. break;
  22616. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22617. this.matricesIndices = data;
  22618. break;
  22619. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22620. this.matricesWeights = data;
  22621. break;
  22622. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22623. this.matricesIndicesExtra = data;
  22624. break;
  22625. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22626. this.matricesWeightsExtra = data;
  22627. break;
  22628. }
  22629. };
  22630. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22631. this._applyTo(mesh, updatable);
  22632. };
  22633. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22634. this._applyTo(geometry, updatable);
  22635. };
  22636. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22637. this._update(mesh);
  22638. };
  22639. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22640. this._update(geometry);
  22641. };
  22642. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22643. if (this.positions) {
  22644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22645. }
  22646. if (this.normals) {
  22647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22648. }
  22649. if (this.uvs) {
  22650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22651. }
  22652. if (this.uvs2) {
  22653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22654. }
  22655. if (this.uvs3) {
  22656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22657. }
  22658. if (this.uvs4) {
  22659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22660. }
  22661. if (this.uvs5) {
  22662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22663. }
  22664. if (this.uvs6) {
  22665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22666. }
  22667. if (this.colors) {
  22668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22669. }
  22670. if (this.matricesIndices) {
  22671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22672. }
  22673. if (this.matricesWeights) {
  22674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22675. }
  22676. if (this.matricesIndicesExtra) {
  22677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22678. }
  22679. if (this.matricesWeightsExtra) {
  22680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22681. }
  22682. if (this.indices) {
  22683. meshOrGeometry.setIndices(this.indices);
  22684. }
  22685. };
  22686. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22687. if (this.positions) {
  22688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22689. }
  22690. if (this.normals) {
  22691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22692. }
  22693. if (this.uvs) {
  22694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22695. }
  22696. if (this.uvs2) {
  22697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22698. }
  22699. if (this.uvs3) {
  22700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22701. }
  22702. if (this.uvs4) {
  22703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22704. }
  22705. if (this.uvs5) {
  22706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22707. }
  22708. if (this.uvs6) {
  22709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22710. }
  22711. if (this.colors) {
  22712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22713. }
  22714. if (this.matricesIndices) {
  22715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22716. }
  22717. if (this.matricesWeights) {
  22718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22719. }
  22720. if (this.matricesIndicesExtra) {
  22721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22722. }
  22723. if (this.matricesWeightsExtra) {
  22724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22725. }
  22726. if (this.indices) {
  22727. meshOrGeometry.setIndices(this.indices);
  22728. }
  22729. };
  22730. VertexData.prototype.transform = function (matrix) {
  22731. var transformed = BABYLON.Vector3.Zero();
  22732. var index;
  22733. if (this.positions) {
  22734. var position = BABYLON.Vector3.Zero();
  22735. for (index = 0; index < this.positions.length; index += 3) {
  22736. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22737. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22738. this.positions[index] = transformed.x;
  22739. this.positions[index + 1] = transformed.y;
  22740. this.positions[index + 2] = transformed.z;
  22741. }
  22742. }
  22743. if (this.normals) {
  22744. var normal = BABYLON.Vector3.Zero();
  22745. for (index = 0; index < this.normals.length; index += 3) {
  22746. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22747. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22748. this.normals[index] = transformed.x;
  22749. this.normals[index + 1] = transformed.y;
  22750. this.normals[index + 2] = transformed.z;
  22751. }
  22752. }
  22753. };
  22754. VertexData.prototype.merge = function (other) {
  22755. if (other.indices) {
  22756. if (!this.indices) {
  22757. this.indices = [];
  22758. }
  22759. var offset = this.positions ? this.positions.length / 3 : 0;
  22760. for (var index = 0; index < other.indices.length; index++) {
  22761. //TODO check type - if Int32Array!
  22762. this.indices.push(other.indices[index] + offset);
  22763. }
  22764. }
  22765. this.positions = this._mergeElement(this.positions, other.positions);
  22766. this.normals = this._mergeElement(this.normals, other.normals);
  22767. this.uvs = this._mergeElement(this.uvs, other.uvs);
  22768. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  22769. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  22770. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  22771. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  22772. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  22773. this.colors = this._mergeElement(this.colors, other.colors);
  22774. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  22775. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  22776. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  22777. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  22778. };
  22779. VertexData.prototype._mergeElement = function (source, other) {
  22780. if (!other)
  22781. return source;
  22782. if (!source)
  22783. return other;
  22784. var len = other.length + source.length;
  22785. var isSrcTypedArray = source instanceof Float32Array;
  22786. var isOthTypedArray = other instanceof Float32Array;
  22787. // use non-loop method when the source is Float32Array
  22788. if (isSrcTypedArray) {
  22789. var ret32 = new Float32Array(len);
  22790. ret32.set(source);
  22791. ret32.set(other, source.length);
  22792. return ret32;
  22793. }
  22794. else if (!isOthTypedArray) {
  22795. return source.concat(other);
  22796. }
  22797. else {
  22798. var ret = source.slice(0); // copy source to a separate array
  22799. for (var i = 0, len = other.length; i < len; i++) {
  22800. ret.push(other[i]);
  22801. }
  22802. return ret;
  22803. }
  22804. };
  22805. VertexData.prototype.serialize = function () {
  22806. var serializationObject = this.serialize();
  22807. if (this.positions) {
  22808. serializationObject.positions = this.positions;
  22809. }
  22810. if (this.normals) {
  22811. serializationObject.normals = this.normals;
  22812. }
  22813. if (this.uvs) {
  22814. serializationObject.uvs = this.uvs;
  22815. }
  22816. if (this.uvs2) {
  22817. serializationObject.uvs2 = this.uvs2;
  22818. }
  22819. if (this.uvs3) {
  22820. serializationObject.uvs3 = this.uvs3;
  22821. }
  22822. if (this.uvs4) {
  22823. serializationObject.uvs4 = this.uvs4;
  22824. }
  22825. if (this.uvs5) {
  22826. serializationObject.uvs5 = this.uvs5;
  22827. }
  22828. if (this.uvs6) {
  22829. serializationObject.uvs6 = this.uvs6;
  22830. }
  22831. if (this.colors) {
  22832. serializationObject.colors = this.colors;
  22833. }
  22834. if (this.matricesIndices) {
  22835. serializationObject.matricesIndices = this.matricesIndices;
  22836. serializationObject.matricesIndices._isExpanded = true;
  22837. }
  22838. if (this.matricesWeights) {
  22839. serializationObject.matricesWeights = this.matricesWeights;
  22840. }
  22841. if (this.matricesIndicesExtra) {
  22842. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  22843. serializationObject.matricesIndicesExtra._isExpanded = true;
  22844. }
  22845. if (this.matricesWeightsExtra) {
  22846. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  22847. }
  22848. serializationObject.indices = this.indices;
  22849. return serializationObject;
  22850. };
  22851. // Statics
  22852. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22853. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22854. };
  22855. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22856. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22857. };
  22858. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22859. var result = new VertexData();
  22860. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22861. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22862. }
  22863. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22864. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22865. }
  22866. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22867. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22868. }
  22869. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22870. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22871. }
  22872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22873. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22874. }
  22875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22876. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22877. }
  22878. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22879. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22880. }
  22881. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22882. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22883. }
  22884. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22885. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22886. }
  22887. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22888. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22889. }
  22890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22891. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22892. }
  22893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22894. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22895. }
  22896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22897. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22898. }
  22899. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22900. return result;
  22901. };
  22902. VertexData.CreateRibbon = function (options) {
  22903. var pathArray = options.pathArray;
  22904. var closeArray = options.closeArray || false;
  22905. var closePath = options.closePath || false;
  22906. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22907. var offset = options.offset || defaultOffset;
  22908. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22909. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22910. var positions = [];
  22911. var indices = [];
  22912. var normals = [];
  22913. var uvs = [];
  22914. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22915. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22916. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22917. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22918. var minlg; // minimal length among all paths from pathArray
  22919. var lg = []; // array of path lengths : nb of vertex per path
  22920. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22921. var p; // path iterator
  22922. var i; // point iterator
  22923. var j; // point iterator
  22924. // if single path in pathArray
  22925. if (pathArray.length < 2) {
  22926. var ar1 = [];
  22927. var ar2 = [];
  22928. for (i = 0; i < pathArray[0].length - offset; i++) {
  22929. ar1.push(pathArray[0][i]);
  22930. ar2.push(pathArray[0][i + offset]);
  22931. }
  22932. pathArray = [ar1, ar2];
  22933. }
  22934. // positions and horizontal distances (u)
  22935. var idc = 0;
  22936. var closePathCorr = (closePath) ? 1 : 0;
  22937. var path;
  22938. var l;
  22939. minlg = pathArray[0].length;
  22940. var vectlg;
  22941. var dist;
  22942. for (p = 0; p < pathArray.length; p++) {
  22943. uTotalDistance[p] = 0;
  22944. us[p] = [0];
  22945. path = pathArray[p];
  22946. l = path.length;
  22947. minlg = (minlg < l) ? minlg : l;
  22948. j = 0;
  22949. while (j < l) {
  22950. positions.push(path[j].x, path[j].y, path[j].z);
  22951. if (j > 0) {
  22952. vectlg = path[j].subtract(path[j - 1]).length();
  22953. dist = vectlg + uTotalDistance[p];
  22954. us[p].push(dist);
  22955. uTotalDistance[p] = dist;
  22956. }
  22957. j++;
  22958. }
  22959. if (closePath) {
  22960. j--;
  22961. positions.push(path[0].x, path[0].y, path[0].z);
  22962. vectlg = path[j].subtract(path[0]).length();
  22963. dist = vectlg + uTotalDistance[p];
  22964. us[p].push(dist);
  22965. uTotalDistance[p] = dist;
  22966. }
  22967. lg[p] = l + closePathCorr;
  22968. idx[p] = idc;
  22969. idc += (l + closePathCorr);
  22970. }
  22971. // vertical distances (v)
  22972. var path1;
  22973. var path2;
  22974. var vertex1;
  22975. var vertex2;
  22976. for (i = 0; i < minlg + closePathCorr; i++) {
  22977. vTotalDistance[i] = 0;
  22978. vs[i] = [0];
  22979. for (p = 0; p < pathArray.length - 1; p++) {
  22980. path1 = pathArray[p];
  22981. path2 = pathArray[p + 1];
  22982. if (i === minlg) {
  22983. vertex1 = path1[0];
  22984. vertex2 = path2[0];
  22985. }
  22986. else {
  22987. vertex1 = path1[i];
  22988. vertex2 = path2[i];
  22989. }
  22990. vectlg = vertex2.subtract(vertex1).length();
  22991. dist = vectlg + vTotalDistance[i];
  22992. vs[i].push(dist);
  22993. vTotalDistance[i] = dist;
  22994. }
  22995. if (closeArray) {
  22996. path1 = pathArray[p];
  22997. path2 = pathArray[0];
  22998. if (i === minlg) {
  22999. vertex2 = path2[0];
  23000. }
  23001. vectlg = vertex2.subtract(vertex1).length();
  23002. dist = vectlg + vTotalDistance[i];
  23003. vTotalDistance[i] = dist;
  23004. }
  23005. }
  23006. // uvs
  23007. var u;
  23008. var v;
  23009. for (p = 0; p < pathArray.length; p++) {
  23010. for (i = 0; i < minlg + closePathCorr; i++) {
  23011. u = us[p][i] / uTotalDistance[p];
  23012. v = vs[i][p] / vTotalDistance[i];
  23013. uvs.push(u, v);
  23014. }
  23015. }
  23016. // indices
  23017. p = 0; // path index
  23018. var pi = 0; // positions array index
  23019. var l1 = lg[p] - 1; // path1 length
  23020. var l2 = lg[p + 1] - 1; // path2 length
  23021. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23022. var shft = idx[1] - idx[0]; // shift
  23023. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23024. while (pi <= min && p < path1nb) {
  23025. // 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
  23026. indices.push(pi, pi + shft, pi + 1);
  23027. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23028. pi += 1;
  23029. if (pi === min) {
  23030. p++;
  23031. if (p === lg.length - 1) {
  23032. shft = idx[0] - idx[p];
  23033. l1 = lg[p] - 1;
  23034. l2 = lg[0] - 1;
  23035. }
  23036. else {
  23037. shft = idx[p + 1] - idx[p];
  23038. l1 = lg[p] - 1;
  23039. l2 = lg[p + 1] - 1;
  23040. }
  23041. pi = idx[p];
  23042. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23043. }
  23044. }
  23045. // normals
  23046. VertexData.ComputeNormals(positions, indices, normals);
  23047. if (closePath) {
  23048. var indexFirst = 0;
  23049. var indexLast = 0;
  23050. for (p = 0; p < pathArray.length; p++) {
  23051. indexFirst = idx[p] * 3;
  23052. if (p + 1 < pathArray.length) {
  23053. indexLast = (idx[p + 1] - 1) * 3;
  23054. }
  23055. else {
  23056. indexLast = normals.length - 3;
  23057. }
  23058. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23059. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23060. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23061. normals[indexLast] = normals[indexFirst];
  23062. normals[indexLast + 1] = normals[indexFirst + 1];
  23063. normals[indexLast + 2] = normals[indexFirst + 2];
  23064. }
  23065. }
  23066. // sides
  23067. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23068. // Result
  23069. var vertexData = new VertexData();
  23070. vertexData.indices = indices;
  23071. vertexData.positions = positions;
  23072. vertexData.normals = normals;
  23073. vertexData.uvs = uvs;
  23074. if (closePath) {
  23075. vertexData._idx = idx;
  23076. }
  23077. return vertexData;
  23078. };
  23079. VertexData.CreateBox = function (options) {
  23080. var normalsSource = [
  23081. new BABYLON.Vector3(0, 0, 1),
  23082. new BABYLON.Vector3(0, 0, -1),
  23083. new BABYLON.Vector3(1, 0, 0),
  23084. new BABYLON.Vector3(-1, 0, 0),
  23085. new BABYLON.Vector3(0, 1, 0),
  23086. new BABYLON.Vector3(0, -1, 0)
  23087. ];
  23088. var indices = [];
  23089. var positions = [];
  23090. var normals = [];
  23091. var uvs = [];
  23092. var width = options.width || options.size || 1;
  23093. var height = options.height || options.size || 1;
  23094. var depth = options.depth || options.size || 1;
  23095. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23096. var faceUV = options.faceUV || new Array(6);
  23097. var faceColors = options.faceColors;
  23098. var colors = [];
  23099. // default face colors and UV if undefined
  23100. for (var f = 0; f < 6; f++) {
  23101. if (faceUV[f] === undefined) {
  23102. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23103. }
  23104. if (faceColors && faceColors[f] === undefined) {
  23105. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23106. }
  23107. }
  23108. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23109. // Create each face in turn.
  23110. for (var index = 0; index < normalsSource.length; index++) {
  23111. var normal = normalsSource[index];
  23112. // Get two vectors perpendicular to the face normal and to each other.
  23113. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23114. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23115. // Six indices (two triangles) per face.
  23116. var verticesLength = positions.length / 3;
  23117. indices.push(verticesLength);
  23118. indices.push(verticesLength + 1);
  23119. indices.push(verticesLength + 2);
  23120. indices.push(verticesLength);
  23121. indices.push(verticesLength + 2);
  23122. indices.push(verticesLength + 3);
  23123. // Four vertices per face.
  23124. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23125. positions.push(vertex.x, vertex.y, vertex.z);
  23126. normals.push(normal.x, normal.y, normal.z);
  23127. uvs.push(faceUV[index].z, faceUV[index].w);
  23128. if (faceColors) {
  23129. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23130. }
  23131. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23132. positions.push(vertex.x, vertex.y, vertex.z);
  23133. normals.push(normal.x, normal.y, normal.z);
  23134. uvs.push(faceUV[index].x, faceUV[index].w);
  23135. if (faceColors) {
  23136. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23137. }
  23138. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23139. positions.push(vertex.x, vertex.y, vertex.z);
  23140. normals.push(normal.x, normal.y, normal.z);
  23141. uvs.push(faceUV[index].x, faceUV[index].y);
  23142. if (faceColors) {
  23143. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23144. }
  23145. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23146. positions.push(vertex.x, vertex.y, vertex.z);
  23147. normals.push(normal.x, normal.y, normal.z);
  23148. uvs.push(faceUV[index].z, faceUV[index].y);
  23149. if (faceColors) {
  23150. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23151. }
  23152. }
  23153. // sides
  23154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23155. // Result
  23156. var vertexData = new VertexData();
  23157. vertexData.indices = indices;
  23158. vertexData.positions = positions;
  23159. vertexData.normals = normals;
  23160. vertexData.uvs = uvs;
  23161. if (faceColors) {
  23162. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23163. vertexData.colors = totalColors;
  23164. }
  23165. return vertexData;
  23166. };
  23167. VertexData.CreateSphere = function (options) {
  23168. var segments = options.segments || 32;
  23169. var diameterX = options.diameterX || options.diameter || 1;
  23170. var diameterY = options.diameterY || options.diameter || 1;
  23171. var diameterZ = options.diameterZ || options.diameter || 1;
  23172. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23173. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23174. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23175. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23176. var totalZRotationSteps = 2 + segments;
  23177. var totalYRotationSteps = 2 * totalZRotationSteps;
  23178. var indices = [];
  23179. var positions = [];
  23180. var normals = [];
  23181. var uvs = [];
  23182. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23183. var normalizedZ = zRotationStep / totalZRotationSteps;
  23184. var angleZ = normalizedZ * Math.PI * slice;
  23185. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23186. var normalizedY = yRotationStep / totalYRotationSteps;
  23187. var angleY = normalizedY * Math.PI * 2 * arc;
  23188. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23189. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23190. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23191. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23192. var vertex = complete.multiply(radius);
  23193. var normal = complete.divide(radius).normalize();
  23194. positions.push(vertex.x, vertex.y, vertex.z);
  23195. normals.push(normal.x, normal.y, normal.z);
  23196. uvs.push(normalizedY, normalizedZ);
  23197. }
  23198. if (zRotationStep > 0) {
  23199. var verticesCount = positions.length / 3;
  23200. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23201. indices.push((firstIndex));
  23202. indices.push((firstIndex + 1));
  23203. indices.push(firstIndex + totalYRotationSteps + 1);
  23204. indices.push((firstIndex + totalYRotationSteps + 1));
  23205. indices.push((firstIndex + 1));
  23206. indices.push((firstIndex + totalYRotationSteps + 2));
  23207. }
  23208. }
  23209. }
  23210. // Sides
  23211. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23212. // Result
  23213. var vertexData = new VertexData();
  23214. vertexData.indices = indices;
  23215. vertexData.positions = positions;
  23216. vertexData.normals = normals;
  23217. vertexData.uvs = uvs;
  23218. return vertexData;
  23219. };
  23220. // Cylinder and cone
  23221. VertexData.CreateCylinder = function (options) {
  23222. var height = options.height || 2;
  23223. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23224. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23225. var tessellation = options.tessellation || 24;
  23226. var subdivisions = options.subdivisions || 1;
  23227. var hasRings = options.hasRings;
  23228. var enclose = options.enclose;
  23229. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23231. var faceUV = options.faceUV || new Array(3);
  23232. var faceColors = options.faceColors;
  23233. // default face colors and UV if undefined
  23234. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23235. var ringNb = (hasRings) ? subdivisions : 1;
  23236. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23237. var f;
  23238. for (f = 0; f < surfaceNb; f++) {
  23239. if (faceColors && faceColors[f] === undefined) {
  23240. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23241. }
  23242. }
  23243. for (f = 0; f < surfaceNb; f++) {
  23244. if (faceUV && faceUV[f] === undefined) {
  23245. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23246. }
  23247. }
  23248. var indices = [];
  23249. var positions = [];
  23250. var normals = [];
  23251. var uvs = [];
  23252. var colors = [];
  23253. var angle_step = Math.PI * 2 * arc / tessellation;
  23254. var angle;
  23255. var h;
  23256. var radius;
  23257. var tan = (diameterBottom - diameterTop) / 2 / height;
  23258. var ringVertex = BABYLON.Vector3.Zero();
  23259. var ringNormal = BABYLON.Vector3.Zero();
  23260. var ringFirstVertex = BABYLON.Vector3.Zero();
  23261. var ringFirstNormal = BABYLON.Vector3.Zero();
  23262. var quadNormal = BABYLON.Vector3.Zero();
  23263. var Y = BABYLON.Axis.Y;
  23264. // positions, normals, uvs
  23265. var i;
  23266. var j;
  23267. var r;
  23268. var ringIdx = 1;
  23269. var s = 1; // surface index
  23270. var cs = 0;
  23271. var v = 0;
  23272. for (i = 0; i <= subdivisions; i++) {
  23273. h = i / subdivisions;
  23274. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23275. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23276. for (r = 0; r < ringIdx; r++) {
  23277. if (hasRings) {
  23278. s += r;
  23279. }
  23280. if (enclose) {
  23281. s += 2 * r;
  23282. }
  23283. for (j = 0; j <= tessellation; j++) {
  23284. angle = j * angle_step;
  23285. // position
  23286. ringVertex.x = Math.cos(-angle) * radius;
  23287. ringVertex.y = -height / 2 + h * height;
  23288. ringVertex.z = Math.sin(-angle) * radius;
  23289. // normal
  23290. if (diameterTop === 0 && i === subdivisions) {
  23291. // if no top cap, reuse former normals
  23292. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23293. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23294. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23295. }
  23296. else {
  23297. ringNormal.x = ringVertex.x;
  23298. ringNormal.z = ringVertex.z;
  23299. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23300. ringNormal.normalize();
  23301. }
  23302. // keep first ring vertex values for enclose
  23303. if (j === 0) {
  23304. ringFirstVertex.copyFrom(ringVertex);
  23305. ringFirstNormal.copyFrom(ringNormal);
  23306. }
  23307. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23308. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23309. if (hasRings) {
  23310. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23311. }
  23312. else {
  23313. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23314. }
  23315. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23316. if (faceColors) {
  23317. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23318. }
  23319. }
  23320. // if enclose, add four vertices and their dedicated normals
  23321. if (arc !== 1 && enclose) {
  23322. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23323. positions.push(0, ringVertex.y, 0);
  23324. positions.push(0, ringVertex.y, 0);
  23325. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23326. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23327. quadNormal.normalize();
  23328. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23329. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23330. quadNormal.normalize();
  23331. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23332. if (hasRings) {
  23333. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23334. }
  23335. else {
  23336. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23337. }
  23338. uvs.push(faceUV[s + 1].x, v);
  23339. uvs.push(faceUV[s + 1].z, v);
  23340. if (hasRings) {
  23341. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23342. }
  23343. else {
  23344. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23345. }
  23346. uvs.push(faceUV[s + 2].x, v);
  23347. uvs.push(faceUV[s + 2].z, v);
  23348. if (faceColors) {
  23349. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23350. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23351. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23352. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23353. }
  23354. }
  23355. if (cs !== s) {
  23356. cs = s;
  23357. }
  23358. }
  23359. }
  23360. // indices
  23361. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23362. var s;
  23363. i = 0;
  23364. for (s = 0; s < subdivisions; s++) {
  23365. for (j = 0; j < tessellation; j++) {
  23366. var i0 = i * (e + 1) + j;
  23367. var i1 = (i + 1) * (e + 1) + j;
  23368. var i2 = i * (e + 1) + (j + 1);
  23369. var i3 = (i + 1) * (e + 1) + (j + 1);
  23370. indices.push(i0, i1, i2);
  23371. indices.push(i3, i2, i1);
  23372. }
  23373. if (arc !== 1 && enclose) {
  23374. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23375. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23376. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23377. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23378. }
  23379. i = (hasRings) ? (i + 2) : (i + 1);
  23380. }
  23381. // Caps
  23382. var createCylinderCap = function (isTop) {
  23383. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23384. if (radius === 0) {
  23385. return;
  23386. }
  23387. // Cap positions, normals & uvs
  23388. var angle;
  23389. var circleVector;
  23390. var i;
  23391. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23392. var c;
  23393. if (faceColors) {
  23394. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23395. }
  23396. // cap center
  23397. var vbase = positions.length / 3;
  23398. var offset = isTop ? height / 2 : -height / 2;
  23399. var center = new BABYLON.Vector3(0, offset, 0);
  23400. positions.push(center.x, center.y, center.z);
  23401. normals.push(0, isTop ? 1 : -1, 0);
  23402. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23403. if (faceColors) {
  23404. colors.push(c.r, c.g, c.b, c.a);
  23405. }
  23406. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23407. for (i = 0; i <= tessellation; i++) {
  23408. angle = Math.PI * 2 * i * arc / tessellation;
  23409. var cos = Math.cos(-angle);
  23410. var sin = Math.sin(-angle);
  23411. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23412. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23413. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23414. normals.push(0, isTop ? 1 : -1, 0);
  23415. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23416. if (faceColors) {
  23417. colors.push(c.r, c.g, c.b, c.a);
  23418. }
  23419. }
  23420. // Cap indices
  23421. for (i = 0; i < tessellation; i++) {
  23422. if (!isTop) {
  23423. indices.push(vbase);
  23424. indices.push(vbase + (i + 1));
  23425. indices.push(vbase + (i + 2));
  23426. }
  23427. else {
  23428. indices.push(vbase);
  23429. indices.push(vbase + (i + 2));
  23430. indices.push(vbase + (i + 1));
  23431. }
  23432. }
  23433. };
  23434. // add caps to geometry
  23435. createCylinderCap(false);
  23436. createCylinderCap(true);
  23437. // Sides
  23438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23439. var vertexData = new VertexData();
  23440. vertexData.indices = indices;
  23441. vertexData.positions = positions;
  23442. vertexData.normals = normals;
  23443. vertexData.uvs = uvs;
  23444. if (faceColors) {
  23445. vertexData.colors = colors;
  23446. }
  23447. return vertexData;
  23448. };
  23449. VertexData.CreateTorus = function (options) {
  23450. var indices = [];
  23451. var positions = [];
  23452. var normals = [];
  23453. var uvs = [];
  23454. var diameter = options.diameter || 1;
  23455. var thickness = options.thickness || 0.5;
  23456. var tessellation = options.tessellation || 16;
  23457. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23458. var stride = tessellation + 1;
  23459. for (var i = 0; i <= tessellation; i++) {
  23460. var u = i / tessellation;
  23461. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23462. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23463. for (var j = 0; j <= tessellation; j++) {
  23464. var v = 1 - j / tessellation;
  23465. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23466. var dx = Math.cos(innerAngle);
  23467. var dy = Math.sin(innerAngle);
  23468. // Create a vertex.
  23469. var normal = new BABYLON.Vector3(dx, dy, 0);
  23470. var position = normal.scale(thickness / 2);
  23471. var textureCoordinate = new BABYLON.Vector2(u, v);
  23472. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23473. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23474. positions.push(position.x, position.y, position.z);
  23475. normals.push(normal.x, normal.y, normal.z);
  23476. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23477. // And create indices for two triangles.
  23478. var nextI = (i + 1) % stride;
  23479. var nextJ = (j + 1) % stride;
  23480. indices.push(i * stride + j);
  23481. indices.push(i * stride + nextJ);
  23482. indices.push(nextI * stride + j);
  23483. indices.push(i * stride + nextJ);
  23484. indices.push(nextI * stride + nextJ);
  23485. indices.push(nextI * stride + j);
  23486. }
  23487. }
  23488. // Sides
  23489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23490. // Result
  23491. var vertexData = new VertexData();
  23492. vertexData.indices = indices;
  23493. vertexData.positions = positions;
  23494. vertexData.normals = normals;
  23495. vertexData.uvs = uvs;
  23496. return vertexData;
  23497. };
  23498. VertexData.CreateLines = function (options) {
  23499. var indices = [];
  23500. var positions = [];
  23501. var points = options.points;
  23502. for (var index = 0; index < points.length; index++) {
  23503. positions.push(points[index].x, points[index].y, points[index].z);
  23504. if (index > 0) {
  23505. indices.push(index - 1);
  23506. indices.push(index);
  23507. }
  23508. }
  23509. // Result
  23510. var vertexData = new VertexData();
  23511. vertexData.indices = indices;
  23512. vertexData.positions = positions;
  23513. return vertexData;
  23514. };
  23515. VertexData.CreateDashedLines = function (options) {
  23516. var dashSize = options.dashSize || 3;
  23517. var gapSize = options.gapSize || 1;
  23518. var dashNb = options.dashNb || 200;
  23519. var points = options.points;
  23520. var positions = new Array();
  23521. var indices = new Array();
  23522. var curvect = BABYLON.Vector3.Zero();
  23523. var lg = 0;
  23524. var nb = 0;
  23525. var shft = 0;
  23526. var dashshft = 0;
  23527. var curshft = 0;
  23528. var idx = 0;
  23529. var i = 0;
  23530. for (i = 0; i < points.length - 1; i++) {
  23531. points[i + 1].subtractToRef(points[i], curvect);
  23532. lg += curvect.length();
  23533. }
  23534. shft = lg / dashNb;
  23535. dashshft = dashSize * shft / (dashSize + gapSize);
  23536. for (i = 0; i < points.length - 1; i++) {
  23537. points[i + 1].subtractToRef(points[i], curvect);
  23538. nb = Math.floor(curvect.length() / shft);
  23539. curvect.normalize();
  23540. for (var j = 0; j < nb; j++) {
  23541. curshft = shft * j;
  23542. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23543. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23544. indices.push(idx, idx + 1);
  23545. idx += 2;
  23546. }
  23547. }
  23548. // Result
  23549. var vertexData = new VertexData();
  23550. vertexData.positions = positions;
  23551. vertexData.indices = indices;
  23552. return vertexData;
  23553. };
  23554. VertexData.CreateGround = function (options) {
  23555. var indices = [];
  23556. var positions = [];
  23557. var normals = [];
  23558. var uvs = [];
  23559. var row, col;
  23560. var width = options.width || 1;
  23561. var height = options.height || 1;
  23562. var subdivisions = options.subdivisions || 1;
  23563. for (row = 0; row <= subdivisions; row++) {
  23564. for (col = 0; col <= subdivisions; col++) {
  23565. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23566. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23567. positions.push(position.x, position.y, position.z);
  23568. normals.push(normal.x, normal.y, normal.z);
  23569. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23570. }
  23571. }
  23572. for (row = 0; row < subdivisions; row++) {
  23573. for (col = 0; col < subdivisions; col++) {
  23574. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23575. indices.push(col + 1 + row * (subdivisions + 1));
  23576. indices.push(col + row * (subdivisions + 1));
  23577. indices.push(col + (row + 1) * (subdivisions + 1));
  23578. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23579. indices.push(col + row * (subdivisions + 1));
  23580. }
  23581. }
  23582. // Result
  23583. var vertexData = new VertexData();
  23584. vertexData.indices = indices;
  23585. vertexData.positions = positions;
  23586. vertexData.normals = normals;
  23587. vertexData.uvs = uvs;
  23588. return vertexData;
  23589. };
  23590. VertexData.CreateTiledGround = function (options) {
  23591. var xmin = options.xmin;
  23592. var zmin = options.zmin;
  23593. var xmax = options.xmax;
  23594. var zmax = options.zmax;
  23595. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23596. var precision = options.precision || { w: 1, h: 1 };
  23597. var indices = [];
  23598. var positions = [];
  23599. var normals = [];
  23600. var uvs = [];
  23601. var row, col, tileRow, tileCol;
  23602. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23603. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23604. precision.w = (precision.w < 1) ? 1 : precision.w;
  23605. precision.h = (precision.h < 1) ? 1 : precision.h;
  23606. var tileSize = {
  23607. 'w': (xmax - xmin) / subdivisions.w,
  23608. 'h': (zmax - zmin) / subdivisions.h
  23609. };
  23610. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23611. // Indices
  23612. var base = positions.length / 3;
  23613. var rowLength = precision.w + 1;
  23614. for (row = 0; row < precision.h; row++) {
  23615. for (col = 0; col < precision.w; col++) {
  23616. var square = [
  23617. base + col + row * rowLength,
  23618. base + (col + 1) + row * rowLength,
  23619. base + (col + 1) + (row + 1) * rowLength,
  23620. base + col + (row + 1) * rowLength
  23621. ];
  23622. indices.push(square[1]);
  23623. indices.push(square[2]);
  23624. indices.push(square[3]);
  23625. indices.push(square[0]);
  23626. indices.push(square[1]);
  23627. indices.push(square[3]);
  23628. }
  23629. }
  23630. // Position, normals and uvs
  23631. var position = BABYLON.Vector3.Zero();
  23632. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23633. for (row = 0; row <= precision.h; row++) {
  23634. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23635. for (col = 0; col <= precision.w; col++) {
  23636. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23637. position.y = 0;
  23638. positions.push(position.x, position.y, position.z);
  23639. normals.push(normal.x, normal.y, normal.z);
  23640. uvs.push(col / precision.w, row / precision.h);
  23641. }
  23642. }
  23643. }
  23644. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23645. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23646. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23647. }
  23648. }
  23649. // Result
  23650. var vertexData = new VertexData();
  23651. vertexData.indices = indices;
  23652. vertexData.positions = positions;
  23653. vertexData.normals = normals;
  23654. vertexData.uvs = uvs;
  23655. return vertexData;
  23656. };
  23657. VertexData.CreateGroundFromHeightMap = function (options) {
  23658. var indices = [];
  23659. var positions = [];
  23660. var normals = [];
  23661. var uvs = [];
  23662. var row, col;
  23663. // Vertices
  23664. for (row = 0; row <= options.subdivisions; row++) {
  23665. for (col = 0; col <= options.subdivisions; col++) {
  23666. 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));
  23667. // Compute height
  23668. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23669. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23670. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23671. var r = options.buffer[pos] / 255.0;
  23672. var g = options.buffer[pos + 1] / 255.0;
  23673. var b = options.buffer[pos + 2] / 255.0;
  23674. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23675. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23676. // Add vertex
  23677. positions.push(position.x, position.y, position.z);
  23678. normals.push(0, 0, 0);
  23679. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23680. }
  23681. }
  23682. // Indices
  23683. for (row = 0; row < options.subdivisions; row++) {
  23684. for (col = 0; col < options.subdivisions; col++) {
  23685. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23686. indices.push(col + 1 + row * (options.subdivisions + 1));
  23687. indices.push(col + row * (options.subdivisions + 1));
  23688. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23689. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23690. indices.push(col + row * (options.subdivisions + 1));
  23691. }
  23692. }
  23693. // Normals
  23694. VertexData.ComputeNormals(positions, indices, normals);
  23695. // Result
  23696. var vertexData = new VertexData();
  23697. vertexData.indices = indices;
  23698. vertexData.positions = positions;
  23699. vertexData.normals = normals;
  23700. vertexData.uvs = uvs;
  23701. return vertexData;
  23702. };
  23703. VertexData.CreatePlane = function (options) {
  23704. var indices = [];
  23705. var positions = [];
  23706. var normals = [];
  23707. var uvs = [];
  23708. var width = options.width || options.size || 1;
  23709. var height = options.height || options.size || 1;
  23710. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23711. // Vertices
  23712. var halfWidth = width / 2.0;
  23713. var halfHeight = height / 2.0;
  23714. positions.push(-halfWidth, -halfHeight, 0);
  23715. normals.push(0, 0, -1.0);
  23716. uvs.push(0.0, 0.0);
  23717. positions.push(halfWidth, -halfHeight, 0);
  23718. normals.push(0, 0, -1.0);
  23719. uvs.push(1.0, 0.0);
  23720. positions.push(halfWidth, halfHeight, 0);
  23721. normals.push(0, 0, -1.0);
  23722. uvs.push(1.0, 1.0);
  23723. positions.push(-halfWidth, halfHeight, 0);
  23724. normals.push(0, 0, -1.0);
  23725. uvs.push(0.0, 1.0);
  23726. // Indices
  23727. indices.push(0);
  23728. indices.push(1);
  23729. indices.push(2);
  23730. indices.push(0);
  23731. indices.push(2);
  23732. indices.push(3);
  23733. // Sides
  23734. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23735. // Result
  23736. var vertexData = new VertexData();
  23737. vertexData.indices = indices;
  23738. vertexData.positions = positions;
  23739. vertexData.normals = normals;
  23740. vertexData.uvs = uvs;
  23741. return vertexData;
  23742. };
  23743. VertexData.CreateDisc = function (options) {
  23744. var positions = [];
  23745. var indices = [];
  23746. var normals = [];
  23747. var uvs = [];
  23748. var radius = options.radius || 0.5;
  23749. var tessellation = options.tessellation || 64;
  23750. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23751. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23752. // positions and uvs
  23753. positions.push(0, 0, 0); // disc center first
  23754. uvs.push(0.5, 0.5);
  23755. var theta = Math.PI * 2 * arc;
  23756. var step = theta / tessellation;
  23757. for (var a = 0; a < theta; a += step) {
  23758. var x = Math.cos(a);
  23759. var y = Math.sin(a);
  23760. var u = (x + 1) / 2;
  23761. var v = (1 - y) / 2;
  23762. positions.push(radius * x, radius * y, 0);
  23763. uvs.push(u, v);
  23764. }
  23765. if (arc === 1) {
  23766. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23767. uvs.push(uvs[2], uvs[3]);
  23768. }
  23769. //indices
  23770. var vertexNb = positions.length / 3;
  23771. for (var i = 1; i < vertexNb - 1; i++) {
  23772. indices.push(i + 1, 0, i);
  23773. }
  23774. // result
  23775. VertexData.ComputeNormals(positions, indices, normals);
  23776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23777. var vertexData = new VertexData();
  23778. vertexData.indices = indices;
  23779. vertexData.positions = positions;
  23780. vertexData.normals = normals;
  23781. vertexData.uvs = uvs;
  23782. return vertexData;
  23783. };
  23784. VertexData.CreateIcoSphere = function (options) {
  23785. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23786. var radius = options.radius || 1;
  23787. var flat = (options.flat === undefined) ? true : options.flat;
  23788. var subdivisions = options.subdivisions || 4;
  23789. var radiusX = options.radiusX || radius;
  23790. var radiusY = options.radiusY || radius;
  23791. var radiusZ = options.radiusZ || radius;
  23792. var t = (1 + Math.sqrt(5)) / 2;
  23793. // 12 vertex x,y,z
  23794. var ico_vertices = [
  23795. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23796. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23797. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23798. ];
  23799. // index of 3 vertex makes a face of icopshere
  23800. var ico_indices = [
  23801. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23802. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23803. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23804. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23805. ];
  23806. // vertex for uv have aliased position, not for UV
  23807. var vertices_unalias_id = [
  23808. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23809. // vertex alias
  23810. 0,
  23811. 2,
  23812. 3,
  23813. 3,
  23814. 3,
  23815. 4,
  23816. 7,
  23817. 8,
  23818. 9,
  23819. 9,
  23820. 10,
  23821. 11 // 23: B + 12
  23822. ];
  23823. // uv as integer step (not pixels !)
  23824. var ico_vertexuv = [
  23825. 5, 1, 3, 1, 6, 4, 0, 0,
  23826. 5, 3, 4, 2, 2, 2, 4, 0,
  23827. 2, 0, 1, 1, 6, 0, 6, 2,
  23828. // vertex alias (for same vertex on different faces)
  23829. 0, 4,
  23830. 3, 3,
  23831. 4, 4,
  23832. 3, 1,
  23833. 4, 2,
  23834. 4, 4,
  23835. 0, 2,
  23836. 1, 1,
  23837. 2, 2,
  23838. 3, 3,
  23839. 1, 3,
  23840. 2, 4 // 23: B + 12
  23841. ];
  23842. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23843. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23844. // First island of uv mapping
  23845. // v = 4h 3+ 2
  23846. // v = 3h 9+ 4
  23847. // v = 2h 9+ 5 B
  23848. // v = 1h 9 1 0
  23849. // v = 0h 3 8 7 A
  23850. // u = 0 1 2 3 4 5 6 *a
  23851. // Second island of uv mapping
  23852. // v = 4h 0+ B+ 4+
  23853. // v = 3h A+ 2+
  23854. // v = 2h 7+ 6 3+
  23855. // v = 1h 8+ 3+
  23856. // v = 0h
  23857. // u = 0 1 2 3 4 5 6 *a
  23858. // Face layout on texture UV mapping
  23859. // ============
  23860. // \ 4 /\ 16 / ======
  23861. // \ / \ / /\ 11 /
  23862. // \/ 7 \/ / \ /
  23863. // ======= / 10 \/
  23864. // /\ 17 /\ =======
  23865. // / \ / \ \ 15 /\
  23866. // / 8 \/ 12 \ \ / \
  23867. // ============ \/ 6 \
  23868. // \ 18 /\ ============
  23869. // \ / \ \ 5 /\ 0 /
  23870. // \/ 13 \ \ / \ /
  23871. // ======= \/ 1 \/
  23872. // =============
  23873. // /\ 19 /\ 2 /\
  23874. // / \ / \ / \
  23875. // / 14 \/ 9 \/ 3 \
  23876. // ===================
  23877. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23878. var ustep = 138 / 1024;
  23879. var vstep = 239 / 1024;
  23880. var uoffset = 60 / 1024;
  23881. var voffset = 26 / 1024;
  23882. // Second island should have margin, not to touch the first island
  23883. // avoid any borderline artefact in pixel rounding
  23884. var island_u_offset = -40 / 1024;
  23885. var island_v_offset = +20 / 1024;
  23886. // face is either island 0 or 1 :
  23887. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23888. var island = [
  23889. 0, 0, 0, 0, 1,
  23890. 0, 0, 1, 1, 0,
  23891. 0, 0, 1, 1, 0,
  23892. 0, 1, 1, 1, 0 // 15 - 19
  23893. ];
  23894. var indices = [];
  23895. var positions = [];
  23896. var normals = [];
  23897. var uvs = [];
  23898. var current_indice = 0;
  23899. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23900. var face_vertex_pos = new Array(3);
  23901. var face_vertex_uv = new Array(3);
  23902. var v012;
  23903. for (v012 = 0; v012 < 3; v012++) {
  23904. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23905. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23906. }
  23907. // create all with normals
  23908. for (var face = 0; face < 20; face++) {
  23909. // 3 vertex per face
  23910. for (v012 = 0; v012 < 3; v012++) {
  23911. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23912. var v_id = ico_indices[3 * face + v012];
  23913. // vertex have 3D position (x,y,z)
  23914. 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]);
  23915. // Normalize to get normal, then scale to radius
  23916. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23917. // uv Coordinates from vertex ID
  23918. 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);
  23919. }
  23920. // Subdivide the face (interpolate pos, norm, uv)
  23921. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23922. // - norm is linear interpolation of vertex corner normal
  23923. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23924. // - uv is linear interpolation
  23925. //
  23926. // Topology is as below for sub-divide by 2
  23927. // vertex shown as v0,v1,v2
  23928. // interp index is i1 to progress in range [v0,v1[
  23929. // interp index is i2 to progress in range [v0,v2[
  23930. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23931. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23932. //
  23933. //
  23934. // i2 v2
  23935. // ^ ^
  23936. // / / \
  23937. // / / \
  23938. // / / \
  23939. // / / (0,1) \
  23940. // / #---------\
  23941. // / / \ (0,0)'/ \
  23942. // / / \ / \
  23943. // / / \ / \
  23944. // / / (0,0) \ / (1,0) \
  23945. // / #---------#---------\
  23946. // v0 v1
  23947. //
  23948. // --------------------> i1
  23949. //
  23950. // interp of (i1,i2):
  23951. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23952. // along i1 : lerp(x0,x1, i1/(S-i2))
  23953. //
  23954. // centroid of triangle is needed to get help normal computation
  23955. // (c1,c2) are used for centroid location
  23956. var interp_vertex = function (i1, i2, c1, c2) {
  23957. // vertex is interpolated from
  23958. // - face_vertex_pos[0..2]
  23959. // - face_vertex_uv[0..2]
  23960. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  23961. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  23962. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  23963. pos_interp.normalize();
  23964. var vertex_normal;
  23965. if (flat) {
  23966. // in flat mode, recalculate normal as face centroid normal
  23967. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  23968. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  23969. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  23970. }
  23971. else {
  23972. // in smooth mode, recalculate normal from each single vertex position
  23973. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  23974. }
  23975. // Vertex normal need correction due to X,Y,Z radius scaling
  23976. vertex_normal.x /= radiusX;
  23977. vertex_normal.y /= radiusY;
  23978. vertex_normal.z /= radiusZ;
  23979. vertex_normal.normalize();
  23980. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  23981. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  23982. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  23983. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  23984. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  23985. uvs.push(uv_interp.x, uv_interp.y);
  23986. // push each vertex has member of a face
  23987. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  23988. indices.push(current_indice);
  23989. current_indice++;
  23990. };
  23991. for (var i2 = 0; i2 < subdivisions; i2++) {
  23992. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  23993. // face : (i1,i2) for /\ :
  23994. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  23995. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23996. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23997. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23998. if (i1 + i2 + 1 < subdivisions) {
  23999. // face : (i1,i2)' for \/ :
  24000. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24001. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24002. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24003. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24004. }
  24005. }
  24006. }
  24007. }
  24008. // Sides
  24009. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24010. // Result
  24011. var vertexData = new VertexData();
  24012. vertexData.indices = indices;
  24013. vertexData.positions = positions;
  24014. vertexData.normals = normals;
  24015. vertexData.uvs = uvs;
  24016. return vertexData;
  24017. };
  24018. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24019. VertexData.CreatePolyhedron = function (options) {
  24020. // provided polyhedron types :
  24021. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24022. // 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)
  24023. var polyhedra = [];
  24024. 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]] };
  24025. 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]] };
  24026. polyhedra[2] = {
  24027. 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]],
  24028. 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]]
  24029. };
  24030. polyhedra[3] = {
  24031. 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]],
  24032. 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]]
  24033. };
  24034. polyhedra[4] = {
  24035. 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]],
  24036. 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]]
  24037. };
  24038. 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]] };
  24039. 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]] };
  24040. 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]] };
  24041. 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]] };
  24042. 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]] };
  24043. 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]] };
  24044. 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]] };
  24045. 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]] };
  24046. 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]] };
  24047. polyhedra[14] = {
  24048. 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]],
  24049. 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]]
  24050. };
  24051. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24052. var size = options.size;
  24053. var sizeX = options.sizeX || size || 1;
  24054. var sizeY = options.sizeY || size || 1;
  24055. var sizeZ = options.sizeZ || size || 1;
  24056. var data = options.custom || polyhedra[type];
  24057. var nbfaces = data.face.length;
  24058. var faceUV = options.faceUV || new Array(nbfaces);
  24059. var faceColors = options.faceColors;
  24060. var flat = (options.flat === undefined) ? true : options.flat;
  24061. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24062. var positions = [];
  24063. var indices = [];
  24064. var normals = [];
  24065. var uvs = [];
  24066. var colors = [];
  24067. var index = 0;
  24068. var faceIdx = 0; // face cursor in the array "indexes"
  24069. var indexes = [];
  24070. var i = 0;
  24071. var f = 0;
  24072. var u, v, ang, x, y, tmp;
  24073. // default face colors and UV if undefined
  24074. if (flat) {
  24075. for (f = 0; f < nbfaces; f++) {
  24076. if (faceColors && faceColors[f] === undefined) {
  24077. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24078. }
  24079. if (faceUV && faceUV[f] === undefined) {
  24080. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24081. }
  24082. }
  24083. }
  24084. if (!flat) {
  24085. for (i = 0; i < data.vertex.length; i++) {
  24086. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24087. uvs.push(0, 0);
  24088. }
  24089. for (f = 0; f < nbfaces; f++) {
  24090. for (i = 0; i < data.face[f].length - 2; i++) {
  24091. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24092. }
  24093. }
  24094. }
  24095. else {
  24096. for (f = 0; f < nbfaces; f++) {
  24097. var fl = data.face[f].length; // number of vertices of the current face
  24098. ang = 2 * Math.PI / fl;
  24099. x = 0.5 * Math.tan(ang / 2);
  24100. y = 0.5;
  24101. // positions, uvs, colors
  24102. for (i = 0; i < fl; i++) {
  24103. // positions
  24104. 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);
  24105. indexes.push(index);
  24106. index++;
  24107. // uvs
  24108. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24109. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24110. uvs.push(u, v);
  24111. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24112. y = x * Math.sin(ang) + y * Math.cos(ang);
  24113. x = tmp;
  24114. // colors
  24115. if (faceColors) {
  24116. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24117. }
  24118. }
  24119. // indices from indexes
  24120. for (i = 0; i < fl - 2; i++) {
  24121. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24122. }
  24123. faceIdx += fl;
  24124. }
  24125. }
  24126. VertexData.ComputeNormals(positions, indices, normals);
  24127. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24128. var vertexData = new VertexData();
  24129. vertexData.positions = positions;
  24130. vertexData.indices = indices;
  24131. vertexData.normals = normals;
  24132. vertexData.uvs = uvs;
  24133. if (faceColors && flat) {
  24134. vertexData.colors = colors;
  24135. }
  24136. return vertexData;
  24137. };
  24138. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24139. VertexData.CreateTorusKnot = function (options) {
  24140. var indices = [];
  24141. var positions = [];
  24142. var normals = [];
  24143. var uvs = [];
  24144. var radius = options.radius || 2;
  24145. var tube = options.tube || 0.5;
  24146. var radialSegments = options.radialSegments || 32;
  24147. var tubularSegments = options.tubularSegments || 32;
  24148. var p = options.p || 2;
  24149. var q = options.q || 3;
  24150. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24151. // Helper
  24152. var getPos = function (angle) {
  24153. var cu = Math.cos(angle);
  24154. var su = Math.sin(angle);
  24155. var quOverP = q / p * angle;
  24156. var cs = Math.cos(quOverP);
  24157. var tx = radius * (2 + cs) * 0.5 * cu;
  24158. var ty = radius * (2 + cs) * su * 0.5;
  24159. var tz = radius * Math.sin(quOverP) * 0.5;
  24160. return new BABYLON.Vector3(tx, ty, tz);
  24161. };
  24162. // Vertices
  24163. var i;
  24164. var j;
  24165. for (i = 0; i <= radialSegments; i++) {
  24166. var modI = i % radialSegments;
  24167. var u = modI / radialSegments * 2 * p * Math.PI;
  24168. var p1 = getPos(u);
  24169. var p2 = getPos(u + 0.01);
  24170. var tang = p2.subtract(p1);
  24171. var n = p2.add(p1);
  24172. var bitan = BABYLON.Vector3.Cross(tang, n);
  24173. n = BABYLON.Vector3.Cross(bitan, tang);
  24174. bitan.normalize();
  24175. n.normalize();
  24176. for (j = 0; j < tubularSegments; j++) {
  24177. var modJ = j % tubularSegments;
  24178. var v = modJ / tubularSegments * 2 * Math.PI;
  24179. var cx = -tube * Math.cos(v);
  24180. var cy = tube * Math.sin(v);
  24181. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24182. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24183. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24184. uvs.push(i / radialSegments);
  24185. uvs.push(j / tubularSegments);
  24186. }
  24187. }
  24188. for (i = 0; i < radialSegments; i++) {
  24189. for (j = 0; j < tubularSegments; j++) {
  24190. var jNext = (j + 1) % tubularSegments;
  24191. var a = i * tubularSegments + j;
  24192. var b = (i + 1) * tubularSegments + j;
  24193. var c = (i + 1) * tubularSegments + jNext;
  24194. var d = i * tubularSegments + jNext;
  24195. indices.push(d);
  24196. indices.push(b);
  24197. indices.push(a);
  24198. indices.push(d);
  24199. indices.push(c);
  24200. indices.push(b);
  24201. }
  24202. }
  24203. // Normals
  24204. VertexData.ComputeNormals(positions, indices, normals);
  24205. // Sides
  24206. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24207. // Result
  24208. var vertexData = new VertexData();
  24209. vertexData.indices = indices;
  24210. vertexData.positions = positions;
  24211. vertexData.normals = normals;
  24212. vertexData.uvs = uvs;
  24213. return vertexData;
  24214. };
  24215. // Tools
  24216. /**
  24217. * @param {any} - positions (number[] or Float32Array)
  24218. * @param {any} - indices (number[] or Uint16Array)
  24219. * @param {any} - normals (number[] or Float32Array)
  24220. */
  24221. VertexData.ComputeNormals = function (positions, indices, normals) {
  24222. var index = 0;
  24223. var p1p2x = 0.0;
  24224. var p1p2y = 0.0;
  24225. var p1p2z = 0.0;
  24226. var p3p2x = 0.0;
  24227. var p3p2y = 0.0;
  24228. var p3p2z = 0.0;
  24229. var faceNormalx = 0.0;
  24230. var faceNormaly = 0.0;
  24231. var faceNormalz = 0.0;
  24232. var length = 0.0;
  24233. var i1 = 0;
  24234. var i2 = 0;
  24235. var i3 = 0;
  24236. for (index = 0; index < positions.length; index++) {
  24237. normals[index] = 0.0;
  24238. }
  24239. // indice triplet = 1 face
  24240. var nbFaces = indices.length / 3;
  24241. for (index = 0; index < nbFaces; index++) {
  24242. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24243. i2 = indices[index * 3 + 1];
  24244. i3 = indices[index * 3 + 2];
  24245. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24246. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24247. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24248. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24249. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24250. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24251. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24252. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24253. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24254. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24255. length = (length === 0) ? 1.0 : length;
  24256. faceNormalx /= length; // normalize this normal
  24257. faceNormaly /= length;
  24258. faceNormalz /= length;
  24259. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24260. normals[i1 * 3 + 1] += faceNormaly;
  24261. normals[i1 * 3 + 2] += faceNormalz;
  24262. normals[i2 * 3] += faceNormalx;
  24263. normals[i2 * 3 + 1] += faceNormaly;
  24264. normals[i2 * 3 + 2] += faceNormalz;
  24265. normals[i3 * 3] += faceNormalx;
  24266. normals[i3 * 3 + 1] += faceNormaly;
  24267. normals[i3 * 3 + 2] += faceNormalz;
  24268. }
  24269. // last normalization of each normal
  24270. for (index = 0; index < normals.length / 3; index++) {
  24271. faceNormalx = normals[index * 3];
  24272. faceNormaly = normals[index * 3 + 1];
  24273. faceNormalz = normals[index * 3 + 2];
  24274. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24275. length = (length === 0) ? 1.0 : length;
  24276. faceNormalx /= length;
  24277. faceNormaly /= length;
  24278. faceNormalz /= length;
  24279. normals[index * 3] = faceNormalx;
  24280. normals[index * 3 + 1] = faceNormaly;
  24281. normals[index * 3 + 2] = faceNormalz;
  24282. }
  24283. };
  24284. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24285. var li = indices.length;
  24286. var ln = normals.length;
  24287. var i;
  24288. var n;
  24289. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24290. switch (sideOrientation) {
  24291. case BABYLON.Mesh.FRONTSIDE:
  24292. // nothing changed
  24293. break;
  24294. case BABYLON.Mesh.BACKSIDE:
  24295. var tmp;
  24296. // indices
  24297. for (i = 0; i < li; i += 3) {
  24298. tmp = indices[i];
  24299. indices[i] = indices[i + 2];
  24300. indices[i + 2] = tmp;
  24301. }
  24302. // normals
  24303. for (n = 0; n < ln; n++) {
  24304. normals[n] = -normals[n];
  24305. }
  24306. break;
  24307. case BABYLON.Mesh.DOUBLESIDE:
  24308. // positions
  24309. var lp = positions.length;
  24310. var l = lp / 3;
  24311. for (var p = 0; p < lp; p++) {
  24312. positions[lp + p] = positions[p];
  24313. }
  24314. // indices
  24315. for (i = 0; i < li; i += 3) {
  24316. indices[i + li] = indices[i + 2] + l;
  24317. indices[i + 1 + li] = indices[i + 1] + l;
  24318. indices[i + 2 + li] = indices[i] + l;
  24319. }
  24320. // normals
  24321. for (n = 0; n < ln; n++) {
  24322. normals[ln + n] = -normals[n];
  24323. }
  24324. // uvs
  24325. var lu = uvs.length;
  24326. for (var u = 0; u < lu; u++) {
  24327. uvs[u + lu] = uvs[u];
  24328. }
  24329. break;
  24330. }
  24331. };
  24332. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24333. var vertexData = new VertexData();
  24334. // positions
  24335. var positions = parsedVertexData.positions;
  24336. if (positions) {
  24337. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24338. }
  24339. // normals
  24340. var normals = parsedVertexData.normals;
  24341. if (normals) {
  24342. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24343. }
  24344. // uvs
  24345. var uvs = parsedVertexData.uvs;
  24346. if (uvs) {
  24347. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24348. }
  24349. // uv2s
  24350. var uv2s = parsedVertexData.uv2s;
  24351. if (uv2s) {
  24352. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24353. }
  24354. // uv3s
  24355. var uv3s = parsedVertexData.uv3s;
  24356. if (uv3s) {
  24357. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24358. }
  24359. // uv4s
  24360. var uv4s = parsedVertexData.uv4s;
  24361. if (uv4s) {
  24362. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24363. }
  24364. // uv5s
  24365. var uv5s = parsedVertexData.uv5s;
  24366. if (uv5s) {
  24367. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24368. }
  24369. // uv6s
  24370. var uv6s = parsedVertexData.uv6s;
  24371. if (uv6s) {
  24372. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24373. }
  24374. // colors
  24375. var colors = parsedVertexData.colors;
  24376. if (colors) {
  24377. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24378. }
  24379. // matricesIndices
  24380. var matricesIndices = parsedVertexData.matricesIndices;
  24381. if (matricesIndices) {
  24382. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24383. }
  24384. // matricesWeights
  24385. var matricesWeights = parsedVertexData.matricesWeights;
  24386. if (matricesWeights) {
  24387. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24388. }
  24389. // indices
  24390. var indices = parsedVertexData.indices;
  24391. if (indices) {
  24392. vertexData.indices = indices;
  24393. }
  24394. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24395. };
  24396. return VertexData;
  24397. })();
  24398. BABYLON.VertexData = VertexData;
  24399. })(BABYLON || (BABYLON = {}));
  24400. var BABYLON;
  24401. (function (BABYLON) {
  24402. var Tags = (function () {
  24403. function Tags() {
  24404. }
  24405. Tags.EnableFor = function (obj) {
  24406. obj._tags = obj._tags || {};
  24407. obj.hasTags = function () {
  24408. return Tags.HasTags(obj);
  24409. };
  24410. obj.addTags = function (tagsString) {
  24411. return Tags.AddTagsTo(obj, tagsString);
  24412. };
  24413. obj.removeTags = function (tagsString) {
  24414. return Tags.RemoveTagsFrom(obj, tagsString);
  24415. };
  24416. obj.matchesTagsQuery = function (tagsQuery) {
  24417. return Tags.MatchesQuery(obj, tagsQuery);
  24418. };
  24419. };
  24420. Tags.DisableFor = function (obj) {
  24421. delete obj._tags;
  24422. delete obj.hasTags;
  24423. delete obj.addTags;
  24424. delete obj.removeTags;
  24425. delete obj.matchesTagsQuery;
  24426. };
  24427. Tags.HasTags = function (obj) {
  24428. if (!obj._tags) {
  24429. return false;
  24430. }
  24431. return !BABYLON.Tools.IsEmpty(obj._tags);
  24432. };
  24433. Tags.GetTags = function (obj) {
  24434. if (!obj._tags) {
  24435. return null;
  24436. }
  24437. return obj._tags;
  24438. };
  24439. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24440. // a tag cannot start with '||', '&&', and '!'
  24441. // it cannot contain whitespaces
  24442. Tags.AddTagsTo = function (obj, tagsString) {
  24443. if (!tagsString) {
  24444. return;
  24445. }
  24446. if (typeof tagsString !== "string") {
  24447. return;
  24448. }
  24449. var tags = tagsString.split(" ");
  24450. for (var t in tags) {
  24451. Tags._AddTagTo(obj, tags[t]);
  24452. }
  24453. };
  24454. Tags._AddTagTo = function (obj, tag) {
  24455. tag = tag.trim();
  24456. if (tag === "" || tag === "true" || tag === "false") {
  24457. return;
  24458. }
  24459. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24460. return;
  24461. }
  24462. Tags.EnableFor(obj);
  24463. obj._tags[tag] = true;
  24464. };
  24465. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24466. if (!Tags.HasTags(obj)) {
  24467. return;
  24468. }
  24469. var tags = tagsString.split(" ");
  24470. for (var t in tags) {
  24471. Tags._RemoveTagFrom(obj, tags[t]);
  24472. }
  24473. };
  24474. Tags._RemoveTagFrom = function (obj, tag) {
  24475. delete obj._tags[tag];
  24476. };
  24477. Tags.MatchesQuery = function (obj, tagsQuery) {
  24478. if (tagsQuery === undefined) {
  24479. return true;
  24480. }
  24481. if (tagsQuery === "") {
  24482. return Tags.HasTags(obj);
  24483. }
  24484. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24485. };
  24486. return Tags;
  24487. })();
  24488. BABYLON.Tags = Tags;
  24489. })(BABYLON || (BABYLON = {}));
  24490. var BABYLON;
  24491. (function (BABYLON) {
  24492. var Internals;
  24493. (function (Internals) {
  24494. var AndOrNotEvaluator = (function () {
  24495. function AndOrNotEvaluator() {
  24496. }
  24497. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24498. if (!query.match(/\([^\(\)]*\)/g)) {
  24499. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24500. }
  24501. else {
  24502. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24503. // remove parenthesis
  24504. r = r.slice(1, r.length - 1);
  24505. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24506. });
  24507. }
  24508. if (query === "true") {
  24509. return true;
  24510. }
  24511. if (query === "false") {
  24512. return false;
  24513. }
  24514. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24515. };
  24516. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24517. evaluateCallback = evaluateCallback || (function (r) {
  24518. return r === "true" ? true : false;
  24519. });
  24520. var result;
  24521. var or = parenthesisContent.split("||");
  24522. for (var i in or) {
  24523. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24524. var and = ori.split("&&");
  24525. if (and.length > 1) {
  24526. for (var j = 0; j < and.length; ++j) {
  24527. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24528. if (andj !== "true" && andj !== "false") {
  24529. if (andj[0] === "!") {
  24530. result = !evaluateCallback(andj.substring(1));
  24531. }
  24532. else {
  24533. result = evaluateCallback(andj);
  24534. }
  24535. }
  24536. else {
  24537. result = andj === "true" ? true : false;
  24538. }
  24539. if (!result) {
  24540. ori = "false";
  24541. break;
  24542. }
  24543. }
  24544. }
  24545. if (result || ori === "true") {
  24546. result = true;
  24547. break;
  24548. }
  24549. // result equals false (or undefined)
  24550. if (ori !== "true" && ori !== "false") {
  24551. if (ori[0] === "!") {
  24552. result = !evaluateCallback(ori.substring(1));
  24553. }
  24554. else {
  24555. result = evaluateCallback(ori);
  24556. }
  24557. }
  24558. else {
  24559. result = ori === "true" ? true : false;
  24560. }
  24561. }
  24562. // the whole parenthesis scope is replaced by 'true' or 'false'
  24563. return result ? "true" : "false";
  24564. };
  24565. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24566. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24567. // remove whitespaces
  24568. r = r.replace(/[\s]/g, function () { return ""; });
  24569. return r.length % 2 ? "!" : "";
  24570. });
  24571. booleanString = booleanString.trim();
  24572. if (booleanString === "!true") {
  24573. booleanString = "false";
  24574. }
  24575. else if (booleanString === "!false") {
  24576. booleanString = "true";
  24577. }
  24578. return booleanString;
  24579. };
  24580. return AndOrNotEvaluator;
  24581. })();
  24582. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24583. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24584. })(BABYLON || (BABYLON = {}));
  24585. var BABYLON;
  24586. (function (BABYLON) {
  24587. var PostProcessRenderPass = (function () {
  24588. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24589. this._enabled = true;
  24590. this._refCount = 0;
  24591. this._name = name;
  24592. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24593. this.setRenderList(renderList);
  24594. this._renderTexture.onBeforeRender = beforeRender;
  24595. this._renderTexture.onAfterRender = afterRender;
  24596. this._scene = scene;
  24597. this._renderList = renderList;
  24598. }
  24599. // private
  24600. PostProcessRenderPass.prototype._incRefCount = function () {
  24601. if (this._refCount === 0) {
  24602. this._scene.customRenderTargets.push(this._renderTexture);
  24603. }
  24604. return ++this._refCount;
  24605. };
  24606. PostProcessRenderPass.prototype._decRefCount = function () {
  24607. this._refCount--;
  24608. if (this._refCount <= 0) {
  24609. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24610. }
  24611. return this._refCount;
  24612. };
  24613. PostProcessRenderPass.prototype._update = function () {
  24614. this.setRenderList(this._renderList);
  24615. };
  24616. // public
  24617. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24618. this._renderTexture.renderList = renderList;
  24619. };
  24620. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24621. return this._renderTexture;
  24622. };
  24623. return PostProcessRenderPass;
  24624. })();
  24625. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24626. })(BABYLON || (BABYLON = {}));
  24627. var BABYLON;
  24628. (function (BABYLON) {
  24629. var PostProcessRenderEffect = (function () {
  24630. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24631. this._engine = engine;
  24632. this._name = name;
  24633. this._singleInstance = singleInstance || true;
  24634. this._getPostProcess = getPostProcess;
  24635. this._cameras = [];
  24636. this._indicesForCamera = [];
  24637. this._postProcesses = {};
  24638. this._renderPasses = {};
  24639. this._renderEffectAsPasses = {};
  24640. }
  24641. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24642. get: function () {
  24643. for (var index in this._postProcesses) {
  24644. if (!this._postProcesses[index].isSupported) {
  24645. return false;
  24646. }
  24647. }
  24648. return true;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. PostProcessRenderEffect.prototype._update = function () {
  24654. for (var renderPassName in this._renderPasses) {
  24655. this._renderPasses[renderPassName]._update();
  24656. }
  24657. };
  24658. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24659. this._renderPasses[renderPass._name] = renderPass;
  24660. this._linkParameters();
  24661. };
  24662. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24663. delete this._renderPasses[renderPass._name];
  24664. this._linkParameters();
  24665. };
  24666. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24667. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24668. this._linkParameters();
  24669. };
  24670. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24671. for (var renderPassName in this._renderPasses) {
  24672. if (renderPassName === passName) {
  24673. return this._renderPasses[passName];
  24674. }
  24675. }
  24676. };
  24677. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24678. this._renderPasses = {};
  24679. this._linkParameters();
  24680. };
  24681. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24682. var cameraKey;
  24683. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24684. for (var i = 0; i < _cam.length; i++) {
  24685. var camera = _cam[i];
  24686. var cameraName = camera.name;
  24687. if (this._singleInstance) {
  24688. cameraKey = 0;
  24689. }
  24690. else {
  24691. cameraKey = cameraName;
  24692. }
  24693. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24694. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24695. if (!this._indicesForCamera[cameraName]) {
  24696. this._indicesForCamera[cameraName] = [];
  24697. }
  24698. this._indicesForCamera[cameraName].push(index);
  24699. if (this._cameras.indexOf(camera) === -1) {
  24700. this._cameras[cameraName] = camera;
  24701. }
  24702. for (var passName in this._renderPasses) {
  24703. this._renderPasses[passName]._incRefCount();
  24704. }
  24705. }
  24706. this._linkParameters();
  24707. };
  24708. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24709. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24710. for (var i = 0; i < _cam.length; i++) {
  24711. var camera = _cam[i];
  24712. var cameraName = camera.name;
  24713. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24714. var index = this._cameras.indexOf(cameraName);
  24715. this._indicesForCamera.splice(index, 1);
  24716. this._cameras.splice(index, 1);
  24717. for (var passName in this._renderPasses) {
  24718. this._renderPasses[passName]._decRefCount();
  24719. }
  24720. }
  24721. };
  24722. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24723. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24724. for (var i = 0; i < _cam.length; i++) {
  24725. var camera = _cam[i];
  24726. var cameraName = camera.name;
  24727. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24728. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24729. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24730. }
  24731. }
  24732. for (var passName in this._renderPasses) {
  24733. this._renderPasses[passName]._incRefCount();
  24734. }
  24735. }
  24736. };
  24737. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24738. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24739. for (var i = 0; i < _cam.length; i++) {
  24740. var camera = _cam[i];
  24741. var cameraName = camera.Name;
  24742. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24743. for (var passName in this._renderPasses) {
  24744. this._renderPasses[passName]._decRefCount();
  24745. }
  24746. }
  24747. };
  24748. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24749. if (this._singleInstance) {
  24750. return this._postProcesses[0];
  24751. }
  24752. else {
  24753. return this._postProcesses[camera.name];
  24754. }
  24755. };
  24756. PostProcessRenderEffect.prototype._linkParameters = function () {
  24757. var _this = this;
  24758. for (var index in this._postProcesses) {
  24759. if (this.applyParameters) {
  24760. this.applyParameters(this._postProcesses[index]);
  24761. }
  24762. this._postProcesses[index].onBeforeRender = function (effect) {
  24763. _this._linkTextures(effect);
  24764. };
  24765. }
  24766. };
  24767. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24768. for (var renderPassName in this._renderPasses) {
  24769. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24770. }
  24771. for (var renderEffectName in this._renderEffectAsPasses) {
  24772. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24773. }
  24774. };
  24775. return PostProcessRenderEffect;
  24776. })();
  24777. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24778. })(BABYLON || (BABYLON = {}));
  24779. var BABYLON;
  24780. (function (BABYLON) {
  24781. var PostProcessRenderPipeline = (function () {
  24782. function PostProcessRenderPipeline(engine, name) {
  24783. this._engine = engine;
  24784. this._name = name;
  24785. this._renderEffects = {};
  24786. this._renderEffectsForIsolatedPass = {};
  24787. this._cameras = [];
  24788. }
  24789. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24790. get: function () {
  24791. for (var renderEffectName in this._renderEffects) {
  24792. if (!this._renderEffects[renderEffectName].isSupported) {
  24793. return false;
  24794. }
  24795. }
  24796. return true;
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24802. this._renderEffects[renderEffect._name] = renderEffect;
  24803. };
  24804. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24805. var renderEffects = this._renderEffects[renderEffectName];
  24806. if (!renderEffects) {
  24807. return;
  24808. }
  24809. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24810. };
  24811. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24812. var renderEffects = this._renderEffects[renderEffectName];
  24813. if (!renderEffects) {
  24814. return;
  24815. }
  24816. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24817. };
  24818. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24819. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24820. var indicesToDelete = [];
  24821. var i;
  24822. for (i = 0; i < _cam.length; i++) {
  24823. var camera = _cam[i];
  24824. var cameraName = camera.name;
  24825. if (this._cameras.indexOf(camera) === -1) {
  24826. this._cameras[cameraName] = camera;
  24827. }
  24828. else if (unique) {
  24829. indicesToDelete.push(i);
  24830. }
  24831. }
  24832. for (i = 0; i < indicesToDelete.length; i++) {
  24833. cameras.splice(indicesToDelete[i], 1);
  24834. }
  24835. for (var renderEffectName in this._renderEffects) {
  24836. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24837. }
  24838. };
  24839. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24840. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24841. for (var renderEffectName in this._renderEffects) {
  24842. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24843. }
  24844. for (var i = 0; i < _cam.length; i++) {
  24845. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24846. }
  24847. };
  24848. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24849. var _this = this;
  24850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24851. var pass = null;
  24852. var renderEffectName;
  24853. for (renderEffectName in this._renderEffects) {
  24854. pass = this._renderEffects[renderEffectName].getPass(passName);
  24855. if (pass != null) {
  24856. break;
  24857. }
  24858. }
  24859. if (pass === null) {
  24860. return;
  24861. }
  24862. for (renderEffectName in this._renderEffects) {
  24863. this._renderEffects[renderEffectName]._disable(_cam);
  24864. }
  24865. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24866. for (var i = 0; i < _cam.length; i++) {
  24867. var camera = _cam[i];
  24868. var cameraName = camera.name;
  24869. 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); });
  24870. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24871. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24872. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24873. }
  24874. };
  24875. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24876. var _this = this;
  24877. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24878. for (var i = 0; i < _cam.length; i++) {
  24879. var camera = _cam[i];
  24880. var cameraName = camera.name;
  24881. 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); });
  24882. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24883. }
  24884. for (var renderEffectName in this._renderEffects) {
  24885. this._renderEffects[renderEffectName]._enable(_cam);
  24886. }
  24887. };
  24888. PostProcessRenderPipeline.prototype._update = function () {
  24889. for (var renderEffectName in this._renderEffects) {
  24890. this._renderEffects[renderEffectName]._update();
  24891. }
  24892. for (var i = 0; i < this._cameras.length; i++) {
  24893. var cameraName = this._cameras[i].name;
  24894. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24895. this._renderEffectsForIsolatedPass[cameraName]._update();
  24896. }
  24897. }
  24898. };
  24899. PostProcessRenderPipeline.prototype.dispose = function () {
  24900. // Must be implemented by children
  24901. };
  24902. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24903. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24904. return PostProcessRenderPipeline;
  24905. })();
  24906. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24907. })(BABYLON || (BABYLON = {}));
  24908. var BABYLON;
  24909. (function (BABYLON) {
  24910. var PostProcessRenderPipelineManager = (function () {
  24911. function PostProcessRenderPipelineManager() {
  24912. this._renderPipelines = {};
  24913. }
  24914. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24915. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24916. };
  24917. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24918. var renderPipeline = this._renderPipelines[renderPipelineName];
  24919. if (!renderPipeline) {
  24920. return;
  24921. }
  24922. renderPipeline._attachCameras(cameras, unique);
  24923. };
  24924. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24925. var renderPipeline = this._renderPipelines[renderPipelineName];
  24926. if (!renderPipeline) {
  24927. return;
  24928. }
  24929. renderPipeline._detachCameras(cameras);
  24930. };
  24931. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24932. var renderPipeline = this._renderPipelines[renderPipelineName];
  24933. if (!renderPipeline) {
  24934. return;
  24935. }
  24936. renderPipeline._enableEffect(renderEffectName, cameras);
  24937. };
  24938. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24939. var renderPipeline = this._renderPipelines[renderPipelineName];
  24940. if (!renderPipeline) {
  24941. return;
  24942. }
  24943. renderPipeline._disableEffect(renderEffectName, cameras);
  24944. };
  24945. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24946. var renderPipeline = this._renderPipelines[renderPipelineName];
  24947. if (!renderPipeline) {
  24948. return;
  24949. }
  24950. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24951. };
  24952. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24953. var renderPipeline = this._renderPipelines[renderPipelineName];
  24954. if (!renderPipeline) {
  24955. return;
  24956. }
  24957. renderPipeline._disableDisplayOnlyPass(cameras);
  24958. };
  24959. PostProcessRenderPipelineManager.prototype.update = function () {
  24960. for (var renderPipelineName in this._renderPipelines) {
  24961. var pipeline = this._renderPipelines[renderPipelineName];
  24962. if (!pipeline.isSupported) {
  24963. pipeline.dispose();
  24964. delete this._renderPipelines[renderPipelineName];
  24965. }
  24966. else {
  24967. pipeline._update();
  24968. }
  24969. }
  24970. };
  24971. return PostProcessRenderPipelineManager;
  24972. })();
  24973. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24974. })(BABYLON || (BABYLON = {}));
  24975. var BABYLON;
  24976. (function (BABYLON) {
  24977. var BoundingBoxRenderer = (function () {
  24978. function BoundingBoxRenderer(scene) {
  24979. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24980. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24981. this.showBackLines = true;
  24982. this.renderList = new BABYLON.SmartArray(32);
  24983. this._scene = scene;
  24984. }
  24985. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24986. if (this._colorShader) {
  24987. return;
  24988. }
  24989. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24990. attributes: ["position"],
  24991. uniforms: ["worldViewProjection", "color"]
  24992. });
  24993. var engine = this._scene.getEngine();
  24994. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24995. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24996. 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]);
  24997. };
  24998. BoundingBoxRenderer.prototype.reset = function () {
  24999. this.renderList.reset();
  25000. };
  25001. BoundingBoxRenderer.prototype.render = function () {
  25002. if (this.renderList.length === 0) {
  25003. return;
  25004. }
  25005. this._prepareRessources();
  25006. if (!this._colorShader.isReady()) {
  25007. return;
  25008. }
  25009. var engine = this._scene.getEngine();
  25010. engine.setDepthWrite(false);
  25011. this._colorShader._preBind();
  25012. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25013. var boundingBox = this.renderList.data[boundingBoxIndex];
  25014. var min = boundingBox.minimum;
  25015. var max = boundingBox.maximum;
  25016. var diff = max.subtract(min);
  25017. var median = min.add(diff.scale(0.5));
  25018. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25019. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25020. .multiply(boundingBox.getWorldMatrix());
  25021. // VBOs
  25022. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25023. if (this.showBackLines) {
  25024. // Back
  25025. engine.setDepthFunctionToGreaterOrEqual();
  25026. this._scene.resetCachedMaterial();
  25027. this._colorShader.setColor4("color", this.backColor.toColor4());
  25028. this._colorShader.bind(worldMatrix);
  25029. // Draw order
  25030. engine.draw(false, 0, 24);
  25031. }
  25032. // Front
  25033. engine.setDepthFunctionToLess();
  25034. this._scene.resetCachedMaterial();
  25035. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25036. this._colorShader.bind(worldMatrix);
  25037. // Draw order
  25038. engine.draw(false, 0, 24);
  25039. }
  25040. this._colorShader.unbind();
  25041. engine.setDepthFunctionToLessOrEqual();
  25042. engine.setDepthWrite(true);
  25043. };
  25044. BoundingBoxRenderer.prototype.dispose = function () {
  25045. if (!this._colorShader) {
  25046. return;
  25047. }
  25048. this._colorShader.dispose();
  25049. this._vb.dispose();
  25050. this._scene.getEngine()._releaseBuffer(this._ib);
  25051. };
  25052. return BoundingBoxRenderer;
  25053. })();
  25054. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25055. })(BABYLON || (BABYLON = {}));
  25056. var BABYLON;
  25057. (function (BABYLON) {
  25058. var Condition = (function () {
  25059. function Condition(actionManager) {
  25060. this._actionManager = actionManager;
  25061. }
  25062. Condition.prototype.isValid = function () {
  25063. return true;
  25064. };
  25065. Condition.prototype._getProperty = function (propertyPath) {
  25066. return this._actionManager._getProperty(propertyPath);
  25067. };
  25068. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25069. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25070. };
  25071. return Condition;
  25072. })();
  25073. BABYLON.Condition = Condition;
  25074. var ValueCondition = (function (_super) {
  25075. __extends(ValueCondition, _super);
  25076. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25077. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25078. _super.call(this, actionManager);
  25079. this.propertyPath = propertyPath;
  25080. this.value = value;
  25081. this.operator = operator;
  25082. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25083. this._property = this._getProperty(this.propertyPath);
  25084. }
  25085. Object.defineProperty(ValueCondition, "IsEqual", {
  25086. get: function () {
  25087. return ValueCondition._IsEqual;
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. Object.defineProperty(ValueCondition, "IsDifferent", {
  25093. get: function () {
  25094. return ValueCondition._IsDifferent;
  25095. },
  25096. enumerable: true,
  25097. configurable: true
  25098. });
  25099. Object.defineProperty(ValueCondition, "IsGreater", {
  25100. get: function () {
  25101. return ValueCondition._IsGreater;
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. Object.defineProperty(ValueCondition, "IsLesser", {
  25107. get: function () {
  25108. return ValueCondition._IsLesser;
  25109. },
  25110. enumerable: true,
  25111. configurable: true
  25112. });
  25113. // Methods
  25114. ValueCondition.prototype.isValid = function () {
  25115. switch (this.operator) {
  25116. case ValueCondition.IsGreater:
  25117. return this._target[this._property] > this.value;
  25118. case ValueCondition.IsLesser:
  25119. return this._target[this._property] < this.value;
  25120. case ValueCondition.IsEqual:
  25121. case ValueCondition.IsDifferent:
  25122. var check;
  25123. if (this.value.equals) {
  25124. check = this.value.equals(this._target[this._property]);
  25125. }
  25126. else {
  25127. check = this.value === this._target[this._property];
  25128. }
  25129. return this.operator === ValueCondition.IsEqual ? check : !check;
  25130. }
  25131. return false;
  25132. };
  25133. // Statics
  25134. ValueCondition._IsEqual = 0;
  25135. ValueCondition._IsDifferent = 1;
  25136. ValueCondition._IsGreater = 2;
  25137. ValueCondition._IsLesser = 3;
  25138. return ValueCondition;
  25139. })(Condition);
  25140. BABYLON.ValueCondition = ValueCondition;
  25141. var PredicateCondition = (function (_super) {
  25142. __extends(PredicateCondition, _super);
  25143. function PredicateCondition(actionManager, predicate) {
  25144. _super.call(this, actionManager);
  25145. this.predicate = predicate;
  25146. }
  25147. PredicateCondition.prototype.isValid = function () {
  25148. return this.predicate();
  25149. };
  25150. return PredicateCondition;
  25151. })(Condition);
  25152. BABYLON.PredicateCondition = PredicateCondition;
  25153. var StateCondition = (function (_super) {
  25154. __extends(StateCondition, _super);
  25155. function StateCondition(actionManager, target, value) {
  25156. _super.call(this, actionManager);
  25157. this.value = value;
  25158. this._target = target;
  25159. }
  25160. // Methods
  25161. StateCondition.prototype.isValid = function () {
  25162. return this._target.state === this.value;
  25163. };
  25164. return StateCondition;
  25165. })(Condition);
  25166. BABYLON.StateCondition = StateCondition;
  25167. })(BABYLON || (BABYLON = {}));
  25168. var BABYLON;
  25169. (function (BABYLON) {
  25170. var Action = (function () {
  25171. function Action(triggerOptions, condition) {
  25172. this.triggerOptions = triggerOptions;
  25173. if (triggerOptions.parameter) {
  25174. this.trigger = triggerOptions.trigger;
  25175. this._triggerParameter = triggerOptions.parameter;
  25176. }
  25177. else {
  25178. this.trigger = triggerOptions;
  25179. }
  25180. this._nextActiveAction = this;
  25181. this._condition = condition;
  25182. }
  25183. // Methods
  25184. Action.prototype._prepare = function () {
  25185. };
  25186. Action.prototype.getTriggerParameter = function () {
  25187. return this._triggerParameter;
  25188. };
  25189. Action.prototype._executeCurrent = function (evt) {
  25190. if (this._nextActiveAction._condition) {
  25191. var condition = this._nextActiveAction._condition;
  25192. var currentRenderId = this._actionManager.getScene().getRenderId();
  25193. // We cache the current evaluation for the current frame
  25194. if (condition._evaluationId === currentRenderId) {
  25195. if (!condition._currentResult) {
  25196. return;
  25197. }
  25198. }
  25199. else {
  25200. condition._evaluationId = currentRenderId;
  25201. if (!condition.isValid()) {
  25202. condition._currentResult = false;
  25203. return;
  25204. }
  25205. condition._currentResult = true;
  25206. }
  25207. }
  25208. this._nextActiveAction.execute(evt);
  25209. if (this._nextActiveAction._child) {
  25210. if (!this._nextActiveAction._child._actionManager) {
  25211. this._nextActiveAction._child._actionManager = this._actionManager;
  25212. }
  25213. this._nextActiveAction = this._nextActiveAction._child;
  25214. }
  25215. else {
  25216. this._nextActiveAction = this;
  25217. }
  25218. };
  25219. Action.prototype.execute = function (evt) {
  25220. };
  25221. Action.prototype.then = function (action) {
  25222. this._child = action;
  25223. action._actionManager = this._actionManager;
  25224. action._prepare();
  25225. return action;
  25226. };
  25227. Action.prototype._getProperty = function (propertyPath) {
  25228. return this._actionManager._getProperty(propertyPath);
  25229. };
  25230. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25231. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25232. };
  25233. return Action;
  25234. })();
  25235. BABYLON.Action = Action;
  25236. })(BABYLON || (BABYLON = {}));
  25237. var BABYLON;
  25238. (function (BABYLON) {
  25239. /**
  25240. * ActionEvent is the event beint sent when an action is triggered.
  25241. */
  25242. var ActionEvent = (function () {
  25243. /**
  25244. * @constructor
  25245. * @param source The mesh or sprite that triggered the action.
  25246. * @param pointerX The X mouse cursor position at the time of the event
  25247. * @param pointerY The Y mouse cursor position at the time of the event
  25248. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25249. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25250. */
  25251. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25252. this.source = source;
  25253. this.pointerX = pointerX;
  25254. this.pointerY = pointerY;
  25255. this.meshUnderPointer = meshUnderPointer;
  25256. this.sourceEvent = sourceEvent;
  25257. this.additionalData = additionalData;
  25258. }
  25259. /**
  25260. * Helper function to auto-create an ActionEvent from a source mesh.
  25261. * @param source The source mesh that triggered the event
  25262. * @param evt {Event} The original (browser) event
  25263. */
  25264. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25265. var scene = source.getScene();
  25266. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25267. };
  25268. /**
  25269. * Helper function to auto-create an ActionEvent from a source mesh.
  25270. * @param source The source sprite that triggered the event
  25271. * @param scene Scene associated with the sprite
  25272. * @param evt {Event} The original (browser) event
  25273. */
  25274. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25275. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25276. };
  25277. /**
  25278. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25279. * @param scene the scene where the event occurred
  25280. * @param evt {Event} The original (browser) event
  25281. */
  25282. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25283. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25284. };
  25285. return ActionEvent;
  25286. })();
  25287. BABYLON.ActionEvent = ActionEvent;
  25288. /**
  25289. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25290. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25291. */
  25292. var ActionManager = (function () {
  25293. function ActionManager(scene) {
  25294. // Members
  25295. this.actions = new Array();
  25296. this._scene = scene;
  25297. scene._actionManagers.push(this);
  25298. }
  25299. Object.defineProperty(ActionManager, "NothingTrigger", {
  25300. get: function () {
  25301. return ActionManager._NothingTrigger;
  25302. },
  25303. enumerable: true,
  25304. configurable: true
  25305. });
  25306. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25307. get: function () {
  25308. return ActionManager._OnPickTrigger;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25314. get: function () {
  25315. return ActionManager._OnLeftPickTrigger;
  25316. },
  25317. enumerable: true,
  25318. configurable: true
  25319. });
  25320. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25321. get: function () {
  25322. return ActionManager._OnRightPickTrigger;
  25323. },
  25324. enumerable: true,
  25325. configurable: true
  25326. });
  25327. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25328. get: function () {
  25329. return ActionManager._OnCenterPickTrigger;
  25330. },
  25331. enumerable: true,
  25332. configurable: true
  25333. });
  25334. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25335. get: function () {
  25336. return ActionManager._OnPointerOverTrigger;
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25342. get: function () {
  25343. return ActionManager._OnPointerOutTrigger;
  25344. },
  25345. enumerable: true,
  25346. configurable: true
  25347. });
  25348. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25349. get: function () {
  25350. return ActionManager._OnEveryFrameTrigger;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25356. get: function () {
  25357. return ActionManager._OnIntersectionEnterTrigger;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25363. get: function () {
  25364. return ActionManager._OnIntersectionExitTrigger;
  25365. },
  25366. enumerable: true,
  25367. configurable: true
  25368. });
  25369. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25370. get: function () {
  25371. return ActionManager._OnKeyDownTrigger;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25377. get: function () {
  25378. return ActionManager._OnKeyUpTrigger;
  25379. },
  25380. enumerable: true,
  25381. configurable: true
  25382. });
  25383. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25384. get: function () {
  25385. return ActionManager._OnPickUpTrigger;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. // Methods
  25391. ActionManager.prototype.dispose = function () {
  25392. var index = this._scene._actionManagers.indexOf(this);
  25393. if (index > -1) {
  25394. this._scene._actionManagers.splice(index, 1);
  25395. }
  25396. };
  25397. ActionManager.prototype.getScene = function () {
  25398. return this._scene;
  25399. };
  25400. /**
  25401. * Does this action manager handles actions of any of the given triggers
  25402. * @param {number[]} triggers - the triggers to be tested
  25403. * @return {boolean} whether one (or more) of the triggers is handeled
  25404. */
  25405. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25406. for (var index = 0; index < this.actions.length; index++) {
  25407. var action = this.actions[index];
  25408. if (triggers.indexOf(action.trigger) > -1) {
  25409. return true;
  25410. }
  25411. }
  25412. return false;
  25413. };
  25414. /**
  25415. * Does this action manager handles actions of a given trigger
  25416. * @param {number} trigger - the trigger to be tested
  25417. * @return {boolean} whether the trigger is handeled
  25418. */
  25419. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25420. for (var index = 0; index < this.actions.length; index++) {
  25421. var action = this.actions[index];
  25422. if (action.trigger === trigger) {
  25423. return true;
  25424. }
  25425. }
  25426. return false;
  25427. };
  25428. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25429. /**
  25430. * Does this action manager has pointer triggers
  25431. * @return {boolean} whether or not it has pointer triggers
  25432. */
  25433. get: function () {
  25434. for (var index = 0; index < this.actions.length; index++) {
  25435. var action = this.actions[index];
  25436. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25437. return true;
  25438. }
  25439. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25440. return true;
  25441. }
  25442. }
  25443. return false;
  25444. },
  25445. enumerable: true,
  25446. configurable: true
  25447. });
  25448. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25449. /**
  25450. * Does this action manager has pick triggers
  25451. * @return {boolean} whether or not it has pick triggers
  25452. */
  25453. get: function () {
  25454. for (var index = 0; index < this.actions.length; index++) {
  25455. var action = this.actions[index];
  25456. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25457. return true;
  25458. }
  25459. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25460. return true;
  25461. }
  25462. }
  25463. return false;
  25464. },
  25465. enumerable: true,
  25466. configurable: true
  25467. });
  25468. /**
  25469. * Registers an action to this action manager
  25470. * @param {BABYLON.Action} action - the action to be registered
  25471. * @return {BABYLON.Action} the action amended (prepared) after registration
  25472. */
  25473. ActionManager.prototype.registerAction = function (action) {
  25474. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25475. if (this.getScene().actionManager !== this) {
  25476. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25477. return null;
  25478. }
  25479. }
  25480. this.actions.push(action);
  25481. action._actionManager = this;
  25482. action._prepare();
  25483. return action;
  25484. };
  25485. /**
  25486. * Process a specific trigger
  25487. * @param {number} trigger - the trigger to process
  25488. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25489. */
  25490. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25491. for (var index = 0; index < this.actions.length; index++) {
  25492. var action = this.actions[index];
  25493. if (action.trigger === trigger) {
  25494. if (trigger === ActionManager.OnKeyUpTrigger
  25495. || trigger === ActionManager.OnKeyDownTrigger) {
  25496. var parameter = action.getTriggerParameter();
  25497. if (parameter) {
  25498. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25499. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25500. if (actualkey !== parameter.toLowerCase()) {
  25501. continue;
  25502. }
  25503. }
  25504. }
  25505. action._executeCurrent(evt);
  25506. }
  25507. }
  25508. };
  25509. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25510. var properties = propertyPath.split(".");
  25511. for (var index = 0; index < properties.length - 1; index++) {
  25512. target = target[properties[index]];
  25513. }
  25514. return target;
  25515. };
  25516. ActionManager.prototype._getProperty = function (propertyPath) {
  25517. var properties = propertyPath.split(".");
  25518. return properties[properties.length - 1];
  25519. };
  25520. ActionManager.Parse = function (parsedActions, object, scene) {
  25521. var actionManager = new BABYLON.ActionManager(scene);
  25522. if (object === null)
  25523. scene.actionManager = actionManager;
  25524. else
  25525. object.actionManager = actionManager;
  25526. // instanciate a new object
  25527. var instanciate = function (name, params) {
  25528. var newInstance = Object.create(BABYLON[name].prototype);
  25529. newInstance.constructor.apply(newInstance, params);
  25530. return newInstance;
  25531. };
  25532. var parseParameter = function (name, value, target, propertyPath) {
  25533. if (propertyPath === null) {
  25534. // String, boolean or float
  25535. var floatValue = parseFloat(value);
  25536. if (value === "true" || value === "false")
  25537. return value === "true";
  25538. else
  25539. return isNaN(floatValue) ? value : floatValue;
  25540. }
  25541. var effectiveTarget = propertyPath.split(".");
  25542. var values = value.split(",");
  25543. // Get effective Target
  25544. for (var i = 0; i < effectiveTarget.length; i++) {
  25545. target = target[effectiveTarget[i]];
  25546. }
  25547. // Return appropriate value with its type
  25548. if (typeof (target) === "boolean")
  25549. return values[0] === "true";
  25550. if (typeof (target) === "string")
  25551. return values[0];
  25552. // Parameters with multiple values such as Vector3 etc.
  25553. var split = new Array();
  25554. for (var i = 0; i < values.length; i++)
  25555. split.push(parseFloat(values[i]));
  25556. if (target instanceof BABYLON.Vector3)
  25557. return BABYLON.Vector3.FromArray(split);
  25558. if (target instanceof BABYLON.Vector4)
  25559. return BABYLON.Vector4.FromArray(split);
  25560. if (target instanceof BABYLON.Color3)
  25561. return BABYLON.Color3.FromArray(split);
  25562. if (target instanceof BABYLON.Color4)
  25563. return BABYLON.Color4.FromArray(split);
  25564. return parseFloat(values[0]);
  25565. };
  25566. // traverse graph per trigger
  25567. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25568. if (combineArray === void 0) { combineArray = null; }
  25569. if (parsedAction.detached)
  25570. return;
  25571. var parameters = new Array();
  25572. var target = null;
  25573. var propertyPath = null;
  25574. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25575. // Parameters
  25576. if (parsedAction.type === 2)
  25577. parameters.push(actionManager);
  25578. else
  25579. parameters.push(trigger);
  25580. if (combine) {
  25581. var actions = new Array();
  25582. for (var j = 0; j < parsedAction.combine.length; j++) {
  25583. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25584. }
  25585. parameters.push(actions);
  25586. }
  25587. else {
  25588. for (var i = 0; i < parsedAction.properties.length; i++) {
  25589. var value = parsedAction.properties[i].value;
  25590. var name = parsedAction.properties[i].name;
  25591. var targetType = parsedAction.properties[i].targetType;
  25592. if (name === "target")
  25593. if (targetType !== null && targetType === "SceneProperties")
  25594. value = target = scene;
  25595. else
  25596. value = target = scene.getNodeByName(value);
  25597. else if (name === "parent")
  25598. value = scene.getNodeByName(value);
  25599. else if (name === "sound")
  25600. value = scene.getSoundByName(value);
  25601. else if (name !== "propertyPath") {
  25602. if (parsedAction.type === 2 && name === "operator")
  25603. value = BABYLON.ValueCondition[value];
  25604. else
  25605. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25606. }
  25607. else {
  25608. propertyPath = value;
  25609. }
  25610. parameters.push(value);
  25611. }
  25612. }
  25613. if (combineArray === null) {
  25614. parameters.push(condition);
  25615. }
  25616. else {
  25617. parameters.push(null);
  25618. }
  25619. // If interpolate value action
  25620. if (parsedAction.name === "InterpolateValueAction") {
  25621. var param = parameters[parameters.length - 2];
  25622. parameters[parameters.length - 1] = param;
  25623. parameters[parameters.length - 2] = condition;
  25624. }
  25625. // Action or condition(s) and not CombineAction
  25626. var newAction = instanciate(parsedAction.name, parameters);
  25627. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25628. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25629. if (action)
  25630. action.then(nothing);
  25631. else
  25632. actionManager.registerAction(nothing);
  25633. action = nothing;
  25634. }
  25635. if (combineArray === null) {
  25636. if (newAction instanceof BABYLON.Condition) {
  25637. condition = newAction;
  25638. newAction = action;
  25639. }
  25640. else {
  25641. condition = null;
  25642. if (action)
  25643. action.then(newAction);
  25644. else
  25645. actionManager.registerAction(newAction);
  25646. }
  25647. }
  25648. else {
  25649. combineArray.push(newAction);
  25650. }
  25651. for (var i = 0; i < parsedAction.children.length; i++)
  25652. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25653. };
  25654. // triggers
  25655. for (var i = 0; i < parsedActions.children.length; i++) {
  25656. var triggerParams;
  25657. var trigger = parsedActions.children[i];
  25658. if (trigger.properties.length > 0) {
  25659. var param = trigger.properties[0].value;
  25660. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25661. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25662. }
  25663. else
  25664. triggerParams = BABYLON.ActionManager[trigger.name];
  25665. for (var j = 0; j < trigger.children.length; j++) {
  25666. if (!trigger.detached)
  25667. traverse(trigger.children[j], triggerParams, null, null);
  25668. }
  25669. }
  25670. };
  25671. // Statics
  25672. ActionManager._NothingTrigger = 0;
  25673. ActionManager._OnPickTrigger = 1;
  25674. ActionManager._OnLeftPickTrigger = 2;
  25675. ActionManager._OnRightPickTrigger = 3;
  25676. ActionManager._OnCenterPickTrigger = 4;
  25677. ActionManager._OnPointerOverTrigger = 5;
  25678. ActionManager._OnPointerOutTrigger = 6;
  25679. ActionManager._OnEveryFrameTrigger = 7;
  25680. ActionManager._OnIntersectionEnterTrigger = 8;
  25681. ActionManager._OnIntersectionExitTrigger = 9;
  25682. ActionManager._OnKeyDownTrigger = 10;
  25683. ActionManager._OnKeyUpTrigger = 11;
  25684. ActionManager._OnPickUpTrigger = 12;
  25685. return ActionManager;
  25686. })();
  25687. BABYLON.ActionManager = ActionManager;
  25688. })(BABYLON || (BABYLON = {}));
  25689. var BABYLON;
  25690. (function (BABYLON) {
  25691. var InterpolateValueAction = (function (_super) {
  25692. __extends(InterpolateValueAction, _super);
  25693. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25694. if (duration === void 0) { duration = 1000; }
  25695. _super.call(this, triggerOptions, condition);
  25696. this.propertyPath = propertyPath;
  25697. this.value = value;
  25698. this.duration = duration;
  25699. this.stopOtherAnimations = stopOtherAnimations;
  25700. this.onInterpolationDone = onInterpolationDone;
  25701. this._target = target;
  25702. }
  25703. InterpolateValueAction.prototype._prepare = function () {
  25704. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25705. this._property = this._getProperty(this.propertyPath);
  25706. };
  25707. InterpolateValueAction.prototype.execute = function () {
  25708. var scene = this._actionManager.getScene();
  25709. var keys = [
  25710. {
  25711. frame: 0,
  25712. value: this._target[this._property]
  25713. }, {
  25714. frame: 100,
  25715. value: this.value
  25716. }
  25717. ];
  25718. var dataType;
  25719. if (typeof this.value === "number") {
  25720. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25721. }
  25722. else if (this.value instanceof BABYLON.Color3) {
  25723. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25724. }
  25725. else if (this.value instanceof BABYLON.Vector3) {
  25726. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25727. }
  25728. else if (this.value instanceof BABYLON.Matrix) {
  25729. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25730. }
  25731. else if (this.value instanceof BABYLON.Quaternion) {
  25732. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25733. }
  25734. else {
  25735. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25736. return;
  25737. }
  25738. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25739. animation.setKeys(keys);
  25740. if (this.stopOtherAnimations) {
  25741. scene.stopAnimation(this._target);
  25742. }
  25743. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25744. };
  25745. return InterpolateValueAction;
  25746. })(BABYLON.Action);
  25747. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25748. })(BABYLON || (BABYLON = {}));
  25749. var BABYLON;
  25750. (function (BABYLON) {
  25751. var SwitchBooleanAction = (function (_super) {
  25752. __extends(SwitchBooleanAction, _super);
  25753. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25754. _super.call(this, triggerOptions, condition);
  25755. this.propertyPath = propertyPath;
  25756. this._target = target;
  25757. }
  25758. SwitchBooleanAction.prototype._prepare = function () {
  25759. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25760. this._property = this._getProperty(this.propertyPath);
  25761. };
  25762. SwitchBooleanAction.prototype.execute = function () {
  25763. this._target[this._property] = !this._target[this._property];
  25764. };
  25765. return SwitchBooleanAction;
  25766. })(BABYLON.Action);
  25767. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25768. var SetStateAction = (function (_super) {
  25769. __extends(SetStateAction, _super);
  25770. function SetStateAction(triggerOptions, target, value, condition) {
  25771. _super.call(this, triggerOptions, condition);
  25772. this.value = value;
  25773. this._target = target;
  25774. }
  25775. SetStateAction.prototype.execute = function () {
  25776. this._target.state = this.value;
  25777. };
  25778. return SetStateAction;
  25779. })(BABYLON.Action);
  25780. BABYLON.SetStateAction = SetStateAction;
  25781. var SetValueAction = (function (_super) {
  25782. __extends(SetValueAction, _super);
  25783. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25784. _super.call(this, triggerOptions, condition);
  25785. this.propertyPath = propertyPath;
  25786. this.value = value;
  25787. this._target = target;
  25788. }
  25789. SetValueAction.prototype._prepare = function () {
  25790. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25791. this._property = this._getProperty(this.propertyPath);
  25792. };
  25793. SetValueAction.prototype.execute = function () {
  25794. this._target[this._property] = this.value;
  25795. };
  25796. return SetValueAction;
  25797. })(BABYLON.Action);
  25798. BABYLON.SetValueAction = SetValueAction;
  25799. var IncrementValueAction = (function (_super) {
  25800. __extends(IncrementValueAction, _super);
  25801. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25802. _super.call(this, triggerOptions, condition);
  25803. this.propertyPath = propertyPath;
  25804. this.value = value;
  25805. this._target = target;
  25806. }
  25807. IncrementValueAction.prototype._prepare = function () {
  25808. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25809. this._property = this._getProperty(this.propertyPath);
  25810. if (typeof this._target[this._property] !== "number") {
  25811. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25812. }
  25813. };
  25814. IncrementValueAction.prototype.execute = function () {
  25815. this._target[this._property] += this.value;
  25816. };
  25817. return IncrementValueAction;
  25818. })(BABYLON.Action);
  25819. BABYLON.IncrementValueAction = IncrementValueAction;
  25820. var PlayAnimationAction = (function (_super) {
  25821. __extends(PlayAnimationAction, _super);
  25822. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25823. _super.call(this, triggerOptions, condition);
  25824. this.from = from;
  25825. this.to = to;
  25826. this.loop = loop;
  25827. this._target = target;
  25828. }
  25829. PlayAnimationAction.prototype._prepare = function () {
  25830. };
  25831. PlayAnimationAction.prototype.execute = function () {
  25832. var scene = this._actionManager.getScene();
  25833. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25834. };
  25835. return PlayAnimationAction;
  25836. })(BABYLON.Action);
  25837. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25838. var StopAnimationAction = (function (_super) {
  25839. __extends(StopAnimationAction, _super);
  25840. function StopAnimationAction(triggerOptions, target, condition) {
  25841. _super.call(this, triggerOptions, condition);
  25842. this._target = target;
  25843. }
  25844. StopAnimationAction.prototype._prepare = function () {
  25845. };
  25846. StopAnimationAction.prototype.execute = function () {
  25847. var scene = this._actionManager.getScene();
  25848. scene.stopAnimation(this._target);
  25849. };
  25850. return StopAnimationAction;
  25851. })(BABYLON.Action);
  25852. BABYLON.StopAnimationAction = StopAnimationAction;
  25853. var DoNothingAction = (function (_super) {
  25854. __extends(DoNothingAction, _super);
  25855. function DoNothingAction(triggerOptions, condition) {
  25856. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25857. _super.call(this, triggerOptions, condition);
  25858. }
  25859. DoNothingAction.prototype.execute = function () {
  25860. };
  25861. return DoNothingAction;
  25862. })(BABYLON.Action);
  25863. BABYLON.DoNothingAction = DoNothingAction;
  25864. var CombineAction = (function (_super) {
  25865. __extends(CombineAction, _super);
  25866. function CombineAction(triggerOptions, children, condition) {
  25867. _super.call(this, triggerOptions, condition);
  25868. this.children = children;
  25869. }
  25870. CombineAction.prototype._prepare = function () {
  25871. for (var index = 0; index < this.children.length; index++) {
  25872. this.children[index]._actionManager = this._actionManager;
  25873. this.children[index]._prepare();
  25874. }
  25875. };
  25876. CombineAction.prototype.execute = function (evt) {
  25877. for (var index = 0; index < this.children.length; index++) {
  25878. this.children[index].execute(evt);
  25879. }
  25880. };
  25881. return CombineAction;
  25882. })(BABYLON.Action);
  25883. BABYLON.CombineAction = CombineAction;
  25884. var ExecuteCodeAction = (function (_super) {
  25885. __extends(ExecuteCodeAction, _super);
  25886. function ExecuteCodeAction(triggerOptions, func, condition) {
  25887. _super.call(this, triggerOptions, condition);
  25888. this.func = func;
  25889. }
  25890. ExecuteCodeAction.prototype.execute = function (evt) {
  25891. this.func(evt);
  25892. };
  25893. return ExecuteCodeAction;
  25894. })(BABYLON.Action);
  25895. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25896. var SetParentAction = (function (_super) {
  25897. __extends(SetParentAction, _super);
  25898. function SetParentAction(triggerOptions, target, parent, condition) {
  25899. _super.call(this, triggerOptions, condition);
  25900. this._target = target;
  25901. this._parent = parent;
  25902. }
  25903. SetParentAction.prototype._prepare = function () {
  25904. };
  25905. SetParentAction.prototype.execute = function () {
  25906. if (this._target.parent === this._parent) {
  25907. return;
  25908. }
  25909. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25910. invertParentWorldMatrix.invert();
  25911. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25912. this._target.parent = this._parent;
  25913. };
  25914. return SetParentAction;
  25915. })(BABYLON.Action);
  25916. BABYLON.SetParentAction = SetParentAction;
  25917. var PlaySoundAction = (function (_super) {
  25918. __extends(PlaySoundAction, _super);
  25919. function PlaySoundAction(triggerOptions, sound, condition) {
  25920. _super.call(this, triggerOptions, condition);
  25921. this._sound = sound;
  25922. }
  25923. PlaySoundAction.prototype._prepare = function () {
  25924. };
  25925. PlaySoundAction.prototype.execute = function () {
  25926. if (this._sound !== undefined)
  25927. this._sound.play();
  25928. };
  25929. return PlaySoundAction;
  25930. })(BABYLON.Action);
  25931. BABYLON.PlaySoundAction = PlaySoundAction;
  25932. var StopSoundAction = (function (_super) {
  25933. __extends(StopSoundAction, _super);
  25934. function StopSoundAction(triggerOptions, sound, condition) {
  25935. _super.call(this, triggerOptions, condition);
  25936. this._sound = sound;
  25937. }
  25938. StopSoundAction.prototype._prepare = function () {
  25939. };
  25940. StopSoundAction.prototype.execute = function () {
  25941. if (this._sound !== undefined)
  25942. this._sound.stop();
  25943. };
  25944. return StopSoundAction;
  25945. })(BABYLON.Action);
  25946. BABYLON.StopSoundAction = StopSoundAction;
  25947. })(BABYLON || (BABYLON = {}));
  25948. var BABYLON;
  25949. (function (BABYLON) {
  25950. var Geometry = (function () {
  25951. function Geometry(id, scene, vertexData, updatable, mesh) {
  25952. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25953. this._totalVertices = 0;
  25954. this._isDisposed = false;
  25955. this.id = id;
  25956. this._engine = scene.getEngine();
  25957. this._meshes = [];
  25958. this._scene = scene;
  25959. //Init vertex buffer cache
  25960. this._vertexBuffers = {};
  25961. this._indices = [];
  25962. // vertexData
  25963. if (vertexData) {
  25964. this.setAllVerticesData(vertexData, updatable);
  25965. }
  25966. else {
  25967. this._totalVertices = 0;
  25968. this._indices = [];
  25969. }
  25970. // applyToMesh
  25971. if (mesh) {
  25972. this.applyToMesh(mesh);
  25973. mesh.computeWorldMatrix(true);
  25974. }
  25975. }
  25976. Object.defineProperty(Geometry.prototype, "extend", {
  25977. get: function () {
  25978. return this._extend;
  25979. },
  25980. enumerable: true,
  25981. configurable: true
  25982. });
  25983. Geometry.prototype.getScene = function () {
  25984. return this._scene;
  25985. };
  25986. Geometry.prototype.getEngine = function () {
  25987. return this._engine;
  25988. };
  25989. Geometry.prototype.isReady = function () {
  25990. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25991. };
  25992. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25993. vertexData.applyToGeometry(this, updatable);
  25994. this.notifyUpdate();
  25995. };
  25996. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25997. if (this._vertexBuffers[kind]) {
  25998. this._vertexBuffers[kind].dispose();
  25999. }
  26000. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26001. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26002. stride = this._vertexBuffers[kind].getStrideSize();
  26003. this._totalVertices = data.length / stride;
  26004. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26005. var meshes = this._meshes;
  26006. var numOfMeshes = meshes.length;
  26007. for (var index = 0; index < numOfMeshes; index++) {
  26008. var mesh = meshes[index];
  26009. mesh._resetPointsArrayCache();
  26010. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26011. mesh._createGlobalSubMesh();
  26012. mesh.computeWorldMatrix(true);
  26013. }
  26014. }
  26015. this.notifyUpdate(kind);
  26016. };
  26017. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26018. var vertexBuffer = this.getVertexBuffer(kind);
  26019. if (!vertexBuffer) {
  26020. return;
  26021. }
  26022. vertexBuffer.updateDirectly(data, offset);
  26023. this.notifyUpdate(kind);
  26024. };
  26025. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26026. var vertexBuffer = this.getVertexBuffer(kind);
  26027. if (!vertexBuffer) {
  26028. return;
  26029. }
  26030. vertexBuffer.update(data);
  26031. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26032. var stride = vertexBuffer.getStrideSize();
  26033. this._totalVertices = data.length / stride;
  26034. if (updateExtends) {
  26035. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26036. }
  26037. var meshes = this._meshes;
  26038. var numOfMeshes = meshes.length;
  26039. for (var index = 0; index < numOfMeshes; index++) {
  26040. var mesh = meshes[index];
  26041. mesh._resetPointsArrayCache();
  26042. if (updateExtends) {
  26043. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26044. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26045. var subMesh = mesh.subMeshes[subIndex];
  26046. subMesh.refreshBoundingInfo();
  26047. }
  26048. }
  26049. }
  26050. }
  26051. this.notifyUpdate(kind);
  26052. };
  26053. Geometry.prototype.getTotalVertices = function () {
  26054. if (!this.isReady()) {
  26055. return 0;
  26056. }
  26057. return this._totalVertices;
  26058. };
  26059. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26060. var vertexBuffer = this.getVertexBuffer(kind);
  26061. if (!vertexBuffer) {
  26062. return null;
  26063. }
  26064. var orig = vertexBuffer.getData();
  26065. if (!copyWhenShared || this._meshes.length === 1) {
  26066. return orig;
  26067. }
  26068. else {
  26069. var len = orig.length;
  26070. var copy = [];
  26071. for (var i = 0; i < len; i++) {
  26072. copy.push(orig[i]);
  26073. }
  26074. return copy;
  26075. }
  26076. };
  26077. Geometry.prototype.getVertexBuffer = function (kind) {
  26078. if (!this.isReady()) {
  26079. return null;
  26080. }
  26081. return this._vertexBuffers[kind];
  26082. };
  26083. Geometry.prototype.getVertexBuffers = function () {
  26084. if (!this.isReady()) {
  26085. return null;
  26086. }
  26087. return this._vertexBuffers;
  26088. };
  26089. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26090. if (!this._vertexBuffers) {
  26091. if (this._delayInfo) {
  26092. return this._delayInfo.indexOf(kind) !== -1;
  26093. }
  26094. return false;
  26095. }
  26096. return this._vertexBuffers[kind] !== undefined;
  26097. };
  26098. Geometry.prototype.getVerticesDataKinds = function () {
  26099. var result = [];
  26100. var kind;
  26101. if (!this._vertexBuffers && this._delayInfo) {
  26102. for (kind in this._delayInfo) {
  26103. result.push(kind);
  26104. }
  26105. }
  26106. else {
  26107. for (kind in this._vertexBuffers) {
  26108. result.push(kind);
  26109. }
  26110. }
  26111. return result;
  26112. };
  26113. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26114. if (this._indexBuffer) {
  26115. this._engine._releaseBuffer(this._indexBuffer);
  26116. }
  26117. this._indices = indices;
  26118. if (this._meshes.length !== 0 && this._indices) {
  26119. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26120. }
  26121. if (totalVertices !== undefined) {
  26122. this._totalVertices = totalVertices;
  26123. }
  26124. var meshes = this._meshes;
  26125. var numOfMeshes = meshes.length;
  26126. for (var index = 0; index < numOfMeshes; index++) {
  26127. meshes[index]._createGlobalSubMesh();
  26128. }
  26129. this.notifyUpdate();
  26130. };
  26131. Geometry.prototype.getTotalIndices = function () {
  26132. if (!this.isReady()) {
  26133. return 0;
  26134. }
  26135. return this._indices.length;
  26136. };
  26137. Geometry.prototype.getIndices = function (copyWhenShared) {
  26138. if (!this.isReady()) {
  26139. return null;
  26140. }
  26141. var orig = this._indices;
  26142. if (!copyWhenShared || this._meshes.length === 1) {
  26143. return orig;
  26144. }
  26145. else {
  26146. var len = orig.length;
  26147. var copy = [];
  26148. for (var i = 0; i < len; i++) {
  26149. copy.push(orig[i]);
  26150. }
  26151. return copy;
  26152. }
  26153. };
  26154. Geometry.prototype.getIndexBuffer = function () {
  26155. if (!this.isReady()) {
  26156. return null;
  26157. }
  26158. return this._indexBuffer;
  26159. };
  26160. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26161. var meshes = this._meshes;
  26162. var index = meshes.indexOf(mesh);
  26163. if (index === -1) {
  26164. return;
  26165. }
  26166. for (var kind in this._vertexBuffers) {
  26167. this._vertexBuffers[kind].dispose();
  26168. }
  26169. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26170. this._indexBuffer = null;
  26171. }
  26172. meshes.splice(index, 1);
  26173. mesh._geometry = null;
  26174. if (meshes.length === 0 && shouldDispose) {
  26175. this.dispose();
  26176. }
  26177. };
  26178. Geometry.prototype.applyToMesh = function (mesh) {
  26179. if (mesh._geometry === this) {
  26180. return;
  26181. }
  26182. var previousGeometry = mesh._geometry;
  26183. if (previousGeometry) {
  26184. previousGeometry.releaseForMesh(mesh);
  26185. }
  26186. var meshes = this._meshes;
  26187. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26188. mesh._geometry = this;
  26189. this._scene.pushGeometry(this);
  26190. meshes.push(mesh);
  26191. if (this.isReady()) {
  26192. this._applyToMesh(mesh);
  26193. }
  26194. else {
  26195. mesh._boundingInfo = this._boundingInfo;
  26196. }
  26197. };
  26198. Geometry.prototype._applyToMesh = function (mesh) {
  26199. var numOfMeshes = this._meshes.length;
  26200. // vertexBuffers
  26201. for (var kind in this._vertexBuffers) {
  26202. if (numOfMeshes === 1) {
  26203. this._vertexBuffers[kind].create();
  26204. }
  26205. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26206. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26207. mesh._resetPointsArrayCache();
  26208. if (!this._extend) {
  26209. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26210. }
  26211. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26212. mesh._createGlobalSubMesh();
  26213. //bounding info was just created again, world matrix should be applied again.
  26214. mesh._updateBoundingInfo();
  26215. }
  26216. }
  26217. // indexBuffer
  26218. if (numOfMeshes === 1 && this._indices) {
  26219. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26220. }
  26221. if (this._indexBuffer) {
  26222. this._indexBuffer.references = numOfMeshes;
  26223. }
  26224. };
  26225. Geometry.prototype.notifyUpdate = function (kind) {
  26226. if (this.onGeometryUpdated) {
  26227. this.onGeometryUpdated(this, kind);
  26228. }
  26229. };
  26230. Geometry.prototype.load = function (scene, onLoaded) {
  26231. var _this = this;
  26232. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26233. return;
  26234. }
  26235. if (this.isReady()) {
  26236. if (onLoaded) {
  26237. onLoaded();
  26238. }
  26239. return;
  26240. }
  26241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26242. scene._addPendingData(this);
  26243. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26244. _this._delayLoadingFunction(JSON.parse(data), _this);
  26245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26246. _this._delayInfo = [];
  26247. scene._removePendingData(_this);
  26248. var meshes = _this._meshes;
  26249. var numOfMeshes = meshes.length;
  26250. for (var index = 0; index < numOfMeshes; index++) {
  26251. _this._applyToMesh(meshes[index]);
  26252. }
  26253. if (onLoaded) {
  26254. onLoaded();
  26255. }
  26256. }, function () { }, scene.database);
  26257. };
  26258. Geometry.prototype.isDisposed = function () {
  26259. return this._isDisposed;
  26260. };
  26261. Geometry.prototype.dispose = function () {
  26262. var meshes = this._meshes;
  26263. var numOfMeshes = meshes.length;
  26264. var index;
  26265. for (index = 0; index < numOfMeshes; index++) {
  26266. this.releaseForMesh(meshes[index]);
  26267. }
  26268. this._meshes = [];
  26269. for (var kind in this._vertexBuffers) {
  26270. this._vertexBuffers[kind].dispose();
  26271. }
  26272. this._vertexBuffers = [];
  26273. this._totalVertices = 0;
  26274. if (this._indexBuffer) {
  26275. this._engine._releaseBuffer(this._indexBuffer);
  26276. }
  26277. this._indexBuffer = null;
  26278. this._indices = [];
  26279. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26280. this.delayLoadingFile = null;
  26281. this._delayLoadingFunction = null;
  26282. this._delayInfo = [];
  26283. this._boundingInfo = null;
  26284. this._scene.removeGeometry(this);
  26285. this._isDisposed = true;
  26286. };
  26287. Geometry.prototype.copy = function (id) {
  26288. var vertexData = new BABYLON.VertexData();
  26289. vertexData.indices = [];
  26290. var indices = this.getIndices();
  26291. for (var index = 0; index < indices.length; index++) {
  26292. vertexData.indices.push(indices[index]);
  26293. }
  26294. var updatable = false;
  26295. var stopChecking = false;
  26296. var kind;
  26297. for (kind in this._vertexBuffers) {
  26298. // using slice() to make a copy of the array and not just reference it
  26299. var data = this.getVerticesData(kind);
  26300. if (data instanceof Float32Array) {
  26301. vertexData.set(new Float32Array(data), kind);
  26302. }
  26303. else {
  26304. vertexData.set(data.slice(0), kind);
  26305. }
  26306. if (!stopChecking) {
  26307. updatable = this.getVertexBuffer(kind).isUpdatable();
  26308. stopChecking = !updatable;
  26309. }
  26310. }
  26311. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26312. geometry.delayLoadState = this.delayLoadState;
  26313. geometry.delayLoadingFile = this.delayLoadingFile;
  26314. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26315. for (kind in this._delayInfo) {
  26316. geometry._delayInfo = geometry._delayInfo || [];
  26317. geometry._delayInfo.push(kind);
  26318. }
  26319. // Bounding info
  26320. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26321. return geometry;
  26322. };
  26323. Geometry.prototype.serialize = function () {
  26324. var serializationObject = {};
  26325. serializationObject.id = this.id;
  26326. if (BABYLON.Tags.HasTags(this)) {
  26327. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26328. }
  26329. return serializationObject;
  26330. };
  26331. Geometry.prototype.serializeVerticeData = function () {
  26332. var serializationObject = this.serialize();
  26333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26334. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26335. }
  26336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26337. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26338. }
  26339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26340. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26341. }
  26342. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26343. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26344. }
  26345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26346. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26347. }
  26348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26349. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26350. }
  26351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26352. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26353. }
  26354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26355. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26356. }
  26357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26358. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26359. }
  26360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26361. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26362. serializationObject.matricesIndices._isExpanded = true;
  26363. }
  26364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26365. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26366. }
  26367. serializationObject.indices = this.getIndices();
  26368. return serializationObject;
  26369. };
  26370. // Statics
  26371. Geometry.ExtractFromMesh = function (mesh, id) {
  26372. var geometry = mesh._geometry;
  26373. if (!geometry) {
  26374. return null;
  26375. }
  26376. return geometry.copy(id);
  26377. };
  26378. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26379. // be aware Math.random() could cause collisions
  26380. Geometry.RandomId = function () {
  26381. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26382. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26383. return v.toString(16);
  26384. });
  26385. };
  26386. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26387. var scene = mesh.getScene();
  26388. // Geometry
  26389. var geometryId = parsedGeometry.geometryId;
  26390. if (geometryId) {
  26391. var geometry = scene.getGeometryByID(geometryId);
  26392. if (geometry) {
  26393. geometry.applyToMesh(mesh);
  26394. }
  26395. }
  26396. else if (parsedGeometry instanceof ArrayBuffer) {
  26397. var binaryInfo = mesh._binaryInfo;
  26398. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26399. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26400. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26401. }
  26402. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26403. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26404. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26405. }
  26406. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26407. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26408. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26409. }
  26410. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26411. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26412. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26413. }
  26414. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26415. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26416. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26417. }
  26418. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26419. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26420. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26421. }
  26422. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26423. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26424. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26425. }
  26426. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26427. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26428. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26429. }
  26430. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26431. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26432. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26433. }
  26434. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26435. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26436. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26437. }
  26438. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26439. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26440. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26441. }
  26442. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26443. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26444. mesh.setIndices(indicesData);
  26445. }
  26446. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26447. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26448. mesh.subMeshes = [];
  26449. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26450. var materialIndex = subMeshesData[(i * 5) + 0];
  26451. var verticesStart = subMeshesData[(i * 5) + 1];
  26452. var verticesCount = subMeshesData[(i * 5) + 2];
  26453. var indexStart = subMeshesData[(i * 5) + 3];
  26454. var indexCount = subMeshesData[(i * 5) + 4];
  26455. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26456. }
  26457. }
  26458. }
  26459. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26460. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26461. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26462. if (parsedGeometry.uvs) {
  26463. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26464. }
  26465. if (parsedGeometry.uvs2) {
  26466. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26467. }
  26468. if (parsedGeometry.uvs3) {
  26469. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26470. }
  26471. if (parsedGeometry.uvs4) {
  26472. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26473. }
  26474. if (parsedGeometry.uvs5) {
  26475. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26476. }
  26477. if (parsedGeometry.uvs6) {
  26478. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26479. }
  26480. if (parsedGeometry.colors) {
  26481. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26482. }
  26483. if (parsedGeometry.matricesIndices) {
  26484. if (!parsedGeometry.matricesIndices._isExpanded) {
  26485. var floatIndices = [];
  26486. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26487. var matricesIndex = parsedGeometry.matricesIndices[i];
  26488. floatIndices.push(matricesIndex & 0x000000FF);
  26489. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26490. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26491. floatIndices.push(matricesIndex >> 24);
  26492. }
  26493. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26494. }
  26495. else {
  26496. delete parsedGeometry.matricesIndices._isExpanded;
  26497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26498. }
  26499. }
  26500. if (parsedGeometry.matricesIndicesExtra) {
  26501. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26502. var floatIndices = [];
  26503. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26504. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26505. floatIndices.push(matricesIndex & 0x000000FF);
  26506. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26507. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26508. floatIndices.push(matricesIndex >> 24);
  26509. }
  26510. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26511. }
  26512. else {
  26513. delete parsedGeometry.matricesIndices._isExpanded;
  26514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26515. }
  26516. }
  26517. if (parsedGeometry.matricesWeights) {
  26518. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26519. }
  26520. if (parsedGeometry.matricesWeightsExtra) {
  26521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26522. }
  26523. mesh.setIndices(parsedGeometry.indices);
  26524. }
  26525. // SubMeshes
  26526. if (parsedGeometry.subMeshes) {
  26527. mesh.subMeshes = [];
  26528. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26529. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26530. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26531. }
  26532. }
  26533. // Flat shading
  26534. if (mesh._shouldGenerateFlatShading) {
  26535. mesh.convertToFlatShadedMesh();
  26536. delete mesh._shouldGenerateFlatShading;
  26537. }
  26538. // Update
  26539. mesh.computeWorldMatrix(true);
  26540. // Octree
  26541. if (scene['_selectionOctree']) {
  26542. scene['_selectionOctree'].addMesh(mesh);
  26543. }
  26544. };
  26545. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26546. if (scene.getGeometryByID(parsedVertexData.id)) {
  26547. return null; // null since geometry could be something else than a box...
  26548. }
  26549. var geometry = new Geometry(parsedVertexData.id, scene);
  26550. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26551. if (parsedVertexData.delayLoadingFile) {
  26552. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26553. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26554. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26555. geometry._delayInfo = [];
  26556. if (parsedVertexData.hasUVs) {
  26557. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26558. }
  26559. if (parsedVertexData.hasUVs2) {
  26560. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26561. }
  26562. if (parsedVertexData.hasUVs3) {
  26563. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26564. }
  26565. if (parsedVertexData.hasUVs4) {
  26566. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26567. }
  26568. if (parsedVertexData.hasUVs5) {
  26569. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26570. }
  26571. if (parsedVertexData.hasUVs6) {
  26572. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26573. }
  26574. if (parsedVertexData.hasColors) {
  26575. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26576. }
  26577. if (parsedVertexData.hasMatricesIndices) {
  26578. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26579. }
  26580. if (parsedVertexData.hasMatricesWeights) {
  26581. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26582. }
  26583. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26584. }
  26585. else {
  26586. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26587. }
  26588. scene.pushGeometry(geometry, true);
  26589. return geometry;
  26590. };
  26591. return Geometry;
  26592. })();
  26593. BABYLON.Geometry = Geometry;
  26594. /////// Primitives //////////////////////////////////////////////
  26595. var Geometry;
  26596. (function (Geometry) {
  26597. var Primitives;
  26598. (function (Primitives) {
  26599. /// Abstract class
  26600. var _Primitive = (function (_super) {
  26601. __extends(_Primitive, _super);
  26602. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26603. this._beingRegenerated = true;
  26604. this._canBeRegenerated = canBeRegenerated;
  26605. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26606. this._beingRegenerated = false;
  26607. }
  26608. _Primitive.prototype.canBeRegenerated = function () {
  26609. return this._canBeRegenerated;
  26610. };
  26611. _Primitive.prototype.regenerate = function () {
  26612. if (!this._canBeRegenerated) {
  26613. return;
  26614. }
  26615. this._beingRegenerated = true;
  26616. this.setAllVerticesData(this._regenerateVertexData(), false);
  26617. this._beingRegenerated = false;
  26618. };
  26619. _Primitive.prototype.asNewGeometry = function (id) {
  26620. return _super.prototype.copy.call(this, id);
  26621. };
  26622. // overrides
  26623. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26624. if (!this._beingRegenerated) {
  26625. return;
  26626. }
  26627. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26628. };
  26629. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26630. if (!this._beingRegenerated) {
  26631. return;
  26632. }
  26633. _super.prototype.setVerticesData.call(this, kind, data, false);
  26634. };
  26635. // to override
  26636. // protected
  26637. _Primitive.prototype._regenerateVertexData = function () {
  26638. throw new Error("Abstract method");
  26639. };
  26640. _Primitive.prototype.copy = function (id) {
  26641. throw new Error("Must be overriden in sub-classes.");
  26642. };
  26643. _Primitive.prototype.serialize = function () {
  26644. var serializationObject = _super.prototype.serialize.call(this);
  26645. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26646. return serializationObject;
  26647. };
  26648. return _Primitive;
  26649. })(Geometry);
  26650. Primitives._Primitive = _Primitive;
  26651. var Ribbon = (function (_super) {
  26652. __extends(Ribbon, _super);
  26653. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26654. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26655. this.pathArray = pathArray;
  26656. this.closeArray = closeArray;
  26657. this.closePath = closePath;
  26658. this.offset = offset;
  26659. this.side = side;
  26660. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26661. }
  26662. Ribbon.prototype._regenerateVertexData = function () {
  26663. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26664. };
  26665. Ribbon.prototype.copy = function (id) {
  26666. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26667. };
  26668. return Ribbon;
  26669. })(_Primitive);
  26670. Primitives.Ribbon = Ribbon;
  26671. var Box = (function (_super) {
  26672. __extends(Box, _super);
  26673. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26674. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26675. this.size = size;
  26676. this.side = side;
  26677. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26678. }
  26679. Box.prototype._regenerateVertexData = function () {
  26680. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26681. };
  26682. Box.prototype.copy = function (id) {
  26683. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26684. };
  26685. Box.prototype.serialize = function () {
  26686. var serializationObject = _super.prototype.serialize.call(this);
  26687. serializationObject.size = this.size;
  26688. return serializationObject;
  26689. };
  26690. Box.Parse = function (parsedBox, scene) {
  26691. if (scene.getGeometryByID(parsedBox.id)) {
  26692. return null; // null since geometry could be something else than a box...
  26693. }
  26694. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26695. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26696. scene.pushGeometry(box, true);
  26697. return box;
  26698. };
  26699. return Box;
  26700. })(_Primitive);
  26701. Primitives.Box = Box;
  26702. var Sphere = (function (_super) {
  26703. __extends(Sphere, _super);
  26704. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26706. this.segments = segments;
  26707. this.diameter = diameter;
  26708. this.side = side;
  26709. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26710. }
  26711. Sphere.prototype._regenerateVertexData = function () {
  26712. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26713. };
  26714. Sphere.prototype.copy = function (id) {
  26715. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26716. };
  26717. Sphere.prototype.serialize = function () {
  26718. var serializationObject = _super.prototype.serialize.call(this);
  26719. serializationObject.segments = this.segments;
  26720. serializationObject.diameter = this.diameter;
  26721. return serializationObject;
  26722. };
  26723. Sphere.Parse = function (parsedSphere, scene) {
  26724. if (scene.getGeometryByID(parsedSphere.id)) {
  26725. return null; // null since geometry could be something else than a sphere...
  26726. }
  26727. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26728. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26729. scene.pushGeometry(sphere, true);
  26730. return sphere;
  26731. };
  26732. return Sphere;
  26733. })(_Primitive);
  26734. Primitives.Sphere = Sphere;
  26735. var Disc = (function (_super) {
  26736. __extends(Disc, _super);
  26737. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26739. this.radius = radius;
  26740. this.tessellation = tessellation;
  26741. this.side = side;
  26742. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26743. }
  26744. Disc.prototype._regenerateVertexData = function () {
  26745. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26746. };
  26747. Disc.prototype.copy = function (id) {
  26748. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26749. };
  26750. return Disc;
  26751. })(_Primitive);
  26752. Primitives.Disc = Disc;
  26753. var Cylinder = (function (_super) {
  26754. __extends(Cylinder, _super);
  26755. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26756. if (subdivisions === void 0) { subdivisions = 1; }
  26757. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26758. this.height = height;
  26759. this.diameterTop = diameterTop;
  26760. this.diameterBottom = diameterBottom;
  26761. this.tessellation = tessellation;
  26762. this.subdivisions = subdivisions;
  26763. this.side = side;
  26764. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26765. }
  26766. Cylinder.prototype._regenerateVertexData = function () {
  26767. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26768. };
  26769. Cylinder.prototype.copy = function (id) {
  26770. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26771. };
  26772. Cylinder.prototype.serialize = function () {
  26773. var serializationObject = _super.prototype.serialize.call(this);
  26774. serializationObject.height = this.height;
  26775. serializationObject.diameterTop = this.diameterTop;
  26776. serializationObject.diameterBottom = this.diameterBottom;
  26777. serializationObject.tessellation = this.tessellation;
  26778. return serializationObject;
  26779. };
  26780. Cylinder.Parse = function (parsedCylinder, scene) {
  26781. if (scene.getGeometryByID(parsedCylinder.id)) {
  26782. return null; // null since geometry could be something else than a cylinder...
  26783. }
  26784. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26785. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26786. scene.pushGeometry(cylinder, true);
  26787. return cylinder;
  26788. };
  26789. return Cylinder;
  26790. })(_Primitive);
  26791. Primitives.Cylinder = Cylinder;
  26792. var Torus = (function (_super) {
  26793. __extends(Torus, _super);
  26794. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26796. this.diameter = diameter;
  26797. this.thickness = thickness;
  26798. this.tessellation = tessellation;
  26799. this.side = side;
  26800. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26801. }
  26802. Torus.prototype._regenerateVertexData = function () {
  26803. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26804. };
  26805. Torus.prototype.copy = function (id) {
  26806. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26807. };
  26808. Torus.prototype.serialize = function () {
  26809. var serializationObject = _super.prototype.serialize.call(this);
  26810. serializationObject.diameter = this.diameter;
  26811. serializationObject.thickness = this.thickness;
  26812. serializationObject.tessellation = this.tessellation;
  26813. return serializationObject;
  26814. };
  26815. Torus.Parse = function (parsedTorus, scene) {
  26816. if (scene.getGeometryByID(parsedTorus.id)) {
  26817. return null; // null since geometry could be something else than a torus...
  26818. }
  26819. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26820. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26821. scene.pushGeometry(torus, true);
  26822. return torus;
  26823. };
  26824. return Torus;
  26825. })(_Primitive);
  26826. Primitives.Torus = Torus;
  26827. var Ground = (function (_super) {
  26828. __extends(Ground, _super);
  26829. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26830. this.width = width;
  26831. this.height = height;
  26832. this.subdivisions = subdivisions;
  26833. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26834. }
  26835. Ground.prototype._regenerateVertexData = function () {
  26836. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26837. };
  26838. Ground.prototype.copy = function (id) {
  26839. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26840. };
  26841. Ground.prototype.serialize = function () {
  26842. var serializationObject = _super.prototype.serialize.call(this);
  26843. serializationObject.width = this.width;
  26844. serializationObject.height = this.height;
  26845. serializationObject.subdivisions = this.subdivisions;
  26846. return serializationObject;
  26847. };
  26848. Ground.Parse = function (parsedGround, scene) {
  26849. if (scene.getGeometryByID(parsedGround.id)) {
  26850. return null; // null since geometry could be something else than a ground...
  26851. }
  26852. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26853. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26854. scene.pushGeometry(ground, true);
  26855. return ground;
  26856. };
  26857. return Ground;
  26858. })(_Primitive);
  26859. Primitives.Ground = Ground;
  26860. var TiledGround = (function (_super) {
  26861. __extends(TiledGround, _super);
  26862. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26863. this.xmin = xmin;
  26864. this.zmin = zmin;
  26865. this.xmax = xmax;
  26866. this.zmax = zmax;
  26867. this.subdivisions = subdivisions;
  26868. this.precision = precision;
  26869. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26870. }
  26871. TiledGround.prototype._regenerateVertexData = function () {
  26872. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26873. };
  26874. TiledGround.prototype.copy = function (id) {
  26875. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26876. };
  26877. return TiledGround;
  26878. })(_Primitive);
  26879. Primitives.TiledGround = TiledGround;
  26880. var Plane = (function (_super) {
  26881. __extends(Plane, _super);
  26882. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26884. this.size = size;
  26885. this.side = side;
  26886. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26887. }
  26888. Plane.prototype._regenerateVertexData = function () {
  26889. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26890. };
  26891. Plane.prototype.copy = function (id) {
  26892. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26893. };
  26894. Plane.prototype.serialize = function () {
  26895. var serializationObject = _super.prototype.serialize.call(this);
  26896. serializationObject.size = this.size;
  26897. return serializationObject;
  26898. };
  26899. Plane.Parse = function (parsedPlane, scene) {
  26900. if (scene.getGeometryByID(parsedPlane.id)) {
  26901. return null; // null since geometry could be something else than a ground...
  26902. }
  26903. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26904. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26905. scene.pushGeometry(plane, true);
  26906. return plane;
  26907. };
  26908. return Plane;
  26909. })(_Primitive);
  26910. Primitives.Plane = Plane;
  26911. var TorusKnot = (function (_super) {
  26912. __extends(TorusKnot, _super);
  26913. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26914. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26915. this.radius = radius;
  26916. this.tube = tube;
  26917. this.radialSegments = radialSegments;
  26918. this.tubularSegments = tubularSegments;
  26919. this.p = p;
  26920. this.q = q;
  26921. this.side = side;
  26922. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26923. }
  26924. TorusKnot.prototype._regenerateVertexData = function () {
  26925. 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 });
  26926. };
  26927. TorusKnot.prototype.copy = function (id) {
  26928. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26929. };
  26930. TorusKnot.prototype.serialize = function () {
  26931. var serializationObject = _super.prototype.serialize.call(this);
  26932. serializationObject.radius = this.radius;
  26933. serializationObject.tube = this.tube;
  26934. serializationObject.radialSegments = this.radialSegments;
  26935. serializationObject.tubularSegments = this.tubularSegments;
  26936. serializationObject.p = this.p;
  26937. serializationObject.q = this.q;
  26938. return serializationObject;
  26939. };
  26940. ;
  26941. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26942. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26943. return null; // null since geometry could be something else than a ground...
  26944. }
  26945. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26946. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26947. scene.pushGeometry(torusKnot, true);
  26948. return torusKnot;
  26949. };
  26950. return TorusKnot;
  26951. })(_Primitive);
  26952. Primitives.TorusKnot = TorusKnot;
  26953. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26954. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26955. })(BABYLON || (BABYLON = {}));
  26956. var BABYLON;
  26957. (function (BABYLON) {
  26958. var GroundMesh = (function (_super) {
  26959. __extends(GroundMesh, _super);
  26960. function GroundMesh(name, scene) {
  26961. _super.call(this, name, scene);
  26962. this.generateOctree = false;
  26963. this._worldInverse = new BABYLON.Matrix();
  26964. }
  26965. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26966. get: function () {
  26967. return this._subdivisions;
  26968. },
  26969. enumerable: true,
  26970. configurable: true
  26971. });
  26972. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26973. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26974. this._subdivisions = chunksCount;
  26975. this.subdivide(this._subdivisions);
  26976. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26977. };
  26978. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26979. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26980. this.getWorldMatrix().invertToRef(this._worldInverse);
  26981. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26982. var pickInfo = this.intersects(ray);
  26983. if (pickInfo.hit) {
  26984. return pickInfo.pickedPoint.y;
  26985. }
  26986. return 0;
  26987. };
  26988. return GroundMesh;
  26989. })(BABYLON.Mesh);
  26990. BABYLON.GroundMesh = GroundMesh;
  26991. })(BABYLON || (BABYLON = {}));
  26992. var BABYLON;
  26993. (function (BABYLON) {
  26994. var LinesMesh = (function (_super) {
  26995. __extends(LinesMesh, _super);
  26996. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26997. if (parent === void 0) { parent = null; }
  26998. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26999. this.color = new BABYLON.Color3(1, 1, 1);
  27000. this.alpha = 1;
  27001. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27002. attributes: ["position"],
  27003. uniforms: ["worldViewProjection", "color"],
  27004. needAlphaBlending: true
  27005. });
  27006. }
  27007. Object.defineProperty(LinesMesh.prototype, "material", {
  27008. get: function () {
  27009. return this._colorShader;
  27010. },
  27011. enumerable: true,
  27012. configurable: true
  27013. });
  27014. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27015. get: function () {
  27016. return false;
  27017. },
  27018. enumerable: true,
  27019. configurable: true
  27020. });
  27021. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27022. get: function () {
  27023. return false;
  27024. },
  27025. enumerable: true,
  27026. configurable: true
  27027. });
  27028. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27029. var engine = this.getScene().getEngine();
  27030. var indexToBind = this._geometry.getIndexBuffer();
  27031. // VBOs
  27032. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27033. // Color
  27034. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27035. };
  27036. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27037. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27038. return;
  27039. }
  27040. var engine = this.getScene().getEngine();
  27041. // Draw order
  27042. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27043. };
  27044. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27045. return null;
  27046. };
  27047. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27048. this._colorShader.dispose();
  27049. _super.prototype.dispose.call(this, doNotRecurse);
  27050. };
  27051. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27052. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27053. };
  27054. return LinesMesh;
  27055. })(BABYLON.Mesh);
  27056. BABYLON.LinesMesh = LinesMesh;
  27057. })(BABYLON || (BABYLON = {}));
  27058. var BABYLON;
  27059. (function (BABYLON) {
  27060. var DebugLayer = (function () {
  27061. function DebugLayer(scene) {
  27062. var _this = this;
  27063. this._transformationMatrix = BABYLON.Matrix.Identity();
  27064. this._enabled = false;
  27065. this._labelsEnabled = false;
  27066. this._displayStatistics = true;
  27067. this._displayTree = false;
  27068. this._displayLogs = false;
  27069. this._identityMatrix = BABYLON.Matrix.Identity();
  27070. this.axisRatio = 0.02;
  27071. this.accentColor = "orange";
  27072. this._scene = scene;
  27073. this._syncPositions = function () {
  27074. var engine = _this._scene.getEngine();
  27075. var canvasRect = engine.getRenderingCanvasClientRect();
  27076. if (_this._showUI) {
  27077. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27078. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27079. _this._statsDiv.style.width = "400px";
  27080. _this._statsDiv.style.height = "auto";
  27081. _this._statsSubsetDiv.style.maxHeight = "240px";
  27082. _this._optionsDiv.style.left = "0px";
  27083. _this._optionsDiv.style.top = "10px";
  27084. _this._optionsDiv.style.width = "200px";
  27085. _this._optionsDiv.style.height = "auto";
  27086. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27087. _this._logDiv.style.left = "0px";
  27088. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27089. _this._logDiv.style.width = "600px";
  27090. _this._logDiv.style.height = "160px";
  27091. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27092. _this._treeDiv.style.top = "10px";
  27093. _this._treeDiv.style.width = "300px";
  27094. _this._treeDiv.style.height = "auto";
  27095. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27096. }
  27097. _this._globalDiv.style.left = canvasRect.left + "px";
  27098. _this._globalDiv.style.top = canvasRect.top + "px";
  27099. _this._drawingCanvas.style.left = "0px";
  27100. _this._drawingCanvas.style.top = "0px";
  27101. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27102. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27103. var devicePixelRatio = window.devicePixelRatio || 1;
  27104. var context = _this._drawingContext;
  27105. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27106. context.mozBackingStorePixelRatio ||
  27107. context.msBackingStorePixelRatio ||
  27108. context.oBackingStorePixelRatio ||
  27109. context.backingStorePixelRatio || 1;
  27110. _this._ratio = devicePixelRatio / backingStoreRatio;
  27111. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27112. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27113. };
  27114. this._onCanvasClick = function (evt) {
  27115. _this._clickPosition = {
  27116. x: evt.clientX * _this._ratio,
  27117. y: evt.clientY * _this._ratio
  27118. };
  27119. };
  27120. this._syncUI = function () {
  27121. if (_this._showUI) {
  27122. if (_this._displayStatistics) {
  27123. _this._displayStats();
  27124. _this._statsDiv.style.display = "";
  27125. }
  27126. else {
  27127. _this._statsDiv.style.display = "none";
  27128. }
  27129. if (_this._displayLogs) {
  27130. _this._logDiv.style.display = "";
  27131. }
  27132. else {
  27133. _this._logDiv.style.display = "none";
  27134. }
  27135. if (_this._displayTree) {
  27136. _this._treeDiv.style.display = "";
  27137. if (_this._needToRefreshMeshesTree) {
  27138. _this._needToRefreshMeshesTree = false;
  27139. _this._refreshMeshesTreeContent();
  27140. }
  27141. }
  27142. else {
  27143. _this._treeDiv.style.display = "none";
  27144. }
  27145. }
  27146. };
  27147. this._syncData = function () {
  27148. if (_this._labelsEnabled || !_this._showUI) {
  27149. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27150. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27151. var engine = _this._scene.getEngine();
  27152. var viewport = _this._camera.viewport;
  27153. var globalViewport = viewport.toGlobal(engine);
  27154. // Meshes
  27155. var meshes = _this._camera.getActiveMeshes();
  27156. var index;
  27157. var projectedPosition;
  27158. for (index = 0; index < meshes.length; index++) {
  27159. var mesh = meshes.data[index];
  27160. var position = mesh.getBoundingInfo().boundingSphere.center;
  27161. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27162. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27163. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27164. }
  27165. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27166. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27167. }
  27168. }
  27169. // Cameras
  27170. var cameras = _this._scene.cameras;
  27171. for (index = 0; index < cameras.length; index++) {
  27172. var camera = cameras[index];
  27173. if (camera === _this._camera) {
  27174. continue;
  27175. }
  27176. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27177. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27178. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27179. _this._camera.detachControl(engine.getRenderingCanvas());
  27180. _this._camera = camera;
  27181. _this._camera.attachControl(engine.getRenderingCanvas());
  27182. }, function () { return "purple"; });
  27183. }
  27184. }
  27185. // Lights
  27186. var lights = _this._scene.lights;
  27187. for (index = 0; index < lights.length; index++) {
  27188. var light = lights[index];
  27189. if (light.position) {
  27190. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27191. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27192. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27193. light.setEnabled(!light.isEnabled());
  27194. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27195. }
  27196. }
  27197. }
  27198. }
  27199. _this._clickPosition = undefined;
  27200. };
  27201. }
  27202. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27203. while (this._treeSubsetDiv.hasChildNodes()) {
  27204. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27205. }
  27206. // Add meshes
  27207. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27208. sortedArray.sort(function (a, b) {
  27209. if (a.name === b.name) {
  27210. return 0;
  27211. }
  27212. return (a.name > b.name) ? 1 : -1;
  27213. });
  27214. for (var index = 0; index < sortedArray.length; index++) {
  27215. var mesh = sortedArray[index];
  27216. if (!mesh.isEnabled()) {
  27217. continue;
  27218. }
  27219. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27220. m.isVisible = element.checked;
  27221. }, mesh);
  27222. }
  27223. };
  27224. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27225. this._drawingContext.beginPath();
  27226. this._drawingContext.moveTo(zero.x, zero.y);
  27227. this._drawingContext.lineTo(unit.x, unit.y);
  27228. this._drawingContext.strokeStyle = color;
  27229. this._drawingContext.lineWidth = 4;
  27230. this._drawingContext.stroke();
  27231. this._drawingContext.font = "normal 14px Segoe UI";
  27232. this._drawingContext.fillStyle = color;
  27233. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27234. };
  27235. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27236. var position = mesh.getBoundingInfo().boundingSphere.center;
  27237. var worldMatrix = mesh.getWorldMatrix();
  27238. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27239. var unit = (unprojectedVector.subtract(position)).length();
  27240. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27241. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27242. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27243. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27244. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27245. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27246. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27247. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27248. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27249. };
  27250. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27251. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27252. this._drawingContext.font = "normal 12px Segoe UI";
  27253. var textMetrics = this._drawingContext.measureText(text);
  27254. var centerX = projectedPosition.x - textMetrics.width / 2;
  27255. var centerY = projectedPosition.y;
  27256. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27257. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27258. onClick();
  27259. }
  27260. this._drawingContext.beginPath();
  27261. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27262. this._drawingContext.fillStyle = getFillStyle();
  27263. this._drawingContext.globalAlpha = 0.5;
  27264. this._drawingContext.fill();
  27265. this._drawingContext.globalAlpha = 1.0;
  27266. this._drawingContext.strokeStyle = '#FFFFFF';
  27267. this._drawingContext.lineWidth = 1;
  27268. this._drawingContext.stroke();
  27269. this._drawingContext.fillStyle = "#FFFFFF";
  27270. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27271. this._drawingContext.beginPath();
  27272. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27273. this._drawingContext.fill();
  27274. }
  27275. };
  27276. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27277. if (!this._clickPosition) {
  27278. return false;
  27279. }
  27280. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27281. return false;
  27282. }
  27283. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27284. return false;
  27285. }
  27286. return true;
  27287. };
  27288. DebugLayer.prototype.isVisible = function () {
  27289. return this._enabled;
  27290. };
  27291. DebugLayer.prototype.hide = function () {
  27292. if (!this._enabled) {
  27293. return;
  27294. }
  27295. this._enabled = false;
  27296. var engine = this._scene.getEngine();
  27297. this._scene.unregisterBeforeRender(this._syncData);
  27298. this._scene.unregisterAfterRender(this._syncUI);
  27299. this._rootElement.removeChild(this._globalDiv);
  27300. this._scene.forceShowBoundingBoxes = false;
  27301. this._scene.forceWireframe = false;
  27302. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27303. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27304. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27305. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27306. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27307. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27308. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27309. BABYLON.StandardMaterial.LightmapEnabled = true;
  27310. this._scene.shadowsEnabled = true;
  27311. this._scene.particlesEnabled = true;
  27312. this._scene.postProcessesEnabled = true;
  27313. this._scene.collisionsEnabled = true;
  27314. this._scene.lightsEnabled = true;
  27315. this._scene.texturesEnabled = true;
  27316. this._scene.lensFlaresEnabled = true;
  27317. this._scene.proceduralTexturesEnabled = true;
  27318. this._scene.renderTargetsEnabled = true;
  27319. this._scene.probesEnabled = true;
  27320. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27321. };
  27322. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27323. if (showUI === void 0) { showUI = true; }
  27324. if (camera === void 0) { camera = null; }
  27325. if (rootElement === void 0) { rootElement = null; }
  27326. if (this._enabled) {
  27327. return;
  27328. }
  27329. this._enabled = true;
  27330. if (camera) {
  27331. this._camera = camera;
  27332. }
  27333. else {
  27334. this._camera = this._scene.activeCamera;
  27335. }
  27336. this._showUI = showUI;
  27337. var engine = this._scene.getEngine();
  27338. this._globalDiv = document.createElement("div");
  27339. this._rootElement = rootElement || document.body;
  27340. this._rootElement.appendChild(this._globalDiv);
  27341. this._generateDOMelements();
  27342. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27343. this._syncPositions();
  27344. this._scene.registerBeforeRender(this._syncData);
  27345. this._scene.registerAfterRender(this._syncUI);
  27346. };
  27347. DebugLayer.prototype._clearLabels = function () {
  27348. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27349. for (var index = 0; index < this._scene.meshes.length; index++) {
  27350. var mesh = this._scene.meshes[index];
  27351. mesh.renderOverlay = false;
  27352. }
  27353. };
  27354. DebugLayer.prototype._generateheader = function (root, text) {
  27355. var header = document.createElement("div");
  27356. header.innerHTML = text + "&nbsp;";
  27357. header.style.textAlign = "right";
  27358. header.style.width = "100%";
  27359. header.style.color = "white";
  27360. header.style.backgroundColor = "Black";
  27361. header.style.padding = "5px 5px 4px 0px";
  27362. header.style.marginLeft = "-5px";
  27363. header.style.fontWeight = "bold";
  27364. root.appendChild(header);
  27365. };
  27366. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27367. var label = document.createElement("label");
  27368. label.innerHTML = title;
  27369. label.style.color = color;
  27370. root.appendChild(label);
  27371. root.appendChild(document.createElement("br"));
  27372. };
  27373. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27374. if (tag === void 0) { tag = null; }
  27375. var label = document.createElement("label");
  27376. var boundingBoxesCheckbox = document.createElement("input");
  27377. boundingBoxesCheckbox.type = "checkbox";
  27378. boundingBoxesCheckbox.checked = initialState;
  27379. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27380. task(evt.target, tag);
  27381. });
  27382. label.appendChild(boundingBoxesCheckbox);
  27383. var container = document.createElement("span");
  27384. var leftPart = document.createElement("span");
  27385. var rightPart = document.createElement("span");
  27386. rightPart.style.cssFloat = "right";
  27387. leftPart.innerHTML = leftTitle;
  27388. rightPart.innerHTML = rightTitle;
  27389. rightPart.style.fontSize = "12px";
  27390. rightPart.style.maxWidth = "200px";
  27391. container.appendChild(leftPart);
  27392. container.appendChild(rightPart);
  27393. label.appendChild(container);
  27394. root.appendChild(label);
  27395. root.appendChild(document.createElement("br"));
  27396. };
  27397. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27398. if (tag === void 0) { tag = null; }
  27399. var label = document.createElement("label");
  27400. var checkBox = document.createElement("input");
  27401. checkBox.type = "checkbox";
  27402. checkBox.checked = initialState;
  27403. checkBox.addEventListener("change", function (evt) {
  27404. task(evt.target, tag);
  27405. });
  27406. label.appendChild(checkBox);
  27407. label.appendChild(document.createTextNode(title));
  27408. root.appendChild(label);
  27409. root.appendChild(document.createElement("br"));
  27410. };
  27411. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27412. if (tag === void 0) { tag = null; }
  27413. var button = document.createElement("button");
  27414. button.innerHTML = title;
  27415. button.style.height = "24px";
  27416. button.style.width = "150px";
  27417. button.style.marginBottom = "5px";
  27418. button.style.color = "#444444";
  27419. button.style.border = "1px solid white";
  27420. button.className = "debugLayerButton";
  27421. button.addEventListener("click", function (evt) {
  27422. task(evt.target, tag);
  27423. });
  27424. root.appendChild(button);
  27425. root.appendChild(document.createElement("br"));
  27426. };
  27427. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27428. if (tag === void 0) { tag = null; }
  27429. var label = document.createElement("label");
  27430. var boundingBoxesRadio = document.createElement("input");
  27431. boundingBoxesRadio.type = "radio";
  27432. boundingBoxesRadio.name = name;
  27433. boundingBoxesRadio.checked = initialState;
  27434. boundingBoxesRadio.addEventListener("change", function (evt) {
  27435. task(evt.target, tag);
  27436. });
  27437. label.appendChild(boundingBoxesRadio);
  27438. label.appendChild(document.createTextNode(title));
  27439. root.appendChild(label);
  27440. root.appendChild(document.createElement("br"));
  27441. };
  27442. DebugLayer.prototype._generateDOMelements = function () {
  27443. var _this = this;
  27444. this._globalDiv.id = "DebugLayer";
  27445. this._globalDiv.style.position = "absolute";
  27446. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27447. this._globalDiv.style.fontSize = "14px";
  27448. this._globalDiv.style.color = "white";
  27449. // Drawing canvas
  27450. this._drawingCanvas = document.createElement("canvas");
  27451. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27452. this._drawingCanvas.style.position = "absolute";
  27453. this._drawingCanvas.style.pointerEvents = "none";
  27454. this._drawingCanvas.style.backgroundColor = "transparent";
  27455. this._drawingContext = this._drawingCanvas.getContext("2d");
  27456. this._globalDiv.appendChild(this._drawingCanvas);
  27457. if (this._showUI) {
  27458. var background = "rgba(128, 128, 128, 0.4)";
  27459. var border = "rgb(180, 180, 180) solid 1px";
  27460. // Stats
  27461. this._statsDiv = document.createElement("div");
  27462. this._statsDiv.id = "DebugLayerStats";
  27463. this._statsDiv.style.border = border;
  27464. this._statsDiv.style.position = "absolute";
  27465. this._statsDiv.style.background = background;
  27466. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27467. this._generateheader(this._statsDiv, "STATISTICS");
  27468. this._statsSubsetDiv = document.createElement("div");
  27469. this._statsSubsetDiv.style.paddingTop = "5px";
  27470. this._statsSubsetDiv.style.paddingBottom = "5px";
  27471. this._statsSubsetDiv.style.overflowY = "auto";
  27472. this._statsDiv.appendChild(this._statsSubsetDiv);
  27473. // Tree
  27474. this._treeDiv = document.createElement("div");
  27475. this._treeDiv.id = "DebugLayerTree";
  27476. this._treeDiv.style.border = border;
  27477. this._treeDiv.style.position = "absolute";
  27478. this._treeDiv.style.background = background;
  27479. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27480. this._treeDiv.style.display = "none";
  27481. this._generateheader(this._treeDiv, "MESHES TREE");
  27482. this._treeSubsetDiv = document.createElement("div");
  27483. this._treeSubsetDiv.style.paddingTop = "5px";
  27484. this._treeSubsetDiv.style.paddingRight = "5px";
  27485. this._treeSubsetDiv.style.overflowY = "auto";
  27486. this._treeSubsetDiv.style.maxHeight = "300px";
  27487. this._treeDiv.appendChild(this._treeSubsetDiv);
  27488. this._needToRefreshMeshesTree = true;
  27489. // Logs
  27490. this._logDiv = document.createElement("div");
  27491. this._logDiv.style.border = border;
  27492. this._logDiv.id = "DebugLayerLogs";
  27493. this._logDiv.style.position = "absolute";
  27494. this._logDiv.style.background = background;
  27495. this._logDiv.style.padding = "0px 0px 0px 5px";
  27496. this._logDiv.style.display = "none";
  27497. this._generateheader(this._logDiv, "LOGS");
  27498. this._logSubsetDiv = document.createElement("div");
  27499. this._logSubsetDiv.style.height = "127px";
  27500. this._logSubsetDiv.style.paddingTop = "5px";
  27501. this._logSubsetDiv.style.overflowY = "auto";
  27502. this._logSubsetDiv.style.fontSize = "12px";
  27503. this._logSubsetDiv.style.fontFamily = "consolas";
  27504. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27505. this._logDiv.appendChild(this._logSubsetDiv);
  27506. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27507. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27508. };
  27509. // Options
  27510. this._optionsDiv = document.createElement("div");
  27511. this._optionsDiv.id = "DebugLayerOptions";
  27512. this._optionsDiv.style.border = border;
  27513. this._optionsDiv.style.position = "absolute";
  27514. this._optionsDiv.style.background = background;
  27515. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27516. this._optionsDiv.style.overflowY = "auto";
  27517. this._generateheader(this._optionsDiv, "OPTIONS");
  27518. this._optionsSubsetDiv = document.createElement("div");
  27519. this._optionsSubsetDiv.style.paddingTop = "5px";
  27520. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27521. this._optionsSubsetDiv.style.overflowY = "auto";
  27522. this._optionsSubsetDiv.style.maxHeight = "200px";
  27523. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27524. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27525. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27526. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27527. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27528. _this._displayTree = element.checked;
  27529. _this._needToRefreshMeshesTree = true;
  27530. });
  27531. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27532. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27533. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27534. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27535. _this._labelsEnabled = element.checked;
  27536. if (!_this._labelsEnabled) {
  27537. _this._clearLabels();
  27538. }
  27539. });
  27540. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27541. if (element.checked) {
  27542. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27543. }
  27544. else {
  27545. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27546. }
  27547. });
  27548. ;
  27549. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27550. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27551. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27552. if (element.checked) {
  27553. _this._scene.forceWireframe = false;
  27554. _this._scene.forcePointsCloud = false;
  27555. }
  27556. });
  27557. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27558. if (element.checked) {
  27559. _this._scene.forceWireframe = true;
  27560. _this._scene.forcePointsCloud = false;
  27561. }
  27562. });
  27563. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27564. if (element.checked) {
  27565. _this._scene.forceWireframe = false;
  27566. _this._scene.forcePointsCloud = true;
  27567. }
  27568. });
  27569. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27570. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27571. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27572. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27573. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27574. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27575. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27576. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27577. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27578. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27579. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27580. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27581. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27582. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27583. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27584. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27585. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27586. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27587. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27588. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27589. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27590. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27591. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27592. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27593. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27594. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27595. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27596. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27597. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27598. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27599. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27600. if (element.checked) {
  27601. _this._scene.headphone = true;
  27602. }
  27603. });
  27604. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27605. if (element.checked) {
  27606. _this._scene.headphone = false;
  27607. }
  27608. });
  27609. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27610. _this._scene.audioEnabled = !element.checked;
  27611. });
  27612. }
  27613. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27614. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27615. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27616. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27617. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27618. if (_this._camera) {
  27619. console.log(_this._camera);
  27620. }
  27621. else {
  27622. console.warn("No camera defined, or debug layer created before camera creation!");
  27623. }
  27624. });
  27625. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27626. this._globalDiv.appendChild(this._statsDiv);
  27627. this._globalDiv.appendChild(this._logDiv);
  27628. this._globalDiv.appendChild(this._optionsDiv);
  27629. this._globalDiv.appendChild(this._treeDiv);
  27630. }
  27631. };
  27632. DebugLayer.prototype._displayStats = function () {
  27633. var scene = this._scene;
  27634. var engine = scene.getEngine();
  27635. var glInfo = engine.getGlInfo();
  27636. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27637. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27638. + "<b>Count</b><br>"
  27639. + "Total meshes: " + scene.meshes.length + "<br>"
  27640. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27641. + "Total materials: " + scene.materials.length + "<br>"
  27642. + "Total textures: " + scene.textures.length + "<br>"
  27643. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27644. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27645. + "Active bones: " + scene.getActiveBones() + "<br>"
  27646. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27647. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27648. + "<b>Duration</b><br>"
  27649. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27650. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27651. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27652. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27653. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27654. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27655. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27656. + "</div>"
  27657. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27658. + "<b>Extensions</b><br>"
  27659. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27660. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27661. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27662. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27663. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27664. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27665. + "<b>Caps.</b><br>"
  27666. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27667. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27668. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27669. + "</div><br>"
  27670. + "<b>Info</b><br>"
  27671. + glInfo.version + "<br>"
  27672. + glInfo.renderer + "<br>";
  27673. if (this.customStatsFunction) {
  27674. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27675. }
  27676. };
  27677. return DebugLayer;
  27678. })();
  27679. BABYLON.DebugLayer = DebugLayer;
  27680. })(BABYLON || (BABYLON = {}));
  27681. var BABYLON;
  27682. (function (BABYLON) {
  27683. var DefaultLoadingScreen = (function () {
  27684. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27685. var _this = this;
  27686. if (_loadingText === void 0) { _loadingText = ""; }
  27687. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27688. this._renderingCanvas = _renderingCanvas;
  27689. this._loadingText = _loadingText;
  27690. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27691. // Resize
  27692. this._resizeLoadingUI = function () {
  27693. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27694. _this._loadingDiv.style.position = "absolute";
  27695. _this._loadingDiv.style.left = canvasRect.left + "px";
  27696. _this._loadingDiv.style.top = canvasRect.top + "px";
  27697. _this._loadingDiv.style.width = canvasRect.width + "px";
  27698. _this._loadingDiv.style.height = canvasRect.height + "px";
  27699. };
  27700. }
  27701. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27702. var _this = this;
  27703. this._loadingDiv = document.createElement("div");
  27704. this._loadingDiv.id = "babylonjsLoadingDiv";
  27705. this._loadingDiv.style.opacity = "0";
  27706. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27707. // Loading text
  27708. this._loadingTextDiv = document.createElement("div");
  27709. this._loadingTextDiv.style.position = "absolute";
  27710. this._loadingTextDiv.style.left = "0";
  27711. this._loadingTextDiv.style.top = "50%";
  27712. this._loadingTextDiv.style.marginTop = "80px";
  27713. this._loadingTextDiv.style.width = "100%";
  27714. this._loadingTextDiv.style.height = "20px";
  27715. this._loadingTextDiv.style.fontFamily = "Arial";
  27716. this._loadingTextDiv.style.fontSize = "14px";
  27717. this._loadingTextDiv.style.color = "white";
  27718. this._loadingTextDiv.style.textAlign = "center";
  27719. this._loadingTextDiv.innerHTML = "Loading";
  27720. this._loadingDiv.appendChild(this._loadingTextDiv);
  27721. //set the predefined text
  27722. this._loadingTextDiv.innerHTML = this._loadingText;
  27723. // Loading img
  27724. var imgBack = new Image();
  27725. 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==";
  27726. imgBack.style.position = "absolute";
  27727. imgBack.style.left = "50%";
  27728. imgBack.style.top = "50%";
  27729. imgBack.style.marginLeft = "-50px";
  27730. imgBack.style.marginTop = "-50px";
  27731. imgBack.style.transition = "transform 1.0s ease";
  27732. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27733. var deg = 360;
  27734. var onTransitionEnd = function () {
  27735. deg += 360;
  27736. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27737. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27738. };
  27739. imgBack.addEventListener("transitionend", onTransitionEnd);
  27740. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27741. this._loadingDiv.appendChild(imgBack);
  27742. // front image
  27743. var imgFront = new Image();
  27744. 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=";
  27745. imgFront.style.position = "absolute";
  27746. imgFront.style.left = "50%";
  27747. imgFront.style.top = "50%";
  27748. imgFront.style.marginLeft = "-50px";
  27749. imgFront.style.marginTop = "-50px";
  27750. this._loadingDiv.appendChild(imgFront);
  27751. this._resizeLoadingUI();
  27752. window.addEventListener("resize", this._resizeLoadingUI);
  27753. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27754. document.body.appendChild(this._loadingDiv);
  27755. setTimeout(function () {
  27756. _this._loadingDiv.style.opacity = "1";
  27757. imgBack.style.transform = "rotateZ(360deg)";
  27758. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27759. }, 0);
  27760. };
  27761. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27762. var _this = this;
  27763. if (!this._loadingDiv) {
  27764. return;
  27765. }
  27766. var onTransitionEnd = function () {
  27767. if (!_this._loadingDiv) {
  27768. return;
  27769. }
  27770. document.body.removeChild(_this._loadingDiv);
  27771. window.removeEventListener("resize", _this._resizeLoadingUI);
  27772. _this._loadingDiv = null;
  27773. };
  27774. this._loadingDiv.style.opacity = "0";
  27775. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27776. };
  27777. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27778. set: function (text) {
  27779. this._loadingText = text;
  27780. if (this._loadingTextDiv) {
  27781. this._loadingTextDiv.innerHTML = this._loadingText;
  27782. }
  27783. },
  27784. enumerable: true,
  27785. configurable: true
  27786. });
  27787. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27788. get: function () {
  27789. return this._loadingDivBackgroundColor;
  27790. },
  27791. set: function (color) {
  27792. this._loadingDivBackgroundColor = color;
  27793. if (!this._loadingDiv) {
  27794. return;
  27795. }
  27796. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27797. },
  27798. enumerable: true,
  27799. configurable: true
  27800. });
  27801. return DefaultLoadingScreen;
  27802. })();
  27803. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27804. })(BABYLON || (BABYLON = {}));
  27805. var BABYLON;
  27806. (function (BABYLON) {
  27807. var SIMDVector3 = (function () {
  27808. function SIMDVector3() {
  27809. }
  27810. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27811. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27812. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27813. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27814. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27815. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27816. 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));
  27817. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27818. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27819. };
  27820. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27821. var v0 = SIMD.float32x4.splat(x);
  27822. var v1 = SIMD.float32x4.splat(y);
  27823. var v2 = SIMD.float32x4.splat(z);
  27824. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27825. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27826. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27827. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27828. 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));
  27829. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27830. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27831. };
  27832. return SIMDVector3;
  27833. })();
  27834. BABYLON.SIMDVector3 = SIMDVector3;
  27835. var SIMDMatrix = (function () {
  27836. function SIMDMatrix() {
  27837. }
  27838. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27839. if (offset === void 0) { offset = 0; }
  27840. var tm = this.m;
  27841. var om = other.m;
  27842. var om0 = SIMD.float32x4.load(om, 0);
  27843. var om1 = SIMD.float32x4.load(om, 4);
  27844. var om2 = SIMD.float32x4.load(om, 8);
  27845. var om3 = SIMD.float32x4.load(om, 12);
  27846. var tm0 = SIMD.float32x4.load(tm, 0);
  27847. 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)))));
  27848. var tm1 = SIMD.float32x4.load(tm, 4);
  27849. 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)))));
  27850. var tm2 = SIMD.float32x4.load(tm, 8);
  27851. 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)))));
  27852. var tm3 = SIMD.float32x4.load(tm, 12);
  27853. 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)))));
  27854. };
  27855. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27856. var src = this.m;
  27857. var dest = other.m;
  27858. var row0, row1, row2, row3;
  27859. var tmp1;
  27860. var minor0, minor1, minor2, minor3;
  27861. var det;
  27862. // Load the 4 rows
  27863. var src0 = SIMD.float32x4.load(src, 0);
  27864. var src1 = SIMD.float32x4.load(src, 4);
  27865. var src2 = SIMD.float32x4.load(src, 8);
  27866. var src3 = SIMD.float32x4.load(src, 12);
  27867. // Transpose the source matrix. Sort of. Not a true transpose operation
  27868. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27869. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27870. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27871. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27872. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27873. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27874. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27875. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27876. // This is a true transposition, but it will lead to an incorrect result
  27877. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27878. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27879. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27880. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27881. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27882. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27883. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27884. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27885. // ----
  27886. tmp1 = SIMD.float32x4.mul(row2, row3);
  27887. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27888. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27889. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27890. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27891. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27892. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27893. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27894. // ----
  27895. tmp1 = SIMD.float32x4.mul(row1, row2);
  27896. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27897. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27898. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27899. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27900. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27901. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27902. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27903. // ----
  27904. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27905. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27906. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27907. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27908. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27909. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27910. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27911. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27912. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27913. // ----
  27914. tmp1 = SIMD.float32x4.mul(row0, row1);
  27915. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27916. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27917. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27918. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27919. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27920. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27921. // ----
  27922. tmp1 = SIMD.float32x4.mul(row0, row3);
  27923. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27924. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27925. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27926. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27927. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27928. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27929. // ----
  27930. tmp1 = SIMD.float32x4.mul(row0, row2);
  27931. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27932. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27933. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27934. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27935. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27936. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27937. // Compute determinant
  27938. det = SIMD.float32x4.mul(row0, minor0);
  27939. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27940. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27941. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27942. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27943. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27944. // These shuffles aren't necessary if the faulty transposition is done
  27945. // up at the top of this function.
  27946. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27947. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27948. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27949. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27950. // Compute final values by multiplying with 1/det
  27951. minor0 = SIMD.float32x4.mul(det, minor0);
  27952. minor1 = SIMD.float32x4.mul(det, minor1);
  27953. minor2 = SIMD.float32x4.mul(det, minor2);
  27954. minor3 = SIMD.float32x4.mul(det, minor3);
  27955. SIMD.float32x4.store(dest, 0, minor0);
  27956. SIMD.float32x4.store(dest, 4, minor1);
  27957. SIMD.float32x4.store(dest, 8, minor2);
  27958. SIMD.float32x4.store(dest, 12, minor3);
  27959. return this;
  27960. };
  27961. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27962. var out = result.m;
  27963. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27964. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27965. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27966. // cc.kmVec3Subtract(f, pCenter, pEye);
  27967. var f = SIMD.float32x4.sub(center, eye);
  27968. // cc.kmVec3Normalize(f, f);
  27969. var tmp = SIMD.float32x4.mul(f, f);
  27970. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27971. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27972. // cc.kmVec3Assign(up, pUp);
  27973. // cc.kmVec3Normalize(up, up);
  27974. tmp = SIMD.float32x4.mul(up, up);
  27975. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27976. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27977. // cc.kmVec3Cross(s, f, up);
  27978. 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)));
  27979. // cc.kmVec3Normalize(s, s);
  27980. tmp = SIMD.float32x4.mul(s, s);
  27981. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27982. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27983. // cc.kmVec3Cross(u, s, f);
  27984. 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)));
  27985. // cc.kmVec3Normalize(s, s);
  27986. tmp = SIMD.float32x4.mul(s, s);
  27987. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27988. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27989. var zero = SIMD.float32x4.splat(0.0);
  27990. s = SIMD.float32x4.neg(s);
  27991. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27992. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27993. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27994. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27995. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27996. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27997. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27998. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27999. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28000. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28001. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28002. var b3 = SIMD.float32x4.neg(eye);
  28003. b3 = SIMD.float32x4.withW(b3, 1.0);
  28004. 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)))));
  28005. 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)))));
  28006. 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)))));
  28007. 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)))));
  28008. };
  28009. return SIMDMatrix;
  28010. })();
  28011. BABYLON.SIMDMatrix = SIMDMatrix;
  28012. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28013. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28014. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28015. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28016. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28017. var SIMDHelper = (function () {
  28018. function SIMDHelper() {
  28019. }
  28020. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28021. get: function () {
  28022. return SIMDHelper._isEnabled;
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. SIMDHelper.DisableSIMD = function () {
  28028. // Replace functions
  28029. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28030. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28031. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28032. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28034. SIMDHelper._isEnabled = false;
  28035. };
  28036. SIMDHelper.EnableSIMD = function () {
  28037. if (window.SIMD === undefined) {
  28038. return;
  28039. }
  28040. // Replace functions
  28041. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28042. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28043. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28044. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28046. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28047. get: function () { return this._data[0]; },
  28048. set: function (value) {
  28049. if (!this._data) {
  28050. this._data = new Float32Array(3);
  28051. }
  28052. this._data[0] = value;
  28053. }
  28054. });
  28055. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28056. get: function () { return this._data[1]; },
  28057. set: function (value) {
  28058. this._data[1] = value;
  28059. }
  28060. });
  28061. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28062. get: function () { return this._data[2]; },
  28063. set: function (value) {
  28064. this._data[2] = value;
  28065. }
  28066. });
  28067. SIMDHelper._isEnabled = true;
  28068. };
  28069. SIMDHelper._isEnabled = false;
  28070. return SIMDHelper;
  28071. })();
  28072. BABYLON.SIMDHelper = SIMDHelper;
  28073. })(BABYLON || (BABYLON = {}));
  28074. var BABYLON;
  28075. (function (BABYLON) {
  28076. var ShaderMaterial = (function (_super) {
  28077. __extends(ShaderMaterial, _super);
  28078. function ShaderMaterial(name, scene, shaderPath, options) {
  28079. _super.call(this, name, scene);
  28080. this._textures = new Array();
  28081. this._floats = new Array();
  28082. this._floatsArrays = {};
  28083. this._colors3 = new Array();
  28084. this._colors4 = new Array();
  28085. this._vectors2 = new Array();
  28086. this._vectors3 = new Array();
  28087. this._vectors4 = new Array();
  28088. this._matrices = new Array();
  28089. this._matrices3x3 = new Array();
  28090. this._matrices2x2 = new Array();
  28091. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28092. this._shaderPath = shaderPath;
  28093. options.needAlphaBlending = options.needAlphaBlending || false;
  28094. options.needAlphaTesting = options.needAlphaTesting || false;
  28095. options.attributes = options.attributes || ["position", "normal", "uv"];
  28096. options.uniforms = options.uniforms || ["worldViewProjection"];
  28097. options.samplers = options.samplers || [];
  28098. options.defines = options.defines || [];
  28099. this._options = options;
  28100. }
  28101. ShaderMaterial.prototype.needAlphaBlending = function () {
  28102. return this._options.needAlphaBlending;
  28103. };
  28104. ShaderMaterial.prototype.needAlphaTesting = function () {
  28105. return this._options.needAlphaTesting;
  28106. };
  28107. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28108. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28109. this._options.uniforms.push(uniformName);
  28110. }
  28111. };
  28112. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28113. if (this._options.samplers.indexOf(name) === -1) {
  28114. this._options.samplers.push(name);
  28115. }
  28116. this._textures[name] = texture;
  28117. return this;
  28118. };
  28119. ShaderMaterial.prototype.setFloat = function (name, value) {
  28120. this._checkUniform(name);
  28121. this._floats[name] = value;
  28122. return this;
  28123. };
  28124. ShaderMaterial.prototype.setFloats = function (name, value) {
  28125. this._checkUniform(name);
  28126. this._floatsArrays[name] = value;
  28127. return this;
  28128. };
  28129. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28130. this._checkUniform(name);
  28131. this._colors3[name] = value;
  28132. return this;
  28133. };
  28134. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28135. this._checkUniform(name);
  28136. this._colors4[name] = value;
  28137. return this;
  28138. };
  28139. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28140. this._checkUniform(name);
  28141. this._vectors2[name] = value;
  28142. return this;
  28143. };
  28144. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28145. this._checkUniform(name);
  28146. this._vectors3[name] = value;
  28147. return this;
  28148. };
  28149. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28150. this._checkUniform(name);
  28151. this._vectors4[name] = value;
  28152. return this;
  28153. };
  28154. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28155. this._checkUniform(name);
  28156. this._matrices[name] = value;
  28157. return this;
  28158. };
  28159. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28160. this._checkUniform(name);
  28161. this._matrices3x3[name] = value;
  28162. return this;
  28163. };
  28164. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28165. this._checkUniform(name);
  28166. this._matrices2x2[name] = value;
  28167. return this;
  28168. };
  28169. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28170. var scene = this.getScene();
  28171. var engine = scene.getEngine();
  28172. if (!this.checkReadyOnEveryCall) {
  28173. if (this._renderId === scene.getRenderId()) {
  28174. return true;
  28175. }
  28176. }
  28177. // Instances
  28178. var defines = [];
  28179. var fallbacks = new BABYLON.EffectFallbacks();
  28180. if (useInstances) {
  28181. defines.push("#define INSTANCES");
  28182. }
  28183. for (var index = 0; index < this._options.defines.length; index++) {
  28184. defines.push(this._options.defines[index]);
  28185. }
  28186. // Bones
  28187. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28188. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28189. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28190. fallbacks.addCPUSkinningFallback(0, mesh);
  28191. }
  28192. // Alpha test
  28193. if (engine.getAlphaTesting()) {
  28194. defines.push("#define ALPHATEST");
  28195. }
  28196. var previousEffect = this._effect;
  28197. var join = defines.join("\n");
  28198. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28199. if (!this._effect.isReady()) {
  28200. return false;
  28201. }
  28202. if (previousEffect !== this._effect) {
  28203. scene.resetCachedMaterial();
  28204. }
  28205. this._renderId = scene.getRenderId();
  28206. return true;
  28207. };
  28208. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28209. var scene = this.getScene();
  28210. if (this._options.uniforms.indexOf("world") !== -1) {
  28211. this._effect.setMatrix("world", world);
  28212. }
  28213. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28214. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28215. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28216. }
  28217. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28218. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28219. }
  28220. };
  28221. ShaderMaterial.prototype.bind = function (world, mesh) {
  28222. // Std values
  28223. this.bindOnlyWorldMatrix(world);
  28224. if (this.getScene().getCachedMaterial() !== this) {
  28225. if (this._options.uniforms.indexOf("view") !== -1) {
  28226. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28227. }
  28228. if (this._options.uniforms.indexOf("projection") !== -1) {
  28229. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28230. }
  28231. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28232. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28233. }
  28234. // Bones
  28235. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28236. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28237. }
  28238. // Texture
  28239. for (var name in this._textures) {
  28240. this._effect.setTexture(name, this._textures[name]);
  28241. }
  28242. // Float
  28243. for (name in this._floats) {
  28244. this._effect.setFloat(name, this._floats[name]);
  28245. }
  28246. // Float s
  28247. for (name in this._floatsArrays) {
  28248. this._effect.setArray(name, this._floatsArrays[name]);
  28249. }
  28250. // Color3
  28251. for (name in this._colors3) {
  28252. this._effect.setColor3(name, this._colors3[name]);
  28253. }
  28254. // Color4
  28255. for (name in this._colors4) {
  28256. var color = this._colors4[name];
  28257. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28258. }
  28259. // Vector2
  28260. for (name in this._vectors2) {
  28261. this._effect.setVector2(name, this._vectors2[name]);
  28262. }
  28263. // Vector3
  28264. for (name in this._vectors3) {
  28265. this._effect.setVector3(name, this._vectors3[name]);
  28266. }
  28267. // Vector4
  28268. for (name in this._vectors4) {
  28269. this._effect.setVector4(name, this._vectors4[name]);
  28270. }
  28271. // Matrix
  28272. for (name in this._matrices) {
  28273. this._effect.setMatrix(name, this._matrices[name]);
  28274. }
  28275. // Matrix 3x3
  28276. for (name in this._matrices3x3) {
  28277. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28278. }
  28279. // Matrix 2x2
  28280. for (name in this._matrices2x2) {
  28281. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28282. }
  28283. }
  28284. _super.prototype.bind.call(this, world, mesh);
  28285. };
  28286. ShaderMaterial.prototype.clone = function (name) {
  28287. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28288. return newShaderMaterial;
  28289. };
  28290. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28291. for (var name in this._textures) {
  28292. this._textures[name].dispose();
  28293. }
  28294. this._textures = [];
  28295. _super.prototype.dispose.call(this, forceDisposeEffect);
  28296. };
  28297. return ShaderMaterial;
  28298. })(BABYLON.Material);
  28299. BABYLON.ShaderMaterial = ShaderMaterial;
  28300. })(BABYLON || (BABYLON = {}));
  28301. var BABYLON;
  28302. (function (BABYLON) {
  28303. var Internals;
  28304. (function (Internals) {
  28305. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28306. // All values and structures referenced from:
  28307. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28308. var DDS_MAGIC = 0x20534444;
  28309. 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;
  28310. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28311. 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;
  28312. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28313. function FourCCToInt32(value) {
  28314. return value.charCodeAt(0) +
  28315. (value.charCodeAt(1) << 8) +
  28316. (value.charCodeAt(2) << 16) +
  28317. (value.charCodeAt(3) << 24);
  28318. }
  28319. function Int32ToFourCC(value) {
  28320. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28321. }
  28322. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28323. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28324. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28325. var headerLengthInt = 31; // The header length in 32 bit ints
  28326. // Offsets into the header array
  28327. var off_magic = 0;
  28328. var off_size = 1;
  28329. var off_flags = 2;
  28330. var off_height = 3;
  28331. var off_width = 4;
  28332. var off_mipmapCount = 7;
  28333. var off_pfFlags = 20;
  28334. var off_pfFourCC = 21;
  28335. var off_RGBbpp = 22;
  28336. var off_RMask = 23;
  28337. var off_GMask = 24;
  28338. var off_BMask = 25;
  28339. var off_AMask = 26;
  28340. var off_caps1 = 27;
  28341. var off_caps2 = 28;
  28342. ;
  28343. var DDSTools = (function () {
  28344. function DDSTools() {
  28345. }
  28346. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28347. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28348. var mipmapCount = 1;
  28349. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28350. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28351. }
  28352. return {
  28353. width: header[off_width],
  28354. height: header[off_height],
  28355. mipmapCount: mipmapCount,
  28356. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28357. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28358. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28359. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28360. };
  28361. };
  28362. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28363. var byteArray = new Uint8Array(dataLength);
  28364. var srcData = new Uint8Array(arrayBuffer);
  28365. var index = 0;
  28366. for (var y = height - 1; y >= 0; y--) {
  28367. for (var x = 0; x < width; x++) {
  28368. var srcPos = dataOffset + (x + y * width) * 4;
  28369. byteArray[index + 2] = srcData[srcPos];
  28370. byteArray[index + 1] = srcData[srcPos + 1];
  28371. byteArray[index] = srcData[srcPos + 2];
  28372. byteArray[index + 3] = srcData[srcPos + 3];
  28373. index += 4;
  28374. }
  28375. }
  28376. return byteArray;
  28377. };
  28378. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28379. var byteArray = new Uint8Array(dataLength);
  28380. var srcData = new Uint8Array(arrayBuffer);
  28381. var index = 0;
  28382. for (var y = height - 1; y >= 0; y--) {
  28383. for (var x = 0; x < width; x++) {
  28384. var srcPos = dataOffset + (x + y * width) * 3;
  28385. byteArray[index + 2] = srcData[srcPos];
  28386. byteArray[index + 1] = srcData[srcPos + 1];
  28387. byteArray[index] = srcData[srcPos + 2];
  28388. index += 3;
  28389. }
  28390. }
  28391. return byteArray;
  28392. };
  28393. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28394. var byteArray = new Uint8Array(dataLength);
  28395. var srcData = new Uint8Array(arrayBuffer);
  28396. var index = 0;
  28397. for (var y = height - 1; y >= 0; y--) {
  28398. for (var x = 0; x < width; x++) {
  28399. var srcPos = dataOffset + (x + y * width);
  28400. byteArray[index] = srcData[srcPos];
  28401. index++;
  28402. }
  28403. }
  28404. return byteArray;
  28405. };
  28406. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28407. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28408. if (header[off_magic] != DDS_MAGIC) {
  28409. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28410. return;
  28411. }
  28412. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28413. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28414. return;
  28415. }
  28416. if (info.isFourCC) {
  28417. fourCC = header[off_pfFourCC];
  28418. switch (fourCC) {
  28419. case FOURCC_DXT1:
  28420. blockBytes = 8;
  28421. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28422. break;
  28423. case FOURCC_DXT3:
  28424. blockBytes = 16;
  28425. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28426. break;
  28427. case FOURCC_DXT5:
  28428. blockBytes = 16;
  28429. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28430. break;
  28431. default:
  28432. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28433. return;
  28434. }
  28435. }
  28436. mipmapCount = 1;
  28437. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28438. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28439. }
  28440. var bpp = header[off_RGBbpp];
  28441. for (var face = 0; face < faces; face++) {
  28442. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28443. width = header[off_width];
  28444. height = header[off_height];
  28445. dataOffset = header[off_size] + 4;
  28446. for (i = 0; i < mipmapCount; ++i) {
  28447. if (info.isRGB) {
  28448. if (bpp === 24) {
  28449. dataLength = width * height * 3;
  28450. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28451. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28452. }
  28453. else {
  28454. dataLength = width * height * 4;
  28455. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28456. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28457. }
  28458. }
  28459. else if (info.isLuminance) {
  28460. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28461. var unpaddedRowSize = width;
  28462. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28463. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28464. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28465. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28466. }
  28467. else {
  28468. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28469. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28470. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28471. }
  28472. dataOffset += dataLength;
  28473. width *= 0.5;
  28474. height *= 0.5;
  28475. width = Math.max(1.0, width);
  28476. height = Math.max(1.0, height);
  28477. }
  28478. }
  28479. };
  28480. return DDSTools;
  28481. })();
  28482. Internals.DDSTools = DDSTools;
  28483. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28484. })(BABYLON || (BABYLON = {}));
  28485. var BABYLON;
  28486. (function (BABYLON) {
  28487. var CannonJSPlugin = (function () {
  28488. function CannonJSPlugin() {
  28489. this._registeredMeshes = [];
  28490. this._physicsMaterials = [];
  28491. this.name = "cannon";
  28492. this.updateBodyPosition = function (mesh) {
  28493. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28494. var registeredMesh = this._registeredMeshes[index];
  28495. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28496. var body = registeredMesh.body;
  28497. var center = mesh.getBoundingInfo().boundingBox.center;
  28498. body.position.set(center.x, center.y, center.z);
  28499. body.quaternion.copy(mesh.rotationQuaternion);
  28500. if (registeredMesh.deltaRotation) {
  28501. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28502. body.quaternion = body.quaternion.mult(tmpQ);
  28503. }
  28504. if (registeredMesh.heightmap) {
  28505. //calculate the correct body position:
  28506. var rotationQuaternion = mesh.rotationQuaternion;
  28507. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28508. mesh.computeWorldMatrix(true);
  28509. //get original center with no rotation
  28510. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28511. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28512. //rotation is back
  28513. mesh.rotationQuaternion = rotationQuaternion;
  28514. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28515. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28516. mesh.setPivotMatrix(p);
  28517. mesh.computeWorldMatrix(true);
  28518. //calculate the translation
  28519. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28520. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28521. //add it inverted to the delta
  28522. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28523. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28524. mesh.setPivotMatrix(oldPivot);
  28525. mesh.computeWorldMatrix(true);
  28526. }
  28527. return;
  28528. }
  28529. }
  28530. };
  28531. }
  28532. CannonJSPlugin.prototype.initialize = function (iterations) {
  28533. if (iterations === void 0) { iterations = 10; }
  28534. this._world = new CANNON.World();
  28535. this._world.broadphase = new CANNON.NaiveBroadphase();
  28536. this._world.solver.iterations = iterations;
  28537. };
  28538. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28539. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28540. };
  28541. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28542. var _this = this;
  28543. this._world.step(delta);
  28544. this._registeredMeshes.forEach(function (registeredMesh) {
  28545. // Body position
  28546. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28547. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28548. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28549. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28550. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28551. if (registeredMesh.deltaRotation) {
  28552. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28553. }
  28554. //is the physics collision callback is set?
  28555. if (registeredMesh.mesh.onPhysicsCollide) {
  28556. if (!registeredMesh.collisionFunction) {
  28557. registeredMesh.collisionFunction = function (e) {
  28558. //find the mesh that collided with the registered mesh
  28559. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28560. if (_this._registeredMeshes[idx].body == e.body) {
  28561. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28562. }
  28563. }
  28564. };
  28565. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28566. }
  28567. }
  28568. else {
  28569. //unregister, in case the function was removed for some reason
  28570. if (registeredMesh.collisionFunction) {
  28571. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28572. }
  28573. }
  28574. });
  28575. };
  28576. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28577. this._gravity = gravity;
  28578. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28579. };
  28580. CannonJSPlugin.prototype.getGravity = function () {
  28581. return this._gravity;
  28582. };
  28583. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28584. this.unregisterMesh(mesh);
  28585. if (!mesh.rotationQuaternion) {
  28586. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28587. }
  28588. mesh.computeWorldMatrix(true);
  28589. var shape = this._createShape(mesh, impostor);
  28590. return this._createRigidBodyFromShape(shape, mesh, options);
  28591. };
  28592. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28593. //get the correct bounding box
  28594. var oldQuaternion = mesh.rotationQuaternion;
  28595. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28596. mesh.computeWorldMatrix(true);
  28597. var returnValue;
  28598. switch (impostor) {
  28599. case BABYLON.PhysicsEngine.SphereImpostor:
  28600. var bbox = mesh.getBoundingInfo().boundingBox;
  28601. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28602. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28603. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28604. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28605. break;
  28606. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28607. case BABYLON.PhysicsEngine.CylinderImpostor:
  28608. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28609. case BABYLON.PhysicsEngine.BoxImpostor:
  28610. bbox = mesh.getBoundingInfo().boundingBox;
  28611. var min = bbox.minimumWorld;
  28612. var max = bbox.maximumWorld;
  28613. var box = max.subtract(min).scale(0.5);
  28614. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28615. break;
  28616. case BABYLON.PhysicsEngine.PlaneImpostor:
  28617. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28618. returnValue = new CANNON.Plane();
  28619. break;
  28620. case BABYLON.PhysicsEngine.MeshImpostor:
  28621. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28622. var rawFaces = mesh.getIndices();
  28623. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28624. break;
  28625. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28626. returnValue = this._createHeightmap(mesh);
  28627. break;
  28628. }
  28629. mesh.rotationQuaternion = oldQuaternion;
  28630. return returnValue;
  28631. };
  28632. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28633. var verts = [], faces = [];
  28634. mesh.computeWorldMatrix(true);
  28635. //reuse this variable
  28636. var transformed = BABYLON.Vector3.Zero();
  28637. // Get vertices
  28638. for (var i = 0; i < rawVerts.length; i += 3) {
  28639. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28640. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28641. }
  28642. // Get faces
  28643. for (var j = 0; j < rawFaces.length; j += 3) {
  28644. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28645. }
  28646. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28647. return shape;
  28648. };
  28649. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28650. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28651. var matrix = [];
  28652. //For now pointDepth will not be used and will be automatically calculated.
  28653. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28654. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28655. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28656. var elementSize = dim * 2 / arraySize;
  28657. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28658. for (var i = 0; i < pos.length; i = i + 3) {
  28659. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28660. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28661. var y = pos[i + 1] + minY;
  28662. if (!matrix[x]) {
  28663. matrix[x] = [];
  28664. }
  28665. if (!matrix[x][z]) {
  28666. matrix[x][z] = y;
  28667. }
  28668. matrix[x][z] = Math.max(y, matrix[x][z]);
  28669. }
  28670. for (var x = 0; x <= arraySize; ++x) {
  28671. if (!matrix[x]) {
  28672. var loc = 1;
  28673. while (!matrix[(x + loc) % arraySize]) {
  28674. loc++;
  28675. }
  28676. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28677. }
  28678. for (var z = 0; z <= arraySize; ++z) {
  28679. if (!matrix[x][z]) {
  28680. var loc = 1;
  28681. var newValue;
  28682. while (newValue === undefined) {
  28683. newValue = matrix[x][(z + loc++) % arraySize];
  28684. }
  28685. matrix[x][z] = newValue;
  28686. }
  28687. }
  28688. }
  28689. var shape = new CANNON.Heightfield(matrix, {
  28690. elementSize: elementSize
  28691. });
  28692. //For future reference, needed for body transformation
  28693. shape.minY = minY;
  28694. return shape;
  28695. };
  28696. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28697. var index;
  28698. var mat;
  28699. for (index = 0; index < this._physicsMaterials.length; index++) {
  28700. mat = this._physicsMaterials[index];
  28701. if (mat.friction === friction && mat.restitution === restitution) {
  28702. return mat;
  28703. }
  28704. }
  28705. var currentMat = new CANNON.Material("mat");
  28706. this._physicsMaterials.push(currentMat);
  28707. for (index = 0; index < this._physicsMaterials.length; index++) {
  28708. mat = this._physicsMaterials[index];
  28709. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28710. this._world.addContactMaterial(contactMaterial);
  28711. }
  28712. return currentMat;
  28713. };
  28714. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28715. if (!mesh.rotationQuaternion) {
  28716. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28717. }
  28718. // The delta between the mesh position and the mesh bounding box center
  28719. var bbox = mesh.getBoundingInfo().boundingBox;
  28720. var deltaPosition = mesh.position.subtract(bbox.center);
  28721. var deltaRotation;
  28722. var material = this._addMaterial(options.friction, options.restitution);
  28723. var body = new CANNON.Body({
  28724. mass: options.mass,
  28725. material: material,
  28726. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28727. });
  28728. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28729. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28730. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28731. //-90 DEG in X, precalculated
  28732. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28733. body.quaternion = body.quaternion.mult(tmpQ);
  28734. //Invert! (Precalculated, 90 deg in X)
  28735. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28736. }
  28737. //If it is a heightfield, if should be centered.
  28738. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28739. //calculate the correct body position:
  28740. var rotationQuaternion = mesh.rotationQuaternion;
  28741. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28742. mesh.computeWorldMatrix(true);
  28743. //get original center with no rotation
  28744. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28745. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28746. //rotation is back
  28747. mesh.rotationQuaternion = rotationQuaternion;
  28748. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28749. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28750. mesh.setPivotMatrix(p);
  28751. mesh.computeWorldMatrix(true);
  28752. //calculate the translation
  28753. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28754. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28755. //add it inverted to the delta
  28756. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28757. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28758. mesh.setPivotMatrix(oldPivot);
  28759. mesh.computeWorldMatrix(true);
  28760. }
  28761. //add the shape
  28762. body.addShape(shape);
  28763. this._world.add(body);
  28764. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28765. return body;
  28766. };
  28767. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28768. var initialMesh = parts[0].mesh;
  28769. this.unregisterMesh(initialMesh);
  28770. initialMesh.computeWorldMatrix(true);
  28771. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28772. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28773. for (var index = 1; index < parts.length; index++) {
  28774. var mesh = parts[index].mesh;
  28775. mesh.computeWorldMatrix(true);
  28776. var shape = this._createShape(mesh, parts[index].impostor);
  28777. var localPosition = mesh.position;
  28778. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28779. }
  28780. return body;
  28781. };
  28782. CannonJSPlugin.prototype._unbindBody = function (body) {
  28783. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28784. var registeredMesh = this._registeredMeshes[index];
  28785. if (registeredMesh.body === body) {
  28786. this._world.remove(registeredMesh.body);
  28787. registeredMesh.body = null;
  28788. registeredMesh.delta = null;
  28789. registeredMesh.deltaRotation = null;
  28790. }
  28791. }
  28792. };
  28793. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28794. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28795. var registeredMesh = this._registeredMeshes[index];
  28796. if (registeredMesh.mesh === mesh) {
  28797. // Remove body
  28798. if (registeredMesh.body) {
  28799. this._unbindBody(registeredMesh.body);
  28800. }
  28801. this._registeredMeshes.splice(index, 1);
  28802. return;
  28803. }
  28804. }
  28805. };
  28806. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28807. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28808. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28809. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28810. var registeredMesh = this._registeredMeshes[index];
  28811. if (registeredMesh.mesh === mesh) {
  28812. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28813. return;
  28814. }
  28815. }
  28816. };
  28817. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28818. var body1 = null, body2 = null;
  28819. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28820. var registeredMesh = this._registeredMeshes[index];
  28821. if (registeredMesh.mesh === mesh1) {
  28822. body1 = registeredMesh.body;
  28823. }
  28824. else if (registeredMesh.mesh === mesh2) {
  28825. body2 = registeredMesh.body;
  28826. }
  28827. }
  28828. if (!body1 || !body2) {
  28829. return false;
  28830. }
  28831. 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));
  28832. this._world.addConstraint(constraint);
  28833. return true;
  28834. };
  28835. CannonJSPlugin.prototype.dispose = function () {
  28836. while (this._registeredMeshes.length) {
  28837. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28838. }
  28839. };
  28840. CannonJSPlugin.prototype.isSupported = function () {
  28841. return window.CANNON !== undefined;
  28842. };
  28843. CannonJSPlugin.prototype.getWorldObject = function () {
  28844. return this._world;
  28845. };
  28846. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28847. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28848. var registeredMesh = this._registeredMeshes[index];
  28849. if (registeredMesh.mesh === mesh) {
  28850. return registeredMesh.body;
  28851. }
  28852. }
  28853. return null;
  28854. };
  28855. return CannonJSPlugin;
  28856. })();
  28857. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28858. })(BABYLON || (BABYLON = {}));
  28859. var BABYLON;
  28860. (function (BABYLON) {
  28861. var OimoJSPlugin = (function () {
  28862. function OimoJSPlugin() {
  28863. this._registeredMeshes = [];
  28864. this.name = "oimo";
  28865. /**
  28866. * Update the body position according to the mesh position
  28867. * @param mesh
  28868. */
  28869. this.updateBodyPosition = function (mesh) {
  28870. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28871. var registeredMesh = this._registeredMeshes[index];
  28872. var body = registeredMesh.body.body;
  28873. var updated = false;
  28874. var newPosition;
  28875. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28876. mesh.computeWorldMatrix(true);
  28877. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28878. updated = true;
  28879. }
  28880. else if (registeredMesh.mesh.parent === mesh) {
  28881. mesh.computeWorldMatrix(true);
  28882. registeredMesh.mesh.computeWorldMatrix(true);
  28883. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28884. updated = true;
  28885. }
  28886. if (updated) {
  28887. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28888. body.setQuaternion(mesh.rotationQuaternion);
  28889. body.sleeping = false;
  28890. //force Oimo to update the body's position
  28891. body.updatePosition(1);
  28892. }
  28893. }
  28894. };
  28895. }
  28896. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28897. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28898. };
  28899. OimoJSPlugin.prototype.initialize = function (iterations) {
  28900. this._world = new OIMO.World(null, null, iterations);
  28901. this._world.clear();
  28902. };
  28903. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28904. this._gravity = this._world.gravity = gravity;
  28905. };
  28906. OimoJSPlugin.prototype.getGravity = function () {
  28907. return this._gravity;
  28908. };
  28909. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28910. this.unregisterMesh(mesh);
  28911. if (!mesh.rotationQuaternion) {
  28912. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28913. }
  28914. mesh.computeWorldMatrix(true);
  28915. var bbox = mesh.getBoundingInfo().boundingBox;
  28916. // The delta between the mesh position and the mesh bounding box center
  28917. var deltaPosition = mesh.position.subtract(bbox.center);
  28918. //calculate rotation to fit Oimo's needs (Euler...)
  28919. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28920. //get the correct bounding box
  28921. var oldQuaternion = mesh.rotationQuaternion;
  28922. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28923. mesh.computeWorldMatrix(true);
  28924. var bodyConfig = {
  28925. name: mesh.uniqueId,
  28926. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28927. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28928. move: options.mass != 0,
  28929. config: [options.mass, options.friction, options.restitution],
  28930. world: this._world
  28931. };
  28932. // register mesh
  28933. switch (impostor) {
  28934. case BABYLON.PhysicsEngine.SphereImpostor:
  28935. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28936. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28937. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28938. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28939. bodyConfig.type = 'sphere';
  28940. bodyConfig.size = [size];
  28941. break;
  28942. case BABYLON.PhysicsEngine.PlaneImpostor:
  28943. //Oimo "fakes" a cylinder as a box, so why don't we!
  28944. case BABYLON.PhysicsEngine.CylinderImpostor:
  28945. case BABYLON.PhysicsEngine.BoxImpostor:
  28946. var min = bbox.minimumWorld;
  28947. var max = bbox.maximumWorld;
  28948. var box = max.subtract(min);
  28949. var sizeX = this._checkWithEpsilon(box.x);
  28950. var sizeY = this._checkWithEpsilon(box.y);
  28951. var sizeZ = this._checkWithEpsilon(box.z);
  28952. bodyConfig.type = 'box';
  28953. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28954. break;
  28955. }
  28956. var body = new OIMO.Body(bodyConfig);
  28957. //We have to access the rigid body's properties to set the quaternion.
  28958. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28959. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28960. //TEST
  28961. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28962. //update the internal rotation matrix
  28963. //body.body.syncShapes();
  28964. this._registeredMeshes.push({
  28965. mesh: mesh,
  28966. body: body,
  28967. delta: deltaPosition
  28968. });
  28969. //for the sake of consistency.
  28970. mesh.rotationQuaternion = oldQuaternion;
  28971. return body;
  28972. };
  28973. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28974. var types = [], sizes = [], positions = [], rotations = [];
  28975. var initialMesh = parts[0].mesh;
  28976. for (var index = 0; index < parts.length; index++) {
  28977. var part = parts[index];
  28978. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28979. types.push(bodyParameters.type);
  28980. sizes.push.apply(sizes, bodyParameters.size);
  28981. positions.push.apply(positions, bodyParameters.pos);
  28982. rotations.push.apply(rotations, bodyParameters.rot);
  28983. }
  28984. var body = new OIMO.Body({
  28985. name: initialMesh.uniqueId,
  28986. type: types,
  28987. size: sizes,
  28988. pos: positions,
  28989. rot: rotations,
  28990. move: options.mass != 0,
  28991. config: [options.mass, options.friction, options.restitution],
  28992. world: this._world
  28993. });
  28994. //Reset the body's rotation to be of the initial mesh's.
  28995. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28996. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28997. this._registeredMeshes.push({
  28998. mesh: initialMesh,
  28999. body: body
  29000. });
  29001. return body;
  29002. };
  29003. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29004. var mesh = part.mesh;
  29005. if (!mesh.rotationQuaternion) {
  29006. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29007. }
  29008. // We need the bounding box/sphere info to compute the physics body
  29009. mesh.computeWorldMatrix(true);
  29010. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29011. var bodyParameters = {
  29012. name: mesh.uniqueId,
  29013. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29014. //A bug in Oimo (Body class) prevents us from using rot directly.
  29015. rot: [0, 0, 0],
  29016. //For future reference, if the bug will ever be fixed.
  29017. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29018. };
  29019. var oldQuaternion = mesh.rotationQuaternion;
  29020. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29021. mesh.computeWorldMatrix(true);
  29022. switch (part.impostor) {
  29023. case BABYLON.PhysicsEngine.SphereImpostor:
  29024. var bbox = mesh.getBoundingInfo().boundingBox;
  29025. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29026. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29027. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29028. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29029. bodyParameters.type = 'sphere';
  29030. bodyParameters.size = [size, size, size];
  29031. break;
  29032. case BABYLON.PhysicsEngine.PlaneImpostor:
  29033. case BABYLON.PhysicsEngine.CylinderImpostor:
  29034. case BABYLON.PhysicsEngine.BoxImpostor:
  29035. bbox = mesh.getBoundingInfo().boundingBox;
  29036. var min = bbox.minimumWorld;
  29037. var max = bbox.maximumWorld;
  29038. var box = max.subtract(min);
  29039. var sizeX = this._checkWithEpsilon(box.x);
  29040. var sizeY = this._checkWithEpsilon(box.y);
  29041. var sizeZ = this._checkWithEpsilon(box.z);
  29042. bodyParameters.type = 'box';
  29043. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29044. break;
  29045. }
  29046. mesh.rotationQuaternion = oldQuaternion;
  29047. return bodyParameters;
  29048. };
  29049. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29050. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29051. var registeredMesh = this._registeredMeshes[index];
  29052. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29053. if (registeredMesh.body) {
  29054. this._world.removeRigidBody(registeredMesh.body.body);
  29055. this._unbindBody(registeredMesh.body);
  29056. }
  29057. this._registeredMeshes.splice(index, 1);
  29058. return;
  29059. }
  29060. }
  29061. };
  29062. OimoJSPlugin.prototype._unbindBody = function (body) {
  29063. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29064. var registeredMesh = this._registeredMeshes[index];
  29065. if (registeredMesh.body === body) {
  29066. registeredMesh.body = null;
  29067. }
  29068. }
  29069. };
  29070. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29071. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29072. var registeredMesh = this._registeredMeshes[index];
  29073. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29074. // Get object mass to have a behaviour similar to cannon.js
  29075. var mass = registeredMesh.body.body.massInfo.mass;
  29076. // The force is scaled with the mass of object
  29077. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29078. return;
  29079. }
  29080. }
  29081. };
  29082. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29083. var body1 = null, body2 = null;
  29084. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29085. var registeredMesh = this._registeredMeshes[index];
  29086. if (registeredMesh.mesh === mesh1) {
  29087. body1 = registeredMesh.body.body;
  29088. }
  29089. else if (registeredMesh.mesh === mesh2) {
  29090. body2 = registeredMesh.body.body;
  29091. }
  29092. }
  29093. if (!body1 || !body2) {
  29094. return false;
  29095. }
  29096. if (!options) {
  29097. options = {};
  29098. }
  29099. new OIMO.Link({
  29100. type: options.type,
  29101. body1: body1,
  29102. body2: body2,
  29103. min: options.min,
  29104. max: options.max,
  29105. axe1: options.axe1,
  29106. axe2: options.axe2,
  29107. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29108. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29109. collision: options.collision,
  29110. spring: options.spring,
  29111. world: this._world
  29112. });
  29113. return true;
  29114. };
  29115. OimoJSPlugin.prototype.dispose = function () {
  29116. this._world.clear();
  29117. while (this._registeredMeshes.length) {
  29118. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29119. }
  29120. };
  29121. OimoJSPlugin.prototype.isSupported = function () {
  29122. return OIMO !== undefined;
  29123. };
  29124. OimoJSPlugin.prototype.getWorldObject = function () {
  29125. return this._world;
  29126. };
  29127. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29128. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29129. var registeredMesh = this._registeredMeshes[index];
  29130. if (registeredMesh.mesh === mesh) {
  29131. return registeredMesh.body;
  29132. }
  29133. }
  29134. return null;
  29135. };
  29136. OimoJSPlugin.prototype._getLastShape = function (body) {
  29137. var lastShape = body.shapes;
  29138. while (lastShape.next) {
  29139. lastShape = lastShape.next;
  29140. }
  29141. return lastShape;
  29142. };
  29143. OimoJSPlugin.prototype.runOneStep = function (time) {
  29144. this._world.step();
  29145. // Update the position of all registered meshes
  29146. var i = this._registeredMeshes.length;
  29147. var m;
  29148. while (i--) {
  29149. var body = this._registeredMeshes[i].body.body;
  29150. var mesh = this._registeredMeshes[i].mesh;
  29151. if (!this._registeredMeshes[i].delta) {
  29152. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29153. }
  29154. if (!body.sleeping) {
  29155. //TODO check that
  29156. if (body.shapes.next) {
  29157. var parentShape = this._getLastShape(body);
  29158. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29159. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29160. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29161. }
  29162. else {
  29163. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29164. }
  29165. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29166. mesh.computeWorldMatrix();
  29167. }
  29168. //check if the collide callback is set.
  29169. if (mesh.onPhysicsCollide) {
  29170. var meshUniqueName = mesh.uniqueId;
  29171. var contact = this._world.contacts;
  29172. while (contact !== null) {
  29173. //is this body colliding with any other?
  29174. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29175. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29176. //get the mesh and execute the callback
  29177. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29178. if (otherMesh)
  29179. mesh.onPhysicsCollide(otherMesh);
  29180. }
  29181. contact = contact.next;
  29182. }
  29183. }
  29184. }
  29185. };
  29186. return OimoJSPlugin;
  29187. })();
  29188. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29189. })(BABYLON || (BABYLON = {}));
  29190. var BABYLON;
  29191. (function (BABYLON) {
  29192. var DisplayPassPostProcess = (function (_super) {
  29193. __extends(DisplayPassPostProcess, _super);
  29194. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29195. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29196. }
  29197. return DisplayPassPostProcess;
  29198. })(BABYLON.PostProcess);
  29199. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29200. })(BABYLON || (BABYLON = {}));
  29201. var BABYLON;
  29202. (function (BABYLON) {
  29203. var SimplificationSettings = (function () {
  29204. function SimplificationSettings(quality, distance, optimizeMesh) {
  29205. this.quality = quality;
  29206. this.distance = distance;
  29207. this.optimizeMesh = optimizeMesh;
  29208. }
  29209. return SimplificationSettings;
  29210. })();
  29211. BABYLON.SimplificationSettings = SimplificationSettings;
  29212. var SimplificationQueue = (function () {
  29213. function SimplificationQueue() {
  29214. this.running = false;
  29215. this._simplificationArray = [];
  29216. }
  29217. SimplificationQueue.prototype.addTask = function (task) {
  29218. this._simplificationArray.push(task);
  29219. };
  29220. SimplificationQueue.prototype.executeNext = function () {
  29221. var task = this._simplificationArray.pop();
  29222. if (task) {
  29223. this.running = true;
  29224. this.runSimplification(task);
  29225. }
  29226. else {
  29227. this.running = false;
  29228. }
  29229. };
  29230. SimplificationQueue.prototype.runSimplification = function (task) {
  29231. var _this = this;
  29232. if (task.parallelProcessing) {
  29233. //parallel simplifier
  29234. task.settings.forEach(function (setting) {
  29235. var simplifier = _this.getSimplifier(task);
  29236. simplifier.simplify(setting, function (newMesh) {
  29237. task.mesh.addLODLevel(setting.distance, newMesh);
  29238. newMesh.isVisible = true;
  29239. //check if it is the last
  29240. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29241. //all done, run the success callback.
  29242. task.successCallback();
  29243. }
  29244. _this.executeNext();
  29245. });
  29246. });
  29247. }
  29248. else {
  29249. //single simplifier.
  29250. var simplifier = this.getSimplifier(task);
  29251. var runDecimation = function (setting, callback) {
  29252. simplifier.simplify(setting, function (newMesh) {
  29253. task.mesh.addLODLevel(setting.distance, newMesh);
  29254. newMesh.isVisible = true;
  29255. //run the next quality level
  29256. callback();
  29257. });
  29258. };
  29259. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29260. runDecimation(task.settings[loop.index], function () {
  29261. loop.executeNext();
  29262. });
  29263. }, function () {
  29264. //execution ended, run the success callback.
  29265. if (task.successCallback) {
  29266. task.successCallback();
  29267. }
  29268. _this.executeNext();
  29269. });
  29270. }
  29271. };
  29272. SimplificationQueue.prototype.getSimplifier = function (task) {
  29273. switch (task.simplificationType) {
  29274. case SimplificationType.QUADRATIC:
  29275. default:
  29276. return new QuadraticErrorSimplification(task.mesh);
  29277. }
  29278. };
  29279. return SimplificationQueue;
  29280. })();
  29281. BABYLON.SimplificationQueue = SimplificationQueue;
  29282. /**
  29283. * The implemented types of simplification.
  29284. * At the moment only Quadratic Error Decimation is implemented.
  29285. */
  29286. (function (SimplificationType) {
  29287. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29288. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29289. var SimplificationType = BABYLON.SimplificationType;
  29290. var DecimationTriangle = (function () {
  29291. function DecimationTriangle(vertices) {
  29292. this.vertices = vertices;
  29293. this.error = new Array(4);
  29294. this.deleted = false;
  29295. this.isDirty = false;
  29296. this.deletePending = false;
  29297. this.borderFactor = 0;
  29298. }
  29299. return DecimationTriangle;
  29300. })();
  29301. BABYLON.DecimationTriangle = DecimationTriangle;
  29302. var DecimationVertex = (function () {
  29303. function DecimationVertex(position, id) {
  29304. this.position = position;
  29305. this.id = id;
  29306. this.isBorder = true;
  29307. this.q = new QuadraticMatrix();
  29308. this.triangleCount = 0;
  29309. this.triangleStart = 0;
  29310. this.originalOffsets = [];
  29311. }
  29312. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29313. this.position.copyFrom(newPosition);
  29314. };
  29315. return DecimationVertex;
  29316. })();
  29317. BABYLON.DecimationVertex = DecimationVertex;
  29318. var QuadraticMatrix = (function () {
  29319. function QuadraticMatrix(data) {
  29320. this.data = new Array(10);
  29321. for (var i = 0; i < 10; ++i) {
  29322. if (data && data[i]) {
  29323. this.data[i] = data[i];
  29324. }
  29325. else {
  29326. this.data[i] = 0;
  29327. }
  29328. }
  29329. }
  29330. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29331. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29332. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29333. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29334. return det;
  29335. };
  29336. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29337. for (var i = 0; i < 10; ++i) {
  29338. this.data[i] += matrix.data[i];
  29339. }
  29340. };
  29341. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29342. for (var i = 0; i < 10; ++i) {
  29343. this.data[i] += data[i];
  29344. }
  29345. };
  29346. QuadraticMatrix.prototype.add = function (matrix) {
  29347. var m = new QuadraticMatrix();
  29348. for (var i = 0; i < 10; ++i) {
  29349. m.data[i] = this.data[i] + matrix.data[i];
  29350. }
  29351. return m;
  29352. };
  29353. QuadraticMatrix.FromData = function (a, b, c, d) {
  29354. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29355. };
  29356. //returning an array to avoid garbage collection
  29357. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29358. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29359. };
  29360. return QuadraticMatrix;
  29361. })();
  29362. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29363. var Reference = (function () {
  29364. function Reference(vertexId, triangleId) {
  29365. this.vertexId = vertexId;
  29366. this.triangleId = triangleId;
  29367. }
  29368. return Reference;
  29369. })();
  29370. BABYLON.Reference = Reference;
  29371. /**
  29372. * An implementation of the Quadratic Error simplification algorithm.
  29373. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29374. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29375. * @author RaananW
  29376. */
  29377. var QuadraticErrorSimplification = (function () {
  29378. function QuadraticErrorSimplification(_mesh) {
  29379. this._mesh = _mesh;
  29380. this.initialized = false;
  29381. this.syncIterations = 5000;
  29382. this.aggressiveness = 7;
  29383. this.decimationIterations = 100;
  29384. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29385. }
  29386. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29387. var _this = this;
  29388. this.initDecimatedMesh();
  29389. //iterating through the submeshes array, one after the other.
  29390. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29391. _this.initWithMesh(loop.index, function () {
  29392. _this.runDecimation(settings, loop.index, function () {
  29393. loop.executeNext();
  29394. });
  29395. }, settings.optimizeMesh);
  29396. }, function () {
  29397. setTimeout(function () {
  29398. successCallback(_this._reconstructedMesh);
  29399. }, 0);
  29400. });
  29401. };
  29402. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29403. var _this = this;
  29404. var gCount = 0;
  29405. triangle.vertices.forEach(function (vertex) {
  29406. var count = 0;
  29407. var vPos = vertex.position;
  29408. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29409. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29410. ++count;
  29411. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29412. ++count;
  29413. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29414. ++count;
  29415. if (count > 1) {
  29416. ++gCount;
  29417. }
  29418. ;
  29419. });
  29420. if (gCount > 1) {
  29421. console.log(triangle, gCount);
  29422. }
  29423. return gCount > 1;
  29424. };
  29425. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29426. var _this = this;
  29427. var targetCount = ~~(this.triangles.length * settings.quality);
  29428. var deletedTriangles = 0;
  29429. var triangleCount = this.triangles.length;
  29430. var iterationFunction = function (iteration, callback) {
  29431. setTimeout(function () {
  29432. if (iteration % 5 === 0) {
  29433. _this.updateMesh(iteration === 0);
  29434. }
  29435. for (var i = 0; i < _this.triangles.length; ++i) {
  29436. _this.triangles[i].isDirty = false;
  29437. }
  29438. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29439. var trianglesIterator = function (i) {
  29440. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29441. var t = _this.triangles[tIdx];
  29442. if (!t)
  29443. return;
  29444. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29445. return;
  29446. }
  29447. for (var j = 0; j < 3; ++j) {
  29448. if (t.error[j] < threshold) {
  29449. var deleted0 = [];
  29450. var deleted1 = [];
  29451. var v0 = t.vertices[j];
  29452. var v1 = t.vertices[(j + 1) % 3];
  29453. if (v0.isBorder !== v1.isBorder)
  29454. continue;
  29455. var p = BABYLON.Vector3.Zero();
  29456. var n = BABYLON.Vector3.Zero();
  29457. var uv = BABYLON.Vector2.Zero();
  29458. var color = new BABYLON.Color4(0, 0, 0, 1);
  29459. _this.calculateError(v0, v1, p, n, uv, color);
  29460. var delTr = [];
  29461. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29462. continue;
  29463. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29464. continue;
  29465. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29466. continue;
  29467. var uniqueArray = [];
  29468. delTr.forEach(function (deletedT) {
  29469. if (uniqueArray.indexOf(deletedT) === -1) {
  29470. deletedT.deletePending = true;
  29471. uniqueArray.push(deletedT);
  29472. }
  29473. });
  29474. if (uniqueArray.length % 2 !== 0) {
  29475. continue;
  29476. }
  29477. v0.q = v1.q.add(v0.q);
  29478. v0.updatePosition(p);
  29479. var tStart = _this.references.length;
  29480. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29481. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29482. var tCount = _this.references.length - tStart;
  29483. if (tCount <= v0.triangleCount) {
  29484. if (tCount) {
  29485. for (var c = 0; c < tCount; c++) {
  29486. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29487. }
  29488. }
  29489. }
  29490. else {
  29491. v0.triangleStart = tStart;
  29492. }
  29493. v0.triangleCount = tCount;
  29494. break;
  29495. }
  29496. }
  29497. };
  29498. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29499. }, 0);
  29500. };
  29501. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29502. if (triangleCount - deletedTriangles <= targetCount)
  29503. loop.breakLoop();
  29504. else {
  29505. iterationFunction(loop.index, function () {
  29506. loop.executeNext();
  29507. });
  29508. }
  29509. }, function () {
  29510. setTimeout(function () {
  29511. //reconstruct this part of the mesh
  29512. _this.reconstructMesh(submeshIndex);
  29513. successCallback();
  29514. }, 0);
  29515. });
  29516. };
  29517. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29518. var _this = this;
  29519. this.vertices = [];
  29520. this.triangles = [];
  29521. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29522. var indices = this._mesh.getIndices();
  29523. var submesh = this._mesh.subMeshes[submeshIndex];
  29524. var findInVertices = function (positionToSearch) {
  29525. if (optimizeMesh) {
  29526. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29527. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29528. return _this.vertices[ii];
  29529. }
  29530. }
  29531. }
  29532. return null;
  29533. };
  29534. var vertexReferences = [];
  29535. var vertexInit = function (i) {
  29536. var offset = i + submesh.verticesStart;
  29537. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29538. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29539. vertex.originalOffsets.push(offset);
  29540. if (vertex.id === _this.vertices.length) {
  29541. _this.vertices.push(vertex);
  29542. }
  29543. vertexReferences.push(vertex.id);
  29544. };
  29545. //var totalVertices = mesh.getTotalVertices();
  29546. var totalVertices = submesh.verticesCount;
  29547. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29548. var indicesInit = function (i) {
  29549. var offset = (submesh.indexStart / 3) + i;
  29550. var pos = (offset * 3);
  29551. var i0 = indices[pos + 0];
  29552. var i1 = indices[pos + 1];
  29553. var i2 = indices[pos + 2];
  29554. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29555. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29556. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29557. var triangle = new DecimationTriangle([v0, v1, v2]);
  29558. triangle.originalOffset = pos;
  29559. _this.triangles.push(triangle);
  29560. };
  29561. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29562. _this.init(callback);
  29563. });
  29564. });
  29565. };
  29566. QuadraticErrorSimplification.prototype.init = function (callback) {
  29567. var _this = this;
  29568. var triangleInit1 = function (i) {
  29569. var t = _this.triangles[i];
  29570. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29571. for (var j = 0; j < 3; j++) {
  29572. 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))));
  29573. }
  29574. };
  29575. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29576. var triangleInit2 = function (i) {
  29577. var t = _this.triangles[i];
  29578. for (var j = 0; j < 3; ++j) {
  29579. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29580. }
  29581. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29582. };
  29583. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29584. _this.initialized = true;
  29585. callback();
  29586. });
  29587. });
  29588. };
  29589. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29590. var newTriangles = [];
  29591. var i;
  29592. for (i = 0; i < this.vertices.length; ++i) {
  29593. this.vertices[i].triangleCount = 0;
  29594. }
  29595. var t;
  29596. var j;
  29597. for (i = 0; i < this.triangles.length; ++i) {
  29598. if (!this.triangles[i].deleted) {
  29599. t = this.triangles[i];
  29600. for (j = 0; j < 3; ++j) {
  29601. t.vertices[j].triangleCount = 1;
  29602. }
  29603. newTriangles.push(t);
  29604. }
  29605. }
  29606. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29607. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29608. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29609. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29610. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29611. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29612. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29613. var vertexCount = 0;
  29614. for (i = 0; i < this.vertices.length; ++i) {
  29615. var vertex = this.vertices[i];
  29616. vertex.id = vertexCount;
  29617. if (vertex.triangleCount) {
  29618. vertex.originalOffsets.forEach(function (originalOffset) {
  29619. newPositionData.push(vertex.position.x);
  29620. newPositionData.push(vertex.position.y);
  29621. newPositionData.push(vertex.position.z);
  29622. newNormalData.push(normalData[originalOffset * 3]);
  29623. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29624. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29625. if (uvs && uvs.length) {
  29626. newUVsData.push(uvs[(originalOffset * 2)]);
  29627. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29628. }
  29629. else if (colorsData && colorsData.length) {
  29630. newColorsData.push(colorsData[(originalOffset * 4)]);
  29631. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29632. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29633. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29634. }
  29635. ++vertexCount;
  29636. });
  29637. }
  29638. }
  29639. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29640. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29641. var submeshesArray = this._reconstructedMesh.subMeshes;
  29642. this._reconstructedMesh.subMeshes = [];
  29643. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29644. var originalIndices = this._mesh.getIndices();
  29645. for (i = 0; i < newTriangles.length; ++i) {
  29646. t = newTriangles[i]; //now get the new referencing point for each vertex
  29647. [0, 1, 2].forEach(function (idx) {
  29648. var id = originalIndices[t.originalOffset + idx];
  29649. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29650. if (offset < 0)
  29651. offset = 0;
  29652. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29653. });
  29654. }
  29655. //overwriting the old vertex buffers and indices.
  29656. this._reconstructedMesh.setIndices(newIndicesArray);
  29657. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29658. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29659. if (newUVsData.length > 0)
  29660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29661. if (newColorsData.length > 0)
  29662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29663. //create submesh
  29664. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29665. if (submeshIndex > 0) {
  29666. this._reconstructedMesh.subMeshes = [];
  29667. submeshesArray.forEach(function (submesh) {
  29668. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29669. });
  29670. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29671. }
  29672. };
  29673. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29674. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29675. this._reconstructedMesh.material = this._mesh.material;
  29676. this._reconstructedMesh.parent = this._mesh.parent;
  29677. this._reconstructedMesh.isVisible = false;
  29678. };
  29679. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29680. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29681. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29682. if (t.deleted)
  29683. continue;
  29684. var s = this.references[vertex1.triangleStart + i].vertexId;
  29685. var v1 = t.vertices[(s + 1) % 3];
  29686. var v2 = t.vertices[(s + 2) % 3];
  29687. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29688. deletedArray[i] = true;
  29689. delTr.push(t);
  29690. continue;
  29691. }
  29692. var d1 = v1.position.subtract(point);
  29693. d1 = d1.normalize();
  29694. var d2 = v2.position.subtract(point);
  29695. d2 = d2.normalize();
  29696. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29697. return true;
  29698. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29699. deletedArray[i] = false;
  29700. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29701. return true;
  29702. }
  29703. return false;
  29704. };
  29705. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29706. var newDeleted = deletedTriangles;
  29707. for (var i = 0; i < vertex.triangleCount; ++i) {
  29708. var ref = this.references[vertex.triangleStart + i];
  29709. var t = this.triangles[ref.triangleId];
  29710. if (t.deleted)
  29711. continue;
  29712. if (deletedArray[i] && t.deletePending) {
  29713. t.deleted = true;
  29714. newDeleted++;
  29715. continue;
  29716. }
  29717. t.vertices[ref.vertexId] = origVertex;
  29718. t.isDirty = true;
  29719. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29720. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29721. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29722. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29723. this.references.push(ref);
  29724. }
  29725. return newDeleted;
  29726. };
  29727. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29728. for (var i = 0; i < this.vertices.length; ++i) {
  29729. var vCount = [];
  29730. var vId = [];
  29731. var v = this.vertices[i];
  29732. var j;
  29733. for (j = 0; j < v.triangleCount; ++j) {
  29734. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29735. for (var ii = 0; ii < 3; ii++) {
  29736. var ofs = 0;
  29737. var vv = triangle.vertices[ii];
  29738. while (ofs < vCount.length) {
  29739. if (vId[ofs] === vv.id)
  29740. break;
  29741. ++ofs;
  29742. }
  29743. if (ofs === vCount.length) {
  29744. vCount.push(1);
  29745. vId.push(vv.id);
  29746. }
  29747. else {
  29748. vCount[ofs]++;
  29749. }
  29750. }
  29751. }
  29752. for (j = 0; j < vCount.length; ++j) {
  29753. if (vCount[j] === 1) {
  29754. this.vertices[vId[j]].isBorder = true;
  29755. }
  29756. else {
  29757. this.vertices[vId[j]].isBorder = false;
  29758. }
  29759. }
  29760. }
  29761. };
  29762. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29763. if (identifyBorders === void 0) { identifyBorders = false; }
  29764. var i;
  29765. if (!identifyBorders) {
  29766. var newTrianglesVector = [];
  29767. for (i = 0; i < this.triangles.length; ++i) {
  29768. if (!this.triangles[i].deleted) {
  29769. newTrianglesVector.push(this.triangles[i]);
  29770. }
  29771. }
  29772. this.triangles = newTrianglesVector;
  29773. }
  29774. for (i = 0; i < this.vertices.length; ++i) {
  29775. this.vertices[i].triangleCount = 0;
  29776. this.vertices[i].triangleStart = 0;
  29777. }
  29778. var t;
  29779. var j;
  29780. var v;
  29781. for (i = 0; i < this.triangles.length; ++i) {
  29782. t = this.triangles[i];
  29783. for (j = 0; j < 3; ++j) {
  29784. v = t.vertices[j];
  29785. v.triangleCount++;
  29786. }
  29787. }
  29788. var tStart = 0;
  29789. for (i = 0; i < this.vertices.length; ++i) {
  29790. this.vertices[i].triangleStart = tStart;
  29791. tStart += this.vertices[i].triangleCount;
  29792. this.vertices[i].triangleCount = 0;
  29793. }
  29794. var newReferences = new Array(this.triangles.length * 3);
  29795. for (i = 0; i < this.triangles.length; ++i) {
  29796. t = this.triangles[i];
  29797. for (j = 0; j < 3; ++j) {
  29798. v = t.vertices[j];
  29799. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29800. v.triangleCount++;
  29801. }
  29802. }
  29803. this.references = newReferences;
  29804. if (identifyBorders) {
  29805. this.identifyBorder();
  29806. }
  29807. };
  29808. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29809. var x = point.x;
  29810. var y = point.y;
  29811. var z = point.z;
  29812. 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
  29813. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29814. };
  29815. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29816. var q = vertex1.q.add(vertex2.q);
  29817. var border = vertex1.isBorder && vertex2.isBorder;
  29818. var error = 0;
  29819. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29820. if (qDet !== 0 && !border) {
  29821. if (!pointResult) {
  29822. pointResult = BABYLON.Vector3.Zero();
  29823. }
  29824. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29825. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29826. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29827. error = this.vertexError(q, pointResult);
  29828. }
  29829. else {
  29830. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29831. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29832. var error1 = this.vertexError(q, vertex1.position);
  29833. var error2 = this.vertexError(q, vertex2.position);
  29834. var error3 = this.vertexError(q, p3);
  29835. error = Math.min(error1, error2, error3);
  29836. if (error === error1) {
  29837. if (pointResult) {
  29838. pointResult.copyFrom(vertex1.position);
  29839. }
  29840. }
  29841. else if (error === error2) {
  29842. if (pointResult) {
  29843. pointResult.copyFrom(vertex2.position);
  29844. }
  29845. }
  29846. else {
  29847. if (pointResult) {
  29848. pointResult.copyFrom(p3);
  29849. }
  29850. }
  29851. }
  29852. return error;
  29853. };
  29854. return QuadraticErrorSimplification;
  29855. })();
  29856. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29857. })(BABYLON || (BABYLON = {}));
  29858. var BABYLON;
  29859. (function (BABYLON) {
  29860. var serializedGeometries = [];
  29861. var serializeGeometry = function (geometry, serializationGeometries) {
  29862. if (serializedGeometries[geometry.id]) {
  29863. return;
  29864. }
  29865. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29866. serializationGeometries.boxes.push(geometry.serialize());
  29867. }
  29868. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29869. serializationGeometries.spheres.push(geometry.serialize());
  29870. }
  29871. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29872. serializationGeometries.cylinders.push(geometry.serialize());
  29873. }
  29874. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29875. serializationGeometries.toruses.push(geometry.serialize());
  29876. }
  29877. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29878. serializationGeometries.grounds.push(geometry.serialize());
  29879. }
  29880. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29881. serializationGeometries.planes.push(geometry.serialize());
  29882. }
  29883. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29884. serializationGeometries.torusKnots.push(geometry.serialize());
  29885. }
  29886. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29887. throw new Error("Unknown primitive type");
  29888. }
  29889. else {
  29890. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  29891. }
  29892. serializedGeometries[geometry.id] = true;
  29893. };
  29894. var serializeMesh = function (mesh, serializationScene) {
  29895. var serializationObject = {};
  29896. serializationObject.name = mesh.name;
  29897. serializationObject.id = mesh.id;
  29898. if (BABYLON.Tags.HasTags(mesh)) {
  29899. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29900. }
  29901. serializationObject.position = mesh.position.asArray();
  29902. if (mesh.rotationQuaternion) {
  29903. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29904. }
  29905. else if (mesh.rotation) {
  29906. serializationObject.rotation = mesh.rotation.asArray();
  29907. }
  29908. serializationObject.scaling = mesh.scaling.asArray();
  29909. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29910. serializationObject.isEnabled = mesh.isEnabled();
  29911. serializationObject.isVisible = mesh.isVisible;
  29912. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29913. serializationObject.pickable = mesh.isPickable;
  29914. serializationObject.receiveShadows = mesh.receiveShadows;
  29915. serializationObject.billboardMode = mesh.billboardMode;
  29916. serializationObject.visibility = mesh.visibility;
  29917. serializationObject.checkCollisions = mesh.checkCollisions;
  29918. // Parent
  29919. if (mesh.parent) {
  29920. serializationObject.parentId = mesh.parent.id;
  29921. }
  29922. // Geometry
  29923. var geometry = mesh._geometry;
  29924. if (geometry) {
  29925. var geometryId = geometry.id;
  29926. serializationObject.geometryId = geometryId;
  29927. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29928. // 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
  29929. serializeGeometry(geometry, serializationScene.geometries);
  29930. }
  29931. // SubMeshes
  29932. serializationObject.subMeshes = [];
  29933. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29934. var subMesh = mesh.subMeshes[subIndex];
  29935. serializationObject.subMeshes.push({
  29936. materialIndex: subMesh.materialIndex,
  29937. verticesStart: subMesh.verticesStart,
  29938. verticesCount: subMesh.verticesCount,
  29939. indexStart: subMesh.indexStart,
  29940. indexCount: subMesh.indexCount
  29941. });
  29942. }
  29943. }
  29944. // Material
  29945. if (mesh.material) {
  29946. serializationObject.materialId = mesh.material.id;
  29947. }
  29948. else {
  29949. mesh.material = null;
  29950. }
  29951. // Skeleton
  29952. if (mesh.skeleton) {
  29953. serializationObject.skeletonId = mesh.skeleton.id;
  29954. }
  29955. // Physics
  29956. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29957. serializationObject.physicsMass = mesh.getPhysicsMass();
  29958. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29959. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29960. switch (mesh.getPhysicsImpostor()) {
  29961. case BABYLON.PhysicsEngine.BoxImpostor:
  29962. serializationObject.physicsImpostor = 1;
  29963. break;
  29964. case BABYLON.PhysicsEngine.SphereImpostor:
  29965. serializationObject.physicsImpostor = 2;
  29966. break;
  29967. }
  29968. }
  29969. // Instances
  29970. serializationObject.instances = [];
  29971. for (var index = 0; index < mesh.instances.length; index++) {
  29972. var instance = mesh.instances[index];
  29973. var serializationInstance = {
  29974. name: instance.name,
  29975. position: instance.position.asArray(),
  29976. scaling: instance.scaling.asArray()
  29977. };
  29978. if (instance.rotationQuaternion) {
  29979. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29980. }
  29981. else if (instance.rotation) {
  29982. serializationInstance.rotation = instance.rotation.asArray();
  29983. }
  29984. serializationObject.instances.push(serializationInstance);
  29985. // Animations
  29986. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29987. }
  29988. // Animations
  29989. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  29990. // Layer mask
  29991. serializationObject.layerMask = mesh.layerMask;
  29992. return serializationObject;
  29993. };
  29994. var finalizeSingleMesh = function (mesh, serializationObject) {
  29995. //only works if the mesh is already loaded
  29996. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29997. //serialize material
  29998. if (mesh.material) {
  29999. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30000. serializationObject.materials = serializationObject.materials || [];
  30001. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30002. serializationObject.materials.push(mesh.material.serialize());
  30003. }
  30004. }
  30005. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30006. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30007. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30008. serializationObject.multiMaterials.push(mesh.material.serialize());
  30009. }
  30010. }
  30011. }
  30012. //serialize geometry
  30013. var geometry = mesh._geometry;
  30014. if (geometry) {
  30015. if (!serializationObject.geometries) {
  30016. serializationObject.geometries = {};
  30017. serializationObject.geometries.boxes = [];
  30018. serializationObject.geometries.spheres = [];
  30019. serializationObject.geometries.cylinders = [];
  30020. serializationObject.geometries.toruses = [];
  30021. serializationObject.geometries.grounds = [];
  30022. serializationObject.geometries.planes = [];
  30023. serializationObject.geometries.torusKnots = [];
  30024. serializationObject.geometries.vertexData = [];
  30025. }
  30026. serializeGeometry(geometry, serializationObject.geometries);
  30027. }
  30028. // Skeletons
  30029. if (mesh.skeleton) {
  30030. serializationObject.skeletons = serializationObject.skeletons || [];
  30031. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30032. }
  30033. //serialize the actual mesh
  30034. serializationObject.meshes = serializationObject.meshes || [];
  30035. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30036. }
  30037. };
  30038. var SceneSerializer = (function () {
  30039. function SceneSerializer() {
  30040. }
  30041. SceneSerializer.Serialize = function (scene) {
  30042. var serializationObject = {};
  30043. // Scene
  30044. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30045. serializationObject.autoClear = scene.autoClear;
  30046. serializationObject.clearColor = scene.clearColor.asArray();
  30047. serializationObject.ambientColor = scene.ambientColor.asArray();
  30048. serializationObject.gravity = scene.gravity.asArray();
  30049. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30050. serializationObject.workerCollisions = scene.workerCollisions;
  30051. // Fog
  30052. if (scene.fogMode && scene.fogMode !== 0) {
  30053. serializationObject.fogMode = scene.fogMode;
  30054. serializationObject.fogColor = scene.fogColor.asArray();
  30055. serializationObject.fogStart = scene.fogStart;
  30056. serializationObject.fogEnd = scene.fogEnd;
  30057. serializationObject.fogDensity = scene.fogDensity;
  30058. }
  30059. //Physics
  30060. if (scene.isPhysicsEnabled()) {
  30061. serializationObject.physicsEnabled = true;
  30062. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30063. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30064. }
  30065. // Lights
  30066. serializationObject.lights = [];
  30067. var index;
  30068. var light;
  30069. for (index = 0; index < scene.lights.length; index++) {
  30070. light = scene.lights[index];
  30071. serializationObject.lights.push(light.serialize());
  30072. }
  30073. // Cameras
  30074. serializationObject.cameras = [];
  30075. for (index = 0; index < scene.cameras.length; index++) {
  30076. var camera = scene.cameras[index];
  30077. serializationObject.cameras.push(camera.serialize());
  30078. }
  30079. if (scene.activeCamera) {
  30080. serializationObject.activeCameraID = scene.activeCamera.id;
  30081. }
  30082. // Materials
  30083. serializationObject.materials = [];
  30084. serializationObject.multiMaterials = [];
  30085. var material;
  30086. for (index = 0; index < scene.materials.length; index++) {
  30087. material = scene.materials[index];
  30088. serializationObject.materials.push(material.serialize());
  30089. }
  30090. // MultiMaterials
  30091. serializationObject.multiMaterials = [];
  30092. for (index = 0; index < scene.multiMaterials.length; index++) {
  30093. var multiMaterial = scene.multiMaterials[index];
  30094. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30095. }
  30096. for (index = 0; index < scene.materials.length; index++) {
  30097. material = scene.materials[index];
  30098. serializationObject.materials.push(material.serialize());
  30099. }
  30100. // Skeletons
  30101. serializationObject.skeletons = [];
  30102. for (index = 0; index < scene.skeletons.length; index++) {
  30103. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30104. }
  30105. // Geometries
  30106. serializationObject.geometries = {};
  30107. serializationObject.geometries.boxes = [];
  30108. serializationObject.geometries.spheres = [];
  30109. serializationObject.geometries.cylinders = [];
  30110. serializationObject.geometries.toruses = [];
  30111. serializationObject.geometries.grounds = [];
  30112. serializationObject.geometries.planes = [];
  30113. serializationObject.geometries.torusKnots = [];
  30114. serializationObject.geometries.vertexData = [];
  30115. serializedGeometries = [];
  30116. var geometries = scene.getGeometries();
  30117. for (index = 0; index < geometries.length; index++) {
  30118. var geometry = geometries[index];
  30119. if (geometry.isReady()) {
  30120. serializeGeometry(geometry, serializationObject.geometries);
  30121. }
  30122. }
  30123. // Meshes
  30124. serializationObject.meshes = [];
  30125. for (index = 0; index < scene.meshes.length; index++) {
  30126. var abstractMesh = scene.meshes[index];
  30127. if (abstractMesh instanceof BABYLON.Mesh) {
  30128. var mesh = abstractMesh;
  30129. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30130. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30131. }
  30132. }
  30133. }
  30134. // Particles Systems
  30135. serializationObject.particleSystems = [];
  30136. for (index = 0; index < scene.particleSystems.length; index++) {
  30137. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30138. }
  30139. // Lens flares
  30140. serializationObject.lensFlareSystems = [];
  30141. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30142. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30143. }
  30144. // Shadows
  30145. serializationObject.shadowGenerators = [];
  30146. for (index = 0; index < scene.lights.length; index++) {
  30147. light = scene.lights[index];
  30148. if (light.getShadowGenerator()) {
  30149. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30150. }
  30151. }
  30152. return serializationObject;
  30153. };
  30154. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30155. if (withParents === void 0) { withParents = false; }
  30156. if (withChildren === void 0) { withChildren = false; }
  30157. var serializationObject = {};
  30158. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30159. if (withParents || withChildren) {
  30160. //deliberate for loop! not for each, appended should be processed as well.
  30161. for (var i = 0; i < toSerialize.length; ++i) {
  30162. if (withChildren) {
  30163. toSerialize[i].getDescendants().forEach(function (node) {
  30164. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30165. toSerialize.push(node);
  30166. }
  30167. });
  30168. }
  30169. //make sure the array doesn't contain the object already
  30170. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30171. toSerialize.push(toSerialize[i].parent);
  30172. }
  30173. }
  30174. }
  30175. toSerialize.forEach(function (mesh) {
  30176. finalizeSingleMesh(mesh, serializationObject);
  30177. });
  30178. return serializationObject;
  30179. };
  30180. return SceneSerializer;
  30181. })();
  30182. BABYLON.SceneSerializer = SceneSerializer;
  30183. })(BABYLON || (BABYLON = {}));
  30184. var BABYLON;
  30185. (function (BABYLON) {
  30186. // Unique ID when we import meshes from Babylon to CSG
  30187. var currentCSGMeshId = 0;
  30188. // # class Vertex
  30189. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30190. // one to provide additional features like texture coordinates and vertex
  30191. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30192. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30193. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30194. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30195. // is not used anywhere else.
  30196. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30197. var Vertex = (function () {
  30198. function Vertex(pos, normal, uv) {
  30199. this.pos = pos;
  30200. this.normal = normal;
  30201. this.uv = uv;
  30202. }
  30203. Vertex.prototype.clone = function () {
  30204. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30205. };
  30206. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30207. // orientation of a polygon is flipped.
  30208. Vertex.prototype.flip = function () {
  30209. this.normal = this.normal.scale(-1);
  30210. };
  30211. // Create a new vertex between this vertex and `other` by linearly
  30212. // interpolating all properties using a parameter of `t`. Subclasses should
  30213. // override this to interpolate additional properties.
  30214. Vertex.prototype.interpolate = function (other, t) {
  30215. 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));
  30216. };
  30217. return Vertex;
  30218. })();
  30219. // # class Plane
  30220. // Represents a plane in 3D space.
  30221. var Plane = (function () {
  30222. function Plane(normal, w) {
  30223. this.normal = normal;
  30224. this.w = w;
  30225. }
  30226. Plane.FromPoints = function (a, b, c) {
  30227. var v0 = c.subtract(a);
  30228. var v1 = b.subtract(a);
  30229. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30230. return null;
  30231. }
  30232. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30233. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30234. };
  30235. Plane.prototype.clone = function () {
  30236. return new Plane(this.normal.clone(), this.w);
  30237. };
  30238. Plane.prototype.flip = function () {
  30239. this.normal.scaleInPlace(-1);
  30240. this.w = -this.w;
  30241. };
  30242. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30243. // fragments in the appropriate lists. Coplanar polygons go into either
  30244. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30245. // respect to this plane. Polygons in front or in back of this plane go into
  30246. // either `front` or `back`.
  30247. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30248. var COPLANAR = 0;
  30249. var FRONT = 1;
  30250. var BACK = 2;
  30251. var SPANNING = 3;
  30252. // Classify each point as well as the entire polygon into one of the above
  30253. // four classes.
  30254. var polygonType = 0;
  30255. var types = [];
  30256. var i;
  30257. var t;
  30258. for (i = 0; i < polygon.vertices.length; i++) {
  30259. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30260. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30261. polygonType |= type;
  30262. types.push(type);
  30263. }
  30264. // Put the polygon in the correct list, splitting it when necessary.
  30265. switch (polygonType) {
  30266. case COPLANAR:
  30267. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30268. break;
  30269. case FRONT:
  30270. front.push(polygon);
  30271. break;
  30272. case BACK:
  30273. back.push(polygon);
  30274. break;
  30275. case SPANNING:
  30276. var f = [], b = [];
  30277. for (i = 0; i < polygon.vertices.length; i++) {
  30278. var j = (i + 1) % polygon.vertices.length;
  30279. var ti = types[i], tj = types[j];
  30280. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30281. if (ti !== BACK)
  30282. f.push(vi);
  30283. if (ti !== FRONT)
  30284. b.push(ti !== BACK ? vi.clone() : vi);
  30285. if ((ti | tj) === SPANNING) {
  30286. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30287. var v = vi.interpolate(vj, t);
  30288. f.push(v);
  30289. b.push(v.clone());
  30290. }
  30291. }
  30292. var poly;
  30293. if (f.length >= 3) {
  30294. poly = new Polygon(f, polygon.shared);
  30295. if (poly.plane)
  30296. front.push(poly);
  30297. }
  30298. if (b.length >= 3) {
  30299. poly = new Polygon(b, polygon.shared);
  30300. if (poly.plane)
  30301. back.push(poly);
  30302. }
  30303. break;
  30304. }
  30305. };
  30306. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30307. // point is on the plane.
  30308. Plane.EPSILON = 1e-5;
  30309. return Plane;
  30310. })();
  30311. // # class Polygon
  30312. // Represents a convex polygon. The vertices used to initialize a polygon must
  30313. // be coplanar and form a convex loop.
  30314. //
  30315. // Each convex polygon has a `shared` property, which is shared between all
  30316. // polygons that are clones of each other or were split from the same polygon.
  30317. // This can be used to define per-polygon properties (such as surface color).
  30318. var Polygon = (function () {
  30319. function Polygon(vertices, shared) {
  30320. this.vertices = vertices;
  30321. this.shared = shared;
  30322. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30323. }
  30324. Polygon.prototype.clone = function () {
  30325. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30326. return new Polygon(vertices, this.shared);
  30327. };
  30328. Polygon.prototype.flip = function () {
  30329. this.vertices.reverse().map(function (v) { v.flip(); });
  30330. this.plane.flip();
  30331. };
  30332. return Polygon;
  30333. })();
  30334. // # class Node
  30335. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30336. // by picking a polygon to split along. That polygon (and all other coplanar
  30337. // polygons) are added directly to that node and the other polygons are added to
  30338. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30339. // no distinction between internal and leaf nodes.
  30340. var Node = (function () {
  30341. function Node(polygons) {
  30342. this.plane = null;
  30343. this.front = null;
  30344. this.back = null;
  30345. this.polygons = [];
  30346. if (polygons) {
  30347. this.build(polygons);
  30348. }
  30349. }
  30350. Node.prototype.clone = function () {
  30351. var node = new Node();
  30352. node.plane = this.plane && this.plane.clone();
  30353. node.front = this.front && this.front.clone();
  30354. node.back = this.back && this.back.clone();
  30355. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30356. return node;
  30357. };
  30358. // Convert solid space to empty space and empty space to solid space.
  30359. Node.prototype.invert = function () {
  30360. for (var i = 0; i < this.polygons.length; i++) {
  30361. this.polygons[i].flip();
  30362. }
  30363. if (this.plane) {
  30364. this.plane.flip();
  30365. }
  30366. if (this.front) {
  30367. this.front.invert();
  30368. }
  30369. if (this.back) {
  30370. this.back.invert();
  30371. }
  30372. var temp = this.front;
  30373. this.front = this.back;
  30374. this.back = temp;
  30375. };
  30376. // Recursively remove all polygons in `polygons` that are inside this BSP
  30377. // tree.
  30378. Node.prototype.clipPolygons = function (polygons) {
  30379. if (!this.plane)
  30380. return polygons.slice();
  30381. var front = [], back = [];
  30382. for (var i = 0; i < polygons.length; i++) {
  30383. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30384. }
  30385. if (this.front) {
  30386. front = this.front.clipPolygons(front);
  30387. }
  30388. if (this.back) {
  30389. back = this.back.clipPolygons(back);
  30390. }
  30391. else {
  30392. back = [];
  30393. }
  30394. return front.concat(back);
  30395. };
  30396. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30397. // `bsp`.
  30398. Node.prototype.clipTo = function (bsp) {
  30399. this.polygons = bsp.clipPolygons(this.polygons);
  30400. if (this.front)
  30401. this.front.clipTo(bsp);
  30402. if (this.back)
  30403. this.back.clipTo(bsp);
  30404. };
  30405. // Return a list of all polygons in this BSP tree.
  30406. Node.prototype.allPolygons = function () {
  30407. var polygons = this.polygons.slice();
  30408. if (this.front)
  30409. polygons = polygons.concat(this.front.allPolygons());
  30410. if (this.back)
  30411. polygons = polygons.concat(this.back.allPolygons());
  30412. return polygons;
  30413. };
  30414. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30415. // new polygons are filtered down to the bottom of the tree and become new
  30416. // nodes there. Each set of polygons is partitioned using the first polygon
  30417. // (no heuristic is used to pick a good split).
  30418. Node.prototype.build = function (polygons) {
  30419. if (!polygons.length)
  30420. return;
  30421. if (!this.plane)
  30422. this.plane = polygons[0].plane.clone();
  30423. var front = [], back = [];
  30424. for (var i = 0; i < polygons.length; i++) {
  30425. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30426. }
  30427. if (front.length) {
  30428. if (!this.front)
  30429. this.front = new Node();
  30430. this.front.build(front);
  30431. }
  30432. if (back.length) {
  30433. if (!this.back)
  30434. this.back = new Node();
  30435. this.back.build(back);
  30436. }
  30437. };
  30438. return Node;
  30439. })();
  30440. var CSG = (function () {
  30441. function CSG() {
  30442. this.polygons = new Array();
  30443. }
  30444. // Convert BABYLON.Mesh to BABYLON.CSG
  30445. CSG.FromMesh = function (mesh) {
  30446. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30447. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30448. if (mesh instanceof BABYLON.Mesh) {
  30449. mesh.computeWorldMatrix(true);
  30450. matrix = mesh.getWorldMatrix();
  30451. meshPosition = mesh.position.clone();
  30452. meshRotation = mesh.rotation.clone();
  30453. if (mesh.rotationQuaternion) {
  30454. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30455. }
  30456. meshScaling = mesh.scaling.clone();
  30457. }
  30458. else {
  30459. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30460. }
  30461. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30462. var subMeshes = mesh.subMeshes;
  30463. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30464. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30465. vertices = [];
  30466. for (var j = 0; j < 3; j++) {
  30467. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30468. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30469. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30470. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30471. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30472. vertex = new Vertex(position, normal, uv);
  30473. vertices.push(vertex);
  30474. }
  30475. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30476. // To handle the case of degenerated triangle
  30477. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30478. if (polygon.plane)
  30479. polygons.push(polygon);
  30480. }
  30481. }
  30482. var csg = CSG.FromPolygons(polygons);
  30483. csg.matrix = matrix;
  30484. csg.position = meshPosition;
  30485. csg.rotation = meshRotation;
  30486. csg.scaling = meshScaling;
  30487. csg.rotationQuaternion = meshRotationQuaternion;
  30488. currentCSGMeshId++;
  30489. return csg;
  30490. };
  30491. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30492. CSG.FromPolygons = function (polygons) {
  30493. var csg = new CSG();
  30494. csg.polygons = polygons;
  30495. return csg;
  30496. };
  30497. CSG.prototype.clone = function () {
  30498. var csg = new CSG();
  30499. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30500. csg.copyTransformAttributes(this);
  30501. return csg;
  30502. };
  30503. CSG.prototype.toPolygons = function () {
  30504. return this.polygons;
  30505. };
  30506. CSG.prototype.union = function (csg) {
  30507. var a = new Node(this.clone().polygons);
  30508. var b = new Node(csg.clone().polygons);
  30509. a.clipTo(b);
  30510. b.clipTo(a);
  30511. b.invert();
  30512. b.clipTo(a);
  30513. b.invert();
  30514. a.build(b.allPolygons());
  30515. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30516. };
  30517. CSG.prototype.unionInPlace = function (csg) {
  30518. var a = new Node(this.polygons);
  30519. var b = new Node(csg.polygons);
  30520. a.clipTo(b);
  30521. b.clipTo(a);
  30522. b.invert();
  30523. b.clipTo(a);
  30524. b.invert();
  30525. a.build(b.allPolygons());
  30526. this.polygons = a.allPolygons();
  30527. };
  30528. CSG.prototype.subtract = function (csg) {
  30529. var a = new Node(this.clone().polygons);
  30530. var b = new Node(csg.clone().polygons);
  30531. a.invert();
  30532. a.clipTo(b);
  30533. b.clipTo(a);
  30534. b.invert();
  30535. b.clipTo(a);
  30536. b.invert();
  30537. a.build(b.allPolygons());
  30538. a.invert();
  30539. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30540. };
  30541. CSG.prototype.subtractInPlace = function (csg) {
  30542. var a = new Node(this.polygons);
  30543. var b = new Node(csg.polygons);
  30544. a.invert();
  30545. a.clipTo(b);
  30546. b.clipTo(a);
  30547. b.invert();
  30548. b.clipTo(a);
  30549. b.invert();
  30550. a.build(b.allPolygons());
  30551. a.invert();
  30552. this.polygons = a.allPolygons();
  30553. };
  30554. CSG.prototype.intersect = function (csg) {
  30555. var a = new Node(this.clone().polygons);
  30556. var b = new Node(csg.clone().polygons);
  30557. a.invert();
  30558. b.clipTo(a);
  30559. b.invert();
  30560. a.clipTo(b);
  30561. b.clipTo(a);
  30562. a.build(b.allPolygons());
  30563. a.invert();
  30564. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30565. };
  30566. CSG.prototype.intersectInPlace = function (csg) {
  30567. var a = new Node(this.polygons);
  30568. var b = new Node(csg.polygons);
  30569. a.invert();
  30570. b.clipTo(a);
  30571. b.invert();
  30572. a.clipTo(b);
  30573. b.clipTo(a);
  30574. a.build(b.allPolygons());
  30575. a.invert();
  30576. this.polygons = a.allPolygons();
  30577. };
  30578. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30579. // not modified.
  30580. CSG.prototype.inverse = function () {
  30581. var csg = this.clone();
  30582. csg.inverseInPlace();
  30583. return csg;
  30584. };
  30585. CSG.prototype.inverseInPlace = function () {
  30586. this.polygons.map(function (p) { p.flip(); });
  30587. };
  30588. // This is used to keep meshes transformations so they can be restored
  30589. // when we build back a Babylon Mesh
  30590. // NB : All CSG operations are performed in world coordinates
  30591. CSG.prototype.copyTransformAttributes = function (csg) {
  30592. this.matrix = csg.matrix;
  30593. this.position = csg.position;
  30594. this.rotation = csg.rotation;
  30595. this.scaling = csg.scaling;
  30596. this.rotationQuaternion = csg.rotationQuaternion;
  30597. return this;
  30598. };
  30599. // Build Raw mesh from CSG
  30600. // Coordinates here are in world space
  30601. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30602. var matrix = this.matrix.clone();
  30603. matrix.invert();
  30604. 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;
  30605. if (keepSubMeshes) {
  30606. // Sort Polygons, since subMeshes are indices range
  30607. polygons.sort(function (a, b) {
  30608. if (a.shared.meshId === b.shared.meshId) {
  30609. return a.shared.subMeshId - b.shared.subMeshId;
  30610. }
  30611. else {
  30612. return a.shared.meshId - b.shared.meshId;
  30613. }
  30614. });
  30615. }
  30616. for (var i = 0, il = polygons.length; i < il; i++) {
  30617. polygon = polygons[i];
  30618. // Building SubMeshes
  30619. if (!subMesh_dict[polygon.shared.meshId]) {
  30620. subMesh_dict[polygon.shared.meshId] = {};
  30621. }
  30622. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30623. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30624. indexStart: +Infinity,
  30625. indexEnd: -Infinity,
  30626. materialIndex: polygon.shared.materialIndex
  30627. };
  30628. }
  30629. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30630. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30631. polygonIndices[0] = 0;
  30632. polygonIndices[1] = j - 1;
  30633. polygonIndices[2] = j;
  30634. for (var k = 0; k < 3; k++) {
  30635. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30636. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30637. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30638. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30639. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30640. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30641. // Check if 2 points can be merged
  30642. if (!(typeof vertex_idx !== 'undefined' &&
  30643. normals[vertex_idx * 3] === localNormal.x &&
  30644. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30645. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30646. uvs[vertex_idx * 2] === uv.x &&
  30647. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30648. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30649. uvs.push(uv.x, uv.y);
  30650. normals.push(normal.x, normal.y, normal.z);
  30651. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30652. }
  30653. indices.push(vertex_idx);
  30654. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30655. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30656. currentIndex++;
  30657. }
  30658. }
  30659. }
  30660. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30661. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30662. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30663. mesh.setIndices(indices);
  30664. if (keepSubMeshes) {
  30665. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30666. var materialIndexOffset = 0, materialMaxIndex;
  30667. mesh.subMeshes = new Array();
  30668. for (var m in subMesh_dict) {
  30669. materialMaxIndex = -1;
  30670. for (var sm in subMesh_dict[m]) {
  30671. subMesh_obj = subMesh_dict[m][sm];
  30672. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30673. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30674. }
  30675. materialIndexOffset += ++materialMaxIndex;
  30676. }
  30677. }
  30678. return mesh;
  30679. };
  30680. // Build Mesh from CSG taking material and transforms into account
  30681. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30682. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30683. mesh.material = material;
  30684. mesh.position.copyFrom(this.position);
  30685. mesh.rotation.copyFrom(this.rotation);
  30686. if (this.rotationQuaternion) {
  30687. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30688. }
  30689. mesh.scaling.copyFrom(this.scaling);
  30690. mesh.computeWorldMatrix(true);
  30691. return mesh;
  30692. };
  30693. return CSG;
  30694. })();
  30695. BABYLON.CSG = CSG;
  30696. })(BABYLON || (BABYLON = {}));
  30697. var BABYLON;
  30698. (function (BABYLON) {
  30699. var VRDistortionCorrectionPostProcess = (function (_super) {
  30700. __extends(VRDistortionCorrectionPostProcess, _super);
  30701. //ANY
  30702. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30703. var _this = this;
  30704. _super.call(this, name, "vrDistortionCorrection", [
  30705. 'LensCenter',
  30706. 'Scale',
  30707. 'ScaleIn',
  30708. 'HmdWarpParam'
  30709. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30710. this._isRightEye = isRightEye;
  30711. this._distortionFactors = vrMetrics.distortionK;
  30712. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30713. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30714. this.onSizeChanged = function () {
  30715. _this.aspectRatio = _this.width * .5 / _this.height;
  30716. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30717. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30718. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30719. };
  30720. this.onApply = function (effect) {
  30721. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30722. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30723. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30724. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30725. };
  30726. }
  30727. return VRDistortionCorrectionPostProcess;
  30728. })(BABYLON.PostProcess);
  30729. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30730. })(BABYLON || (BABYLON = {}));
  30731. // Mainly based on these 2 articles :
  30732. // 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
  30733. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30734. var BABYLON;
  30735. (function (BABYLON) {
  30736. (function (JoystickAxis) {
  30737. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30738. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30739. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30740. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30741. var JoystickAxis = BABYLON.JoystickAxis;
  30742. var VirtualJoystick = (function () {
  30743. function VirtualJoystick(leftJoystick) {
  30744. var _this = this;
  30745. if (leftJoystick) {
  30746. this._leftJoystick = true;
  30747. }
  30748. else {
  30749. this._leftJoystick = false;
  30750. }
  30751. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30752. VirtualJoystick._globalJoystickIndex++;
  30753. // By default left & right arrow keys are moving the X
  30754. // and up & down keys are moving the Y
  30755. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30756. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30757. this.reverseLeftRight = false;
  30758. this.reverseUpDown = false;
  30759. // collections of pointers
  30760. this._touches = new BABYLON.SmartCollection();
  30761. this.deltaPosition = BABYLON.Vector3.Zero();
  30762. this._joystickSensibility = 25;
  30763. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30764. this._rotationSpeed = 25;
  30765. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30766. this._rotateOnAxisRelativeToMesh = false;
  30767. this._onResize = function (evt) {
  30768. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30769. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30770. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30771. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30772. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30773. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30774. };
  30775. // injecting a canvas element on top of the canvas 3D game
  30776. if (!VirtualJoystick.vjCanvas) {
  30777. window.addEventListener("resize", this._onResize, false);
  30778. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30779. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30780. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30781. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30782. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30783. VirtualJoystick.vjCanvas.style.width = "100%";
  30784. VirtualJoystick.vjCanvas.style.height = "100%";
  30785. VirtualJoystick.vjCanvas.style.position = "absolute";
  30786. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30787. VirtualJoystick.vjCanvas.style.top = "0px";
  30788. VirtualJoystick.vjCanvas.style.left = "0px";
  30789. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30790. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30791. // Support for jQuery PEP polyfill
  30792. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30793. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30794. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30795. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30796. document.body.appendChild(VirtualJoystick.vjCanvas);
  30797. }
  30798. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30799. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30800. this.pressed = false;
  30801. // default joystick color
  30802. this._joystickColor = "cyan";
  30803. this._joystickPointerID = -1;
  30804. // current joystick position
  30805. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30806. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30807. // origin joystick position
  30808. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30809. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30810. this._onPointerDownHandlerRef = function (evt) {
  30811. _this._onPointerDown(evt);
  30812. };
  30813. this._onPointerMoveHandlerRef = function (evt) {
  30814. _this._onPointerMove(evt);
  30815. };
  30816. this._onPointerOutHandlerRef = function (evt) {
  30817. _this._onPointerUp(evt);
  30818. };
  30819. this._onPointerUpHandlerRef = function (evt) {
  30820. _this._onPointerUp(evt);
  30821. };
  30822. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30823. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30824. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30825. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30826. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30827. evt.preventDefault(); // Disables system menu
  30828. }, false);
  30829. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30830. }
  30831. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30832. this._joystickSensibility = newJoystickSensibility;
  30833. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30834. };
  30835. VirtualJoystick.prototype._onPointerDown = function (e) {
  30836. var positionOnScreenCondition;
  30837. e.preventDefault();
  30838. if (this._leftJoystick === true) {
  30839. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30840. }
  30841. else {
  30842. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30843. }
  30844. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30845. // First contact will be dedicated to the virtual joystick
  30846. this._joystickPointerID = e.pointerId;
  30847. this._joystickPointerStartPos.x = e.clientX;
  30848. this._joystickPointerStartPos.y = e.clientY;
  30849. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30850. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30851. this._deltaJoystickVector.x = 0;
  30852. this._deltaJoystickVector.y = 0;
  30853. this.pressed = true;
  30854. this._touches.add(e.pointerId.toString(), e);
  30855. }
  30856. else {
  30857. // You can only trigger the action buttons with a joystick declared
  30858. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30859. this._action();
  30860. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30861. }
  30862. }
  30863. };
  30864. VirtualJoystick.prototype._onPointerMove = function (e) {
  30865. // If the current pointer is the one associated to the joystick (first touch contact)
  30866. if (this._joystickPointerID == e.pointerId) {
  30867. this._joystickPointerPos.x = e.clientX;
  30868. this._joystickPointerPos.y = e.clientY;
  30869. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30870. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30871. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30872. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30873. switch (this._axisTargetedByLeftAndRight) {
  30874. case JoystickAxis.X:
  30875. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30876. break;
  30877. case JoystickAxis.Y:
  30878. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30879. break;
  30880. case JoystickAxis.Z:
  30881. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30882. break;
  30883. }
  30884. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30885. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30886. switch (this._axisTargetedByUpAndDown) {
  30887. case JoystickAxis.X:
  30888. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30889. break;
  30890. case JoystickAxis.Y:
  30891. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30892. break;
  30893. case JoystickAxis.Z:
  30894. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30895. break;
  30896. }
  30897. }
  30898. else {
  30899. if (this._touches.item(e.pointerId.toString())) {
  30900. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30901. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30902. }
  30903. }
  30904. };
  30905. VirtualJoystick.prototype._onPointerUp = function (e) {
  30906. if (this._joystickPointerID == e.pointerId) {
  30907. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30908. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30909. this._joystickPointerID = -1;
  30910. this.pressed = false;
  30911. }
  30912. else {
  30913. var touch = this._touches.item(e.pointerId.toString());
  30914. if (touch) {
  30915. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30916. }
  30917. }
  30918. this._deltaJoystickVector.x = 0;
  30919. this._deltaJoystickVector.y = 0;
  30920. this._touches.remove(e.pointerId.toString());
  30921. };
  30922. /**
  30923. * Change the color of the virtual joystick
  30924. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30925. */
  30926. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30927. this._joystickColor = newColor;
  30928. };
  30929. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30930. this._action = action;
  30931. };
  30932. // Define which axis you'd like to control for left & right
  30933. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30934. switch (axis) {
  30935. case JoystickAxis.X:
  30936. case JoystickAxis.Y:
  30937. case JoystickAxis.Z:
  30938. this._axisTargetedByLeftAndRight = axis;
  30939. break;
  30940. default:
  30941. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30942. break;
  30943. }
  30944. };
  30945. // Define which axis you'd like to control for up & down
  30946. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30947. switch (axis) {
  30948. case JoystickAxis.X:
  30949. case JoystickAxis.Y:
  30950. case JoystickAxis.Z:
  30951. this._axisTargetedByUpAndDown = axis;
  30952. break;
  30953. default:
  30954. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30955. break;
  30956. }
  30957. };
  30958. VirtualJoystick.prototype._clearCanvas = function () {
  30959. if (this._leftJoystick) {
  30960. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30961. }
  30962. else {
  30963. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30964. }
  30965. };
  30966. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30967. var _this = this;
  30968. if (this.pressed) {
  30969. this._touches.forEach(function (touch) {
  30970. if (touch.pointerId === _this._joystickPointerID) {
  30971. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30972. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30973. VirtualJoystick.vjCanvasContext.beginPath();
  30974. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30975. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30976. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30977. VirtualJoystick.vjCanvasContext.stroke();
  30978. VirtualJoystick.vjCanvasContext.closePath();
  30979. VirtualJoystick.vjCanvasContext.beginPath();
  30980. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30981. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30982. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30983. VirtualJoystick.vjCanvasContext.stroke();
  30984. VirtualJoystick.vjCanvasContext.closePath();
  30985. VirtualJoystick.vjCanvasContext.beginPath();
  30986. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30987. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30988. VirtualJoystick.vjCanvasContext.stroke();
  30989. VirtualJoystick.vjCanvasContext.closePath();
  30990. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30991. }
  30992. else {
  30993. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30994. VirtualJoystick.vjCanvasContext.beginPath();
  30995. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30996. VirtualJoystick.vjCanvasContext.beginPath();
  30997. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30998. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30999. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31000. VirtualJoystick.vjCanvasContext.stroke();
  31001. VirtualJoystick.vjCanvasContext.closePath();
  31002. touch.prevX = touch.x;
  31003. touch.prevY = touch.y;
  31004. }
  31005. ;
  31006. });
  31007. }
  31008. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31009. };
  31010. VirtualJoystick.prototype.releaseCanvas = function () {
  31011. if (VirtualJoystick.vjCanvas) {
  31012. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31013. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31014. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31015. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31016. window.removeEventListener("resize", this._onResize);
  31017. document.body.removeChild(VirtualJoystick.vjCanvas);
  31018. VirtualJoystick.vjCanvas = null;
  31019. }
  31020. };
  31021. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31022. VirtualJoystick._globalJoystickIndex = 0;
  31023. return VirtualJoystick;
  31024. })();
  31025. BABYLON.VirtualJoystick = VirtualJoystick;
  31026. })(BABYLON || (BABYLON = {}));
  31027. var BABYLON;
  31028. (function (BABYLON) {
  31029. // We're mainly based on the logic defined into the FreeCamera code
  31030. var VirtualJoysticksCamera = (function (_super) {
  31031. __extends(VirtualJoysticksCamera, _super);
  31032. function VirtualJoysticksCamera(name, position, scene) {
  31033. _super.call(this, name, position, scene);
  31034. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31035. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31036. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31037. this._leftjoystick.setJoystickSensibility(0.15);
  31038. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31039. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31040. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31041. this._rightjoystick.reverseUpDown = true;
  31042. this._rightjoystick.setJoystickSensibility(0.05);
  31043. this._rightjoystick.setJoystickColor("yellow");
  31044. }
  31045. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31046. return this._leftjoystick;
  31047. };
  31048. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31049. return this._rightjoystick;
  31050. };
  31051. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31052. var speed = this._computeLocalCameraSpeed() * 50;
  31053. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31054. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31055. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31056. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31057. if (!this._leftjoystick.pressed) {
  31058. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31059. }
  31060. if (!this._rightjoystick.pressed) {
  31061. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31062. }
  31063. _super.prototype._checkInputs.call(this);
  31064. };
  31065. VirtualJoysticksCamera.prototype.dispose = function () {
  31066. this._leftjoystick.releaseCanvas();
  31067. _super.prototype.dispose.call(this);
  31068. };
  31069. return VirtualJoysticksCamera;
  31070. })(BABYLON.FreeCamera);
  31071. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31072. })(BABYLON || (BABYLON = {}));
  31073. var BABYLON;
  31074. (function (BABYLON) {
  31075. var AnaglyphPostProcess = (function (_super) {
  31076. __extends(AnaglyphPostProcess, _super);
  31077. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31078. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31079. }
  31080. return AnaglyphPostProcess;
  31081. })(BABYLON.PostProcess);
  31082. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31083. })(BABYLON || (BABYLON = {}));
  31084. var BABYLON;
  31085. (function (BABYLON) {
  31086. var OutlineRenderer = (function () {
  31087. function OutlineRenderer(scene) {
  31088. this._scene = scene;
  31089. }
  31090. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31091. var _this = this;
  31092. if (useOverlay === void 0) { useOverlay = false; }
  31093. var scene = this._scene;
  31094. var engine = this._scene.getEngine();
  31095. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31096. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31097. return;
  31098. }
  31099. var mesh = subMesh.getRenderingMesh();
  31100. var material = subMesh.getMaterial();
  31101. engine.enableEffect(this._effect);
  31102. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31103. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31104. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31105. // Bones
  31106. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31107. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31108. }
  31109. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31110. // Alpha test
  31111. if (material && material.needAlphaTesting()) {
  31112. var alphaTexture = material.getAlphaTestTexture();
  31113. this._effect.setTexture("diffuseSampler", alphaTexture);
  31114. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31115. }
  31116. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31117. };
  31118. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31119. var defines = [];
  31120. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31121. var mesh = subMesh.getMesh();
  31122. var material = subMesh.getMaterial();
  31123. // Alpha test
  31124. if (material && material.needAlphaTesting()) {
  31125. defines.push("#define ALPHATEST");
  31126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31127. attribs.push(BABYLON.VertexBuffer.UVKind);
  31128. defines.push("#define UV1");
  31129. }
  31130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31132. defines.push("#define UV2");
  31133. }
  31134. }
  31135. // Bones
  31136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31139. if (mesh.numBoneInfluencers > 4) {
  31140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31142. }
  31143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31144. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31145. }
  31146. else {
  31147. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31148. }
  31149. // Instances
  31150. if (useInstances) {
  31151. defines.push("#define INSTANCES");
  31152. attribs.push("world0");
  31153. attribs.push("world1");
  31154. attribs.push("world2");
  31155. attribs.push("world3");
  31156. }
  31157. // Get correct effect
  31158. var join = defines.join("\n");
  31159. if (this._cachedDefines !== join) {
  31160. this._cachedDefines = join;
  31161. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31162. }
  31163. return this._effect.isReady();
  31164. };
  31165. return OutlineRenderer;
  31166. })();
  31167. BABYLON.OutlineRenderer = OutlineRenderer;
  31168. })(BABYLON || (BABYLON = {}));
  31169. var BABYLON;
  31170. (function (BABYLON) {
  31171. var MeshAssetTask = (function () {
  31172. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31173. this.name = name;
  31174. this.meshesNames = meshesNames;
  31175. this.rootUrl = rootUrl;
  31176. this.sceneFilename = sceneFilename;
  31177. this.isCompleted = false;
  31178. }
  31179. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31180. var _this = this;
  31181. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31182. _this.loadedMeshes = meshes;
  31183. _this.loadedParticleSystems = particleSystems;
  31184. _this.loadedSkeletons = skeletons;
  31185. _this.isCompleted = true;
  31186. if (_this.onSuccess) {
  31187. _this.onSuccess(_this);
  31188. }
  31189. onSuccess();
  31190. }, null, function () {
  31191. if (_this.onError) {
  31192. _this.onError(_this);
  31193. }
  31194. onError();
  31195. });
  31196. };
  31197. return MeshAssetTask;
  31198. })();
  31199. BABYLON.MeshAssetTask = MeshAssetTask;
  31200. var TextFileAssetTask = (function () {
  31201. function TextFileAssetTask(name, url) {
  31202. this.name = name;
  31203. this.url = url;
  31204. this.isCompleted = false;
  31205. }
  31206. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31207. var _this = this;
  31208. BABYLON.Tools.LoadFile(this.url, function (data) {
  31209. _this.text = data;
  31210. _this.isCompleted = true;
  31211. if (_this.onSuccess) {
  31212. _this.onSuccess(_this);
  31213. }
  31214. onSuccess();
  31215. }, null, scene.database, false, function () {
  31216. if (_this.onError) {
  31217. _this.onError(_this);
  31218. }
  31219. onError();
  31220. });
  31221. };
  31222. return TextFileAssetTask;
  31223. })();
  31224. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31225. var BinaryFileAssetTask = (function () {
  31226. function BinaryFileAssetTask(name, url) {
  31227. this.name = name;
  31228. this.url = url;
  31229. this.isCompleted = false;
  31230. }
  31231. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31232. var _this = this;
  31233. BABYLON.Tools.LoadFile(this.url, function (data) {
  31234. _this.data = data;
  31235. _this.isCompleted = true;
  31236. if (_this.onSuccess) {
  31237. _this.onSuccess(_this);
  31238. }
  31239. onSuccess();
  31240. }, null, scene.database, true, function () {
  31241. if (_this.onError) {
  31242. _this.onError(_this);
  31243. }
  31244. onError();
  31245. });
  31246. };
  31247. return BinaryFileAssetTask;
  31248. })();
  31249. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31250. var ImageAssetTask = (function () {
  31251. function ImageAssetTask(name, url) {
  31252. this.name = name;
  31253. this.url = url;
  31254. this.isCompleted = false;
  31255. }
  31256. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31257. var _this = this;
  31258. var img = new Image();
  31259. img.onload = function () {
  31260. _this.image = img;
  31261. _this.isCompleted = true;
  31262. if (_this.onSuccess) {
  31263. _this.onSuccess(_this);
  31264. }
  31265. onSuccess();
  31266. };
  31267. img.onerror = function () {
  31268. if (_this.onError) {
  31269. _this.onError(_this);
  31270. }
  31271. onError();
  31272. };
  31273. img.src = this.url;
  31274. };
  31275. return ImageAssetTask;
  31276. })();
  31277. BABYLON.ImageAssetTask = ImageAssetTask;
  31278. var TextureAssetTask = (function () {
  31279. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31281. this.name = name;
  31282. this.url = url;
  31283. this.noMipmap = noMipmap;
  31284. this.invertY = invertY;
  31285. this.samplingMode = samplingMode;
  31286. this.isCompleted = false;
  31287. }
  31288. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31289. var _this = this;
  31290. var onload = function () {
  31291. _this.isCompleted = true;
  31292. if (_this.onSuccess) {
  31293. _this.onSuccess(_this);
  31294. }
  31295. onSuccess();
  31296. };
  31297. var onerror = function () {
  31298. if (_this.onError) {
  31299. _this.onError(_this);
  31300. }
  31301. onError();
  31302. };
  31303. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31304. };
  31305. return TextureAssetTask;
  31306. })();
  31307. BABYLON.TextureAssetTask = TextureAssetTask;
  31308. var AssetsManager = (function () {
  31309. function AssetsManager(scene) {
  31310. this._tasks = new Array();
  31311. this._waitingTasksCount = 0;
  31312. this.useDefaultLoadingScreen = true;
  31313. this._scene = scene;
  31314. }
  31315. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31316. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31317. this._tasks.push(task);
  31318. return task;
  31319. };
  31320. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31321. var task = new TextFileAssetTask(taskName, url);
  31322. this._tasks.push(task);
  31323. return task;
  31324. };
  31325. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31326. var task = new BinaryFileAssetTask(taskName, url);
  31327. this._tasks.push(task);
  31328. return task;
  31329. };
  31330. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31331. var task = new ImageAssetTask(taskName, url);
  31332. this._tasks.push(task);
  31333. return task;
  31334. };
  31335. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31337. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31338. this._tasks.push(task);
  31339. return task;
  31340. };
  31341. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31342. this._waitingTasksCount--;
  31343. if (this._waitingTasksCount === 0) {
  31344. if (this.onFinish) {
  31345. this.onFinish(this._tasks);
  31346. }
  31347. this._scene.getEngine().hideLoadingUI();
  31348. }
  31349. };
  31350. AssetsManager.prototype._runTask = function (task) {
  31351. var _this = this;
  31352. task.run(this._scene, function () {
  31353. if (_this.onTaskSuccess) {
  31354. _this.onTaskSuccess(task);
  31355. }
  31356. _this._decreaseWaitingTasksCount();
  31357. }, function () {
  31358. if (_this.onTaskError) {
  31359. _this.onTaskError(task);
  31360. }
  31361. _this._decreaseWaitingTasksCount();
  31362. });
  31363. };
  31364. AssetsManager.prototype.reset = function () {
  31365. this._tasks = new Array();
  31366. return this;
  31367. };
  31368. AssetsManager.prototype.load = function () {
  31369. this._waitingTasksCount = this._tasks.length;
  31370. if (this._waitingTasksCount === 0) {
  31371. if (this.onFinish) {
  31372. this.onFinish(this._tasks);
  31373. }
  31374. return this;
  31375. }
  31376. if (this.useDefaultLoadingScreen) {
  31377. this._scene.getEngine().displayLoadingUI();
  31378. }
  31379. for (var index = 0; index < this._tasks.length; index++) {
  31380. var task = this._tasks[index];
  31381. this._runTask(task);
  31382. }
  31383. return this;
  31384. };
  31385. return AssetsManager;
  31386. })();
  31387. BABYLON.AssetsManager = AssetsManager;
  31388. })(BABYLON || (BABYLON = {}));
  31389. var BABYLON;
  31390. (function (BABYLON) {
  31391. var VRDeviceOrientationFreeCamera = (function (_super) {
  31392. __extends(VRDeviceOrientationFreeCamera, _super);
  31393. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31394. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31395. _super.call(this, name, position, scene);
  31396. this._alpha = 0;
  31397. this._beta = 0;
  31398. this._gamma = 0;
  31399. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31400. metrics.compensateDistortion = compensateDistortion;
  31401. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31402. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31403. }
  31404. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31405. this._alpha = +evt.alpha | 0;
  31406. this._beta = +evt.beta | 0;
  31407. this._gamma = +evt.gamma | 0;
  31408. if (this._gamma < 0) {
  31409. this._gamma = 90 + this._gamma;
  31410. }
  31411. else {
  31412. // Incline it in the correct angle.
  31413. this._gamma = 270 - this._gamma;
  31414. }
  31415. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31416. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31417. this.rotation.z = this._beta / 180.0 * Math.PI;
  31418. };
  31419. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31420. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31421. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31422. };
  31423. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31424. _super.prototype.detachControl.call(this, element);
  31425. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31426. };
  31427. return VRDeviceOrientationFreeCamera;
  31428. })(BABYLON.FreeCamera);
  31429. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31430. })(BABYLON || (BABYLON = {}));
  31431. var BABYLON;
  31432. (function (BABYLON) {
  31433. var WebVRFreeCamera = (function (_super) {
  31434. __extends(WebVRFreeCamera, _super);
  31435. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31436. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31437. _super.call(this, name, position, scene);
  31438. this._hmdDevice = null;
  31439. this._sensorDevice = null;
  31440. this._cacheState = null;
  31441. this._cacheQuaternion = new BABYLON.Quaternion();
  31442. this._cacheRotation = BABYLON.Vector3.Zero();
  31443. this._vrEnabled = false;
  31444. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31445. metrics.compensateDistortion = compensateDistortion;
  31446. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31447. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31448. }
  31449. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31450. var size = devices.length;
  31451. var i = 0;
  31452. // Reset devices.
  31453. this._sensorDevice = null;
  31454. this._hmdDevice = null;
  31455. // Search for a HmdDevice.
  31456. while (i < size && this._hmdDevice === null) {
  31457. if (devices[i] instanceof HMDVRDevice) {
  31458. this._hmdDevice = devices[i];
  31459. }
  31460. i++;
  31461. }
  31462. i = 0;
  31463. while (i < size && this._sensorDevice === null) {
  31464. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31465. this._sensorDevice = devices[i];
  31466. }
  31467. i++;
  31468. }
  31469. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31470. };
  31471. WebVRFreeCamera.prototype._checkInputs = function () {
  31472. if (this._vrEnabled) {
  31473. this._cacheState = this._sensorDevice.getState();
  31474. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31475. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31476. this.rotation.x = -this._cacheRotation.z;
  31477. this.rotation.y = -this._cacheRotation.y;
  31478. this.rotation.z = this._cacheRotation.x;
  31479. }
  31480. _super.prototype._checkInputs.call(this);
  31481. };
  31482. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31483. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31484. if (navigator.getVRDevices) {
  31485. navigator.getVRDevices().then(this._getWebVRDevices);
  31486. }
  31487. else if (navigator.mozGetVRDevices) {
  31488. navigator.mozGetVRDevices(this._getWebVRDevices);
  31489. }
  31490. };
  31491. WebVRFreeCamera.prototype.detachControl = function (element) {
  31492. _super.prototype.detachControl.call(this, element);
  31493. this._vrEnabled = false;
  31494. };
  31495. return WebVRFreeCamera;
  31496. })(BABYLON.FreeCamera);
  31497. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31498. })(BABYLON || (BABYLON = {}));
  31499. var BABYLON;
  31500. (function (BABYLON) {
  31501. // Standard optimizations
  31502. var SceneOptimization = (function () {
  31503. function SceneOptimization(priority) {
  31504. if (priority === void 0) { priority = 0; }
  31505. this.priority = priority;
  31506. this.apply = function (scene) {
  31507. return true; // Return true if everything that can be done was applied
  31508. };
  31509. }
  31510. return SceneOptimization;
  31511. })();
  31512. BABYLON.SceneOptimization = SceneOptimization;
  31513. var TextureOptimization = (function (_super) {
  31514. __extends(TextureOptimization, _super);
  31515. function TextureOptimization(priority, maximumSize) {
  31516. var _this = this;
  31517. if (priority === void 0) { priority = 0; }
  31518. if (maximumSize === void 0) { maximumSize = 1024; }
  31519. _super.call(this, priority);
  31520. this.priority = priority;
  31521. this.maximumSize = maximumSize;
  31522. this.apply = function (scene) {
  31523. var allDone = true;
  31524. for (var index = 0; index < scene.textures.length; index++) {
  31525. var texture = scene.textures[index];
  31526. if (!texture.canRescale) {
  31527. continue;
  31528. }
  31529. var currentSize = texture.getSize();
  31530. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31531. if (maxDimension > _this.maximumSize) {
  31532. texture.scale(0.5);
  31533. allDone = false;
  31534. }
  31535. }
  31536. return allDone;
  31537. };
  31538. }
  31539. return TextureOptimization;
  31540. })(SceneOptimization);
  31541. BABYLON.TextureOptimization = TextureOptimization;
  31542. var HardwareScalingOptimization = (function (_super) {
  31543. __extends(HardwareScalingOptimization, _super);
  31544. function HardwareScalingOptimization(priority, maximumScale) {
  31545. var _this = this;
  31546. if (priority === void 0) { priority = 0; }
  31547. if (maximumScale === void 0) { maximumScale = 2; }
  31548. _super.call(this, priority);
  31549. this.priority = priority;
  31550. this.maximumScale = maximumScale;
  31551. this._currentScale = 1;
  31552. this.apply = function (scene) {
  31553. _this._currentScale++;
  31554. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31555. return _this._currentScale >= _this.maximumScale;
  31556. };
  31557. }
  31558. return HardwareScalingOptimization;
  31559. })(SceneOptimization);
  31560. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31561. var ShadowsOptimization = (function (_super) {
  31562. __extends(ShadowsOptimization, _super);
  31563. function ShadowsOptimization() {
  31564. _super.apply(this, arguments);
  31565. this.apply = function (scene) {
  31566. scene.shadowsEnabled = false;
  31567. return true;
  31568. };
  31569. }
  31570. return ShadowsOptimization;
  31571. })(SceneOptimization);
  31572. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31573. var PostProcessesOptimization = (function (_super) {
  31574. __extends(PostProcessesOptimization, _super);
  31575. function PostProcessesOptimization() {
  31576. _super.apply(this, arguments);
  31577. this.apply = function (scene) {
  31578. scene.postProcessesEnabled = false;
  31579. return true;
  31580. };
  31581. }
  31582. return PostProcessesOptimization;
  31583. })(SceneOptimization);
  31584. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31585. var LensFlaresOptimization = (function (_super) {
  31586. __extends(LensFlaresOptimization, _super);
  31587. function LensFlaresOptimization() {
  31588. _super.apply(this, arguments);
  31589. this.apply = function (scene) {
  31590. scene.lensFlaresEnabled = false;
  31591. return true;
  31592. };
  31593. }
  31594. return LensFlaresOptimization;
  31595. })(SceneOptimization);
  31596. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31597. var ParticlesOptimization = (function (_super) {
  31598. __extends(ParticlesOptimization, _super);
  31599. function ParticlesOptimization() {
  31600. _super.apply(this, arguments);
  31601. this.apply = function (scene) {
  31602. scene.particlesEnabled = false;
  31603. return true;
  31604. };
  31605. }
  31606. return ParticlesOptimization;
  31607. })(SceneOptimization);
  31608. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31609. var RenderTargetsOptimization = (function (_super) {
  31610. __extends(RenderTargetsOptimization, _super);
  31611. function RenderTargetsOptimization() {
  31612. _super.apply(this, arguments);
  31613. this.apply = function (scene) {
  31614. scene.renderTargetsEnabled = false;
  31615. return true;
  31616. };
  31617. }
  31618. return RenderTargetsOptimization;
  31619. })(SceneOptimization);
  31620. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31621. var MergeMeshesOptimization = (function (_super) {
  31622. __extends(MergeMeshesOptimization, _super);
  31623. function MergeMeshesOptimization() {
  31624. var _this = this;
  31625. _super.apply(this, arguments);
  31626. this._canBeMerged = function (abstractMesh) {
  31627. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31628. return false;
  31629. }
  31630. var mesh = abstractMesh;
  31631. if (!mesh.isVisible || !mesh.isEnabled()) {
  31632. return false;
  31633. }
  31634. if (mesh.instances.length > 0) {
  31635. return false;
  31636. }
  31637. if (mesh.skeleton || mesh.hasLODLevels) {
  31638. return false;
  31639. }
  31640. if (mesh.parent) {
  31641. return false;
  31642. }
  31643. return true;
  31644. };
  31645. this.apply = function (scene, updateSelectionTree) {
  31646. var globalPool = scene.meshes.slice(0);
  31647. var globalLength = globalPool.length;
  31648. for (var index = 0; index < globalLength; index++) {
  31649. var currentPool = new Array();
  31650. var current = globalPool[index];
  31651. // Checks
  31652. if (!_this._canBeMerged(current)) {
  31653. continue;
  31654. }
  31655. currentPool.push(current);
  31656. // Find compatible meshes
  31657. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31658. var otherMesh = globalPool[subIndex];
  31659. if (!_this._canBeMerged(otherMesh)) {
  31660. continue;
  31661. }
  31662. if (otherMesh.material !== current.material) {
  31663. continue;
  31664. }
  31665. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31666. continue;
  31667. }
  31668. currentPool.push(otherMesh);
  31669. globalLength--;
  31670. globalPool.splice(subIndex, 1);
  31671. subIndex--;
  31672. }
  31673. if (currentPool.length < 2) {
  31674. continue;
  31675. }
  31676. // Merge meshes
  31677. BABYLON.Mesh.MergeMeshes(currentPool);
  31678. }
  31679. if (updateSelectionTree != undefined) {
  31680. if (updateSelectionTree) {
  31681. scene.createOrUpdateSelectionOctree();
  31682. }
  31683. }
  31684. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31685. scene.createOrUpdateSelectionOctree();
  31686. }
  31687. return true;
  31688. };
  31689. }
  31690. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31691. get: function () {
  31692. return MergeMeshesOptimization._UpdateSelectionTree;
  31693. },
  31694. set: function (value) {
  31695. MergeMeshesOptimization._UpdateSelectionTree = value;
  31696. },
  31697. enumerable: true,
  31698. configurable: true
  31699. });
  31700. MergeMeshesOptimization._UpdateSelectionTree = false;
  31701. return MergeMeshesOptimization;
  31702. })(SceneOptimization);
  31703. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31704. // Options
  31705. var SceneOptimizerOptions = (function () {
  31706. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31707. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31708. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31709. this.targetFrameRate = targetFrameRate;
  31710. this.trackerDuration = trackerDuration;
  31711. this.optimizations = new Array();
  31712. }
  31713. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31714. var result = new SceneOptimizerOptions(targetFrameRate);
  31715. var priority = 0;
  31716. result.optimizations.push(new MergeMeshesOptimization(priority));
  31717. result.optimizations.push(new ShadowsOptimization(priority));
  31718. result.optimizations.push(new LensFlaresOptimization(priority));
  31719. // Next priority
  31720. priority++;
  31721. result.optimizations.push(new PostProcessesOptimization(priority));
  31722. result.optimizations.push(new ParticlesOptimization(priority));
  31723. // Next priority
  31724. priority++;
  31725. result.optimizations.push(new TextureOptimization(priority, 1024));
  31726. return result;
  31727. };
  31728. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31729. var result = new SceneOptimizerOptions(targetFrameRate);
  31730. var priority = 0;
  31731. result.optimizations.push(new MergeMeshesOptimization(priority));
  31732. result.optimizations.push(new ShadowsOptimization(priority));
  31733. result.optimizations.push(new LensFlaresOptimization(priority));
  31734. // Next priority
  31735. priority++;
  31736. result.optimizations.push(new PostProcessesOptimization(priority));
  31737. result.optimizations.push(new ParticlesOptimization(priority));
  31738. // Next priority
  31739. priority++;
  31740. result.optimizations.push(new TextureOptimization(priority, 512));
  31741. // Next priority
  31742. priority++;
  31743. result.optimizations.push(new RenderTargetsOptimization(priority));
  31744. // Next priority
  31745. priority++;
  31746. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31747. return result;
  31748. };
  31749. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31750. var result = new SceneOptimizerOptions(targetFrameRate);
  31751. var priority = 0;
  31752. result.optimizations.push(new MergeMeshesOptimization(priority));
  31753. result.optimizations.push(new ShadowsOptimization(priority));
  31754. result.optimizations.push(new LensFlaresOptimization(priority));
  31755. // Next priority
  31756. priority++;
  31757. result.optimizations.push(new PostProcessesOptimization(priority));
  31758. result.optimizations.push(new ParticlesOptimization(priority));
  31759. // Next priority
  31760. priority++;
  31761. result.optimizations.push(new TextureOptimization(priority, 256));
  31762. // Next priority
  31763. priority++;
  31764. result.optimizations.push(new RenderTargetsOptimization(priority));
  31765. // Next priority
  31766. priority++;
  31767. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31768. return result;
  31769. };
  31770. return SceneOptimizerOptions;
  31771. })();
  31772. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31773. // Scene optimizer tool
  31774. var SceneOptimizer = (function () {
  31775. function SceneOptimizer() {
  31776. }
  31777. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31778. // TODO: add an epsilon
  31779. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31780. if (onSuccess) {
  31781. onSuccess();
  31782. }
  31783. return;
  31784. }
  31785. // Apply current level of optimizations
  31786. var allDone = true;
  31787. var noOptimizationApplied = true;
  31788. for (var index = 0; index < options.optimizations.length; index++) {
  31789. var optimization = options.optimizations[index];
  31790. if (optimization.priority === currentPriorityLevel) {
  31791. noOptimizationApplied = false;
  31792. allDone = allDone && optimization.apply(scene);
  31793. }
  31794. }
  31795. // If no optimization was applied, this is a failure :(
  31796. if (noOptimizationApplied) {
  31797. if (onFailure) {
  31798. onFailure();
  31799. }
  31800. return;
  31801. }
  31802. // If all optimizations were done, move to next level
  31803. if (allDone) {
  31804. currentPriorityLevel++;
  31805. }
  31806. // Let's the system running for a specific amount of time before checking FPS
  31807. scene.executeWhenReady(function () {
  31808. setTimeout(function () {
  31809. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31810. }, options.trackerDuration);
  31811. });
  31812. };
  31813. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31814. if (!options) {
  31815. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31816. }
  31817. // Let's the system running for a specific amount of time before checking FPS
  31818. scene.executeWhenReady(function () {
  31819. setTimeout(function () {
  31820. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31821. }, options.trackerDuration);
  31822. });
  31823. };
  31824. return SceneOptimizer;
  31825. })();
  31826. BABYLON.SceneOptimizer = SceneOptimizer;
  31827. })(BABYLON || (BABYLON = {}));
  31828. var BABYLON;
  31829. (function (BABYLON) {
  31830. var Internals;
  31831. (function (Internals) {
  31832. var MeshLODLevel = (function () {
  31833. function MeshLODLevel(distance, mesh) {
  31834. this.distance = distance;
  31835. this.mesh = mesh;
  31836. }
  31837. return MeshLODLevel;
  31838. })();
  31839. Internals.MeshLODLevel = MeshLODLevel;
  31840. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31841. })(BABYLON || (BABYLON = {}));
  31842. var BABYLON;
  31843. (function (BABYLON) {
  31844. var RawTexture = (function (_super) {
  31845. __extends(RawTexture, _super);
  31846. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31848. if (invertY === void 0) { invertY = false; }
  31849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31850. _super.call(this, null, scene, !generateMipMaps, invertY);
  31851. this.format = format;
  31852. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31853. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31854. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31855. }
  31856. RawTexture.prototype.update = function (data) {
  31857. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31858. };
  31859. // Statics
  31860. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31861. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31862. if (invertY === void 0) { invertY = false; }
  31863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31864. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31865. };
  31866. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31867. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31868. if (invertY === void 0) { invertY = false; }
  31869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31870. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31871. };
  31872. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31873. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31874. if (invertY === void 0) { invertY = false; }
  31875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31876. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31877. };
  31878. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31879. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31880. if (invertY === void 0) { invertY = false; }
  31881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31882. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31883. };
  31884. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31885. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31886. if (invertY === void 0) { invertY = false; }
  31887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31888. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31889. };
  31890. return RawTexture;
  31891. })(BABYLON.Texture);
  31892. BABYLON.RawTexture = RawTexture;
  31893. })(BABYLON || (BABYLON = {}));
  31894. var BABYLON;
  31895. (function (BABYLON) {
  31896. var IndexedVector2 = (function (_super) {
  31897. __extends(IndexedVector2, _super);
  31898. function IndexedVector2(original, index) {
  31899. _super.call(this, original.x, original.y);
  31900. this.index = index;
  31901. }
  31902. return IndexedVector2;
  31903. })(BABYLON.Vector2);
  31904. var PolygonPoints = (function () {
  31905. function PolygonPoints() {
  31906. this.elements = new Array();
  31907. }
  31908. PolygonPoints.prototype.add = function (originalPoints) {
  31909. var _this = this;
  31910. var result = new Array();
  31911. originalPoints.forEach(function (point) {
  31912. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31913. var newPoint = new IndexedVector2(point, _this.elements.length);
  31914. result.push(newPoint);
  31915. _this.elements.push(newPoint);
  31916. }
  31917. });
  31918. return result;
  31919. };
  31920. PolygonPoints.prototype.computeBounds = function () {
  31921. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31922. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31923. this.elements.forEach(function (point) {
  31924. // x
  31925. if (point.x < lmin.x) {
  31926. lmin.x = point.x;
  31927. }
  31928. else if (point.x > lmax.x) {
  31929. lmax.x = point.x;
  31930. }
  31931. // y
  31932. if (point.y < lmin.y) {
  31933. lmin.y = point.y;
  31934. }
  31935. else if (point.y > lmax.y) {
  31936. lmax.y = point.y;
  31937. }
  31938. });
  31939. return {
  31940. min: lmin,
  31941. max: lmax,
  31942. width: lmax.x - lmin.x,
  31943. height: lmax.y - lmin.y
  31944. };
  31945. };
  31946. return PolygonPoints;
  31947. })();
  31948. var Polygon = (function () {
  31949. function Polygon() {
  31950. }
  31951. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31952. return [
  31953. new BABYLON.Vector2(xmin, ymin),
  31954. new BABYLON.Vector2(xmax, ymin),
  31955. new BABYLON.Vector2(xmax, ymax),
  31956. new BABYLON.Vector2(xmin, ymax)
  31957. ];
  31958. };
  31959. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31960. if (cx === void 0) { cx = 0; }
  31961. if (cy === void 0) { cy = 0; }
  31962. if (numberOfSides === void 0) { numberOfSides = 32; }
  31963. var result = new Array();
  31964. var angle = 0;
  31965. var increment = (Math.PI * 2) / numberOfSides;
  31966. for (var i = 0; i < numberOfSides; i++) {
  31967. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31968. angle -= increment;
  31969. }
  31970. return result;
  31971. };
  31972. Polygon.Parse = function (input) {
  31973. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31974. var i, result = [];
  31975. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31976. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31977. }
  31978. return result;
  31979. };
  31980. Polygon.StartingAt = function (x, y) {
  31981. return BABYLON.Path2.StartingAt(x, y);
  31982. };
  31983. return Polygon;
  31984. })();
  31985. BABYLON.Polygon = Polygon;
  31986. var PolygonMeshBuilder = (function () {
  31987. function PolygonMeshBuilder(name, contours, scene) {
  31988. this._points = new PolygonPoints();
  31989. this._outlinepoints = new PolygonPoints();
  31990. this._holes = [];
  31991. if (!("poly2tri" in window)) {
  31992. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31993. }
  31994. this._name = name;
  31995. this._scene = scene;
  31996. var points;
  31997. if (contours instanceof BABYLON.Path2) {
  31998. points = contours.getPoints();
  31999. }
  32000. else {
  32001. points = contours;
  32002. }
  32003. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32004. this._outlinepoints.add(points);
  32005. }
  32006. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32007. this._swctx.addHole(this._points.add(hole));
  32008. var holepoints = new PolygonPoints();
  32009. holepoints.add(hole);
  32010. this._holes.push(holepoints);
  32011. return this;
  32012. };
  32013. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32014. var _this = this;
  32015. if (updatable === void 0) { updatable = false; }
  32016. var result = new BABYLON.Mesh(this._name, this._scene);
  32017. var normals = [];
  32018. var positions = [];
  32019. var uvs = [];
  32020. var bounds = this._points.computeBounds();
  32021. this._points.elements.forEach(function (p) {
  32022. normals.push(0, 1.0, 0);
  32023. positions.push(p.x, 0, p.y);
  32024. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32025. });
  32026. var indices = [];
  32027. this._swctx.triangulate();
  32028. this._swctx.getTriangles().forEach(function (triangle) {
  32029. triangle.getPoints().forEach(function (point) {
  32030. indices.push(point.index);
  32031. });
  32032. });
  32033. if (depth > 0) {
  32034. var positionscount = (positions.length / 3); //get the current pointcount
  32035. this._points.elements.forEach(function (p) {
  32036. normals.push(0, -1.0, 0);
  32037. positions.push(p.x, -depth, p.y);
  32038. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32039. });
  32040. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32041. var p2;
  32042. var poscounter = 0;
  32043. this._swctx.getTriangles().forEach(function (triangle) {
  32044. triangle.getPoints().forEach(function (point) {
  32045. switch (poscounter) {
  32046. case 0:
  32047. p1 = point;
  32048. break;
  32049. case 1:
  32050. p2 = point;
  32051. break;
  32052. case 2:
  32053. indices.push(point.index + positionscount);
  32054. indices.push(p2.index + positionscount);
  32055. indices.push(p1.index + positionscount);
  32056. poscounter = -1;
  32057. break;
  32058. }
  32059. poscounter++;
  32060. //indices.push((<IndexedVector2>point).index + positionscount);
  32061. });
  32062. });
  32063. //Add the sides
  32064. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32065. this._holes.forEach(function (hole) {
  32066. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32067. });
  32068. }
  32069. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32070. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32071. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32072. result.setIndices(indices);
  32073. return result;
  32074. };
  32075. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32076. var StartIndex = positions.length / 3;
  32077. var ulength = 0;
  32078. for (var i = 0; i < points.elements.length; i++) {
  32079. var p = points.elements[i];
  32080. var p1;
  32081. if ((i + 1) > points.elements.length - 1) {
  32082. p1 = points.elements[0];
  32083. }
  32084. else {
  32085. p1 = points.elements[i + 1];
  32086. }
  32087. positions.push(p.x, 0, p.y);
  32088. positions.push(p.x, -depth, p.y);
  32089. positions.push(p1.x, 0, p1.y);
  32090. positions.push(p1.x, -depth, p1.y);
  32091. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32092. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32093. var v3 = v2.subtract(v1);
  32094. var v4 = new BABYLON.Vector3(0, 1, 0);
  32095. var vn = BABYLON.Vector3.Cross(v3, v4);
  32096. vn = vn.normalize();
  32097. uvs.push(ulength / bounds.width, 0);
  32098. uvs.push(ulength / bounds.width, 1);
  32099. ulength += v3.length();
  32100. uvs.push((ulength / bounds.width), 0);
  32101. uvs.push((ulength / bounds.width), 1);
  32102. if (!flip) {
  32103. normals.push(-vn.x, -vn.y, -vn.z);
  32104. normals.push(-vn.x, -vn.y, -vn.z);
  32105. normals.push(-vn.x, -vn.y, -vn.z);
  32106. normals.push(-vn.x, -vn.y, -vn.z);
  32107. indices.push(StartIndex);
  32108. indices.push(StartIndex + 1);
  32109. indices.push(StartIndex + 2);
  32110. indices.push(StartIndex + 1);
  32111. indices.push(StartIndex + 3);
  32112. indices.push(StartIndex + 2);
  32113. }
  32114. else {
  32115. normals.push(vn.x, vn.y, vn.z);
  32116. normals.push(vn.x, vn.y, vn.z);
  32117. normals.push(vn.x, vn.y, vn.z);
  32118. normals.push(vn.x, vn.y, vn.z);
  32119. indices.push(StartIndex);
  32120. indices.push(StartIndex + 2);
  32121. indices.push(StartIndex + 1);
  32122. indices.push(StartIndex + 1);
  32123. indices.push(StartIndex + 2);
  32124. indices.push(StartIndex + 3);
  32125. }
  32126. StartIndex += 4;
  32127. }
  32128. ;
  32129. };
  32130. return PolygonMeshBuilder;
  32131. })();
  32132. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32133. })(BABYLON || (BABYLON = {}));
  32134. var BABYLON;
  32135. (function (BABYLON) {
  32136. var Octree = (function () {
  32137. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32138. if (maxDepth === void 0) { maxDepth = 2; }
  32139. this.maxDepth = maxDepth;
  32140. this.dynamicContent = new Array();
  32141. this._maxBlockCapacity = maxBlockCapacity || 64;
  32142. this._selectionContent = new BABYLON.SmartArray(1024);
  32143. this._creationFunc = creationFunc;
  32144. }
  32145. // Methods
  32146. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32147. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32148. };
  32149. Octree.prototype.addMesh = function (entry) {
  32150. for (var index = 0; index < this.blocks.length; index++) {
  32151. var block = this.blocks[index];
  32152. block.addEntry(entry);
  32153. }
  32154. };
  32155. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32156. this._selectionContent.reset();
  32157. for (var index = 0; index < this.blocks.length; index++) {
  32158. var block = this.blocks[index];
  32159. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32160. }
  32161. if (allowDuplicate) {
  32162. this._selectionContent.concat(this.dynamicContent);
  32163. }
  32164. else {
  32165. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32166. }
  32167. return this._selectionContent;
  32168. };
  32169. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32170. this._selectionContent.reset();
  32171. for (var index = 0; index < this.blocks.length; index++) {
  32172. var block = this.blocks[index];
  32173. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32174. }
  32175. if (allowDuplicate) {
  32176. this._selectionContent.concat(this.dynamicContent);
  32177. }
  32178. else {
  32179. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32180. }
  32181. return this._selectionContent;
  32182. };
  32183. Octree.prototype.intersectsRay = function (ray) {
  32184. this._selectionContent.reset();
  32185. for (var index = 0; index < this.blocks.length; index++) {
  32186. var block = this.blocks[index];
  32187. block.intersectsRay(ray, this._selectionContent);
  32188. }
  32189. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32190. return this._selectionContent;
  32191. };
  32192. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32193. target.blocks = new Array();
  32194. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32195. // Segmenting space
  32196. for (var x = 0; x < 2; x++) {
  32197. for (var y = 0; y < 2; y++) {
  32198. for (var z = 0; z < 2; z++) {
  32199. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32200. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32201. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32202. block.addEntries(entries);
  32203. target.blocks.push(block);
  32204. }
  32205. }
  32206. }
  32207. };
  32208. Octree.CreationFuncForMeshes = function (entry, block) {
  32209. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32210. block.entries.push(entry);
  32211. }
  32212. };
  32213. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32214. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32215. block.entries.push(entry);
  32216. }
  32217. };
  32218. return Octree;
  32219. })();
  32220. BABYLON.Octree = Octree;
  32221. })(BABYLON || (BABYLON = {}));
  32222. var BABYLON;
  32223. (function (BABYLON) {
  32224. var OctreeBlock = (function () {
  32225. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32226. this.entries = new Array();
  32227. this._boundingVectors = new Array();
  32228. this._capacity = capacity;
  32229. this._depth = depth;
  32230. this._maxDepth = maxDepth;
  32231. this._creationFunc = creationFunc;
  32232. this._minPoint = minPoint;
  32233. this._maxPoint = maxPoint;
  32234. this._boundingVectors.push(minPoint.clone());
  32235. this._boundingVectors.push(maxPoint.clone());
  32236. this._boundingVectors.push(minPoint.clone());
  32237. this._boundingVectors[2].x = maxPoint.x;
  32238. this._boundingVectors.push(minPoint.clone());
  32239. this._boundingVectors[3].y = maxPoint.y;
  32240. this._boundingVectors.push(minPoint.clone());
  32241. this._boundingVectors[4].z = maxPoint.z;
  32242. this._boundingVectors.push(maxPoint.clone());
  32243. this._boundingVectors[5].z = minPoint.z;
  32244. this._boundingVectors.push(maxPoint.clone());
  32245. this._boundingVectors[6].x = minPoint.x;
  32246. this._boundingVectors.push(maxPoint.clone());
  32247. this._boundingVectors[7].y = minPoint.y;
  32248. }
  32249. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32250. // Property
  32251. get: function () {
  32252. return this._capacity;
  32253. },
  32254. enumerable: true,
  32255. configurable: true
  32256. });
  32257. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32258. get: function () {
  32259. return this._minPoint;
  32260. },
  32261. enumerable: true,
  32262. configurable: true
  32263. });
  32264. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32265. get: function () {
  32266. return this._maxPoint;
  32267. },
  32268. enumerable: true,
  32269. configurable: true
  32270. });
  32271. // Methods
  32272. OctreeBlock.prototype.addEntry = function (entry) {
  32273. if (this.blocks) {
  32274. for (var index = 0; index < this.blocks.length; index++) {
  32275. var block = this.blocks[index];
  32276. block.addEntry(entry);
  32277. }
  32278. return;
  32279. }
  32280. this._creationFunc(entry, this);
  32281. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32282. this.createInnerBlocks();
  32283. }
  32284. };
  32285. OctreeBlock.prototype.addEntries = function (entries) {
  32286. for (var index = 0; index < entries.length; index++) {
  32287. var mesh = entries[index];
  32288. this.addEntry(mesh);
  32289. }
  32290. };
  32291. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32292. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32293. if (this.blocks) {
  32294. for (var index = 0; index < this.blocks.length; index++) {
  32295. var block = this.blocks[index];
  32296. block.select(frustumPlanes, selection, allowDuplicate);
  32297. }
  32298. return;
  32299. }
  32300. if (allowDuplicate) {
  32301. selection.concat(this.entries);
  32302. }
  32303. else {
  32304. selection.concatWithNoDuplicate(this.entries);
  32305. }
  32306. }
  32307. };
  32308. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32309. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32310. if (this.blocks) {
  32311. for (var index = 0; index < this.blocks.length; index++) {
  32312. var block = this.blocks[index];
  32313. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32314. }
  32315. return;
  32316. }
  32317. if (allowDuplicate) {
  32318. selection.concat(this.entries);
  32319. }
  32320. else {
  32321. selection.concatWithNoDuplicate(this.entries);
  32322. }
  32323. }
  32324. };
  32325. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32326. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32327. if (this.blocks) {
  32328. for (var index = 0; index < this.blocks.length; index++) {
  32329. var block = this.blocks[index];
  32330. block.intersectsRay(ray, selection);
  32331. }
  32332. return;
  32333. }
  32334. selection.concatWithNoDuplicate(this.entries);
  32335. }
  32336. };
  32337. OctreeBlock.prototype.createInnerBlocks = function () {
  32338. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32339. };
  32340. return OctreeBlock;
  32341. })();
  32342. BABYLON.OctreeBlock = OctreeBlock;
  32343. })(BABYLON || (BABYLON = {}));
  32344. var BABYLON;
  32345. (function (BABYLON) {
  32346. var BlurPostProcess = (function (_super) {
  32347. __extends(BlurPostProcess, _super);
  32348. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32349. var _this = this;
  32350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32351. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32352. this.direction = direction;
  32353. this.blurWidth = blurWidth;
  32354. this.onApply = function (effect) {
  32355. effect.setFloat2("screenSize", _this.width, _this.height);
  32356. effect.setVector2("direction", _this.direction);
  32357. effect.setFloat("blurWidth", _this.blurWidth);
  32358. };
  32359. }
  32360. return BlurPostProcess;
  32361. })(BABYLON.PostProcess);
  32362. BABYLON.BlurPostProcess = BlurPostProcess;
  32363. })(BABYLON || (BABYLON = {}));
  32364. var BABYLON;
  32365. (function (BABYLON) {
  32366. var RefractionPostProcess = (function (_super) {
  32367. __extends(RefractionPostProcess, _super);
  32368. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32369. var _this = this;
  32370. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32371. this.color = color;
  32372. this.depth = depth;
  32373. this.colorLevel = colorLevel;
  32374. this.onActivate = function (cam) {
  32375. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32376. };
  32377. this.onApply = function (effect) {
  32378. effect.setColor3("baseColor", _this.color);
  32379. effect.setFloat("depth", _this.depth);
  32380. effect.setFloat("colorLevel", _this.colorLevel);
  32381. effect.setTexture("refractionSampler", _this._refRexture);
  32382. };
  32383. }
  32384. // Methods
  32385. RefractionPostProcess.prototype.dispose = function (camera) {
  32386. if (this._refRexture) {
  32387. this._refRexture.dispose();
  32388. }
  32389. _super.prototype.dispose.call(this, camera);
  32390. };
  32391. return RefractionPostProcess;
  32392. })(BABYLON.PostProcess);
  32393. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32394. })(BABYLON || (BABYLON = {}));
  32395. var BABYLON;
  32396. (function (BABYLON) {
  32397. var BlackAndWhitePostProcess = (function (_super) {
  32398. __extends(BlackAndWhitePostProcess, _super);
  32399. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32400. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32401. }
  32402. return BlackAndWhitePostProcess;
  32403. })(BABYLON.PostProcess);
  32404. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32405. })(BABYLON || (BABYLON = {}));
  32406. var BABYLON;
  32407. (function (BABYLON) {
  32408. var ConvolutionPostProcess = (function (_super) {
  32409. __extends(ConvolutionPostProcess, _super);
  32410. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32411. var _this = this;
  32412. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32413. this.kernel = kernel;
  32414. this.onApply = function (effect) {
  32415. effect.setFloat2("screenSize", _this.width, _this.height);
  32416. effect.setArray("kernel", _this.kernel);
  32417. };
  32418. }
  32419. // Statics
  32420. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32421. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32422. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32423. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32424. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32425. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32426. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32427. return ConvolutionPostProcess;
  32428. })(BABYLON.PostProcess);
  32429. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32430. })(BABYLON || (BABYLON = {}));
  32431. var BABYLON;
  32432. (function (BABYLON) {
  32433. var FilterPostProcess = (function (_super) {
  32434. __extends(FilterPostProcess, _super);
  32435. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32436. var _this = this;
  32437. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32438. this.kernelMatrix = kernelMatrix;
  32439. this.onApply = function (effect) {
  32440. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32441. };
  32442. }
  32443. return FilterPostProcess;
  32444. })(BABYLON.PostProcess);
  32445. BABYLON.FilterPostProcess = FilterPostProcess;
  32446. })(BABYLON || (BABYLON = {}));
  32447. var BABYLON;
  32448. (function (BABYLON) {
  32449. var FxaaPostProcess = (function (_super) {
  32450. __extends(FxaaPostProcess, _super);
  32451. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32452. var _this = this;
  32453. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32454. this.onSizeChanged = function () {
  32455. _this.texelWidth = 1.0 / _this.width;
  32456. _this.texelHeight = 1.0 / _this.height;
  32457. };
  32458. this.onApply = function (effect) {
  32459. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32460. };
  32461. }
  32462. return FxaaPostProcess;
  32463. })(BABYLON.PostProcess);
  32464. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32465. })(BABYLON || (BABYLON = {}));
  32466. var BABYLON;
  32467. (function (BABYLON) {
  32468. var StereoscopicInterlacePostProcess = (function (_super) {
  32469. __extends(StereoscopicInterlacePostProcess, _super);
  32470. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32471. var _this = this;
  32472. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32473. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32474. this.onSizeChanged = function () {
  32475. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32476. };
  32477. this.onApply = function (effect) {
  32478. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32479. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32480. };
  32481. }
  32482. return StereoscopicInterlacePostProcess;
  32483. })(BABYLON.PostProcess);
  32484. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32485. })(BABYLON || (BABYLON = {}));
  32486. var BABYLON;
  32487. (function (BABYLON) {
  32488. var LensFlare = (function () {
  32489. function LensFlare(size, position, color, imgUrl, system) {
  32490. this.size = size;
  32491. this.position = position;
  32492. this.dispose = function () {
  32493. if (this.texture) {
  32494. this.texture.dispose();
  32495. }
  32496. // Remove from scene
  32497. var index = this._system.lensFlares.indexOf(this);
  32498. this._system.lensFlares.splice(index, 1);
  32499. };
  32500. this.color = color || new BABYLON.Color3(1, 1, 1);
  32501. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32502. this._system = system;
  32503. system.lensFlares.push(this);
  32504. }
  32505. return LensFlare;
  32506. })();
  32507. BABYLON.LensFlare = LensFlare;
  32508. })(BABYLON || (BABYLON = {}));
  32509. var BABYLON;
  32510. (function (BABYLON) {
  32511. var LensFlareSystem = (function () {
  32512. function LensFlareSystem(name, emitter, scene) {
  32513. this.name = name;
  32514. this.lensFlares = new Array();
  32515. this.borderLimit = 300;
  32516. this.layerMask = 0x0FFFFFFF;
  32517. this._vertexDeclaration = [2];
  32518. this._vertexStrideSize = 2 * 4;
  32519. this._isEnabled = true;
  32520. this._scene = scene;
  32521. this._emitter = emitter;
  32522. scene.lensFlareSystems.push(this);
  32523. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32524. // VBO
  32525. var vertices = [];
  32526. vertices.push(1, 1);
  32527. vertices.push(-1, 1);
  32528. vertices.push(-1, -1);
  32529. vertices.push(1, -1);
  32530. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32531. // Indices
  32532. var indices = [];
  32533. indices.push(0);
  32534. indices.push(1);
  32535. indices.push(2);
  32536. indices.push(0);
  32537. indices.push(2);
  32538. indices.push(3);
  32539. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32540. // Effects
  32541. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32542. }
  32543. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32544. get: function () {
  32545. return this._isEnabled;
  32546. },
  32547. set: function (value) {
  32548. this._isEnabled = value;
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. LensFlareSystem.prototype.getScene = function () {
  32554. return this._scene;
  32555. };
  32556. LensFlareSystem.prototype.getEmitter = function () {
  32557. return this._emitter;
  32558. };
  32559. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32560. this._emitter = newEmitter;
  32561. };
  32562. LensFlareSystem.prototype.getEmitterPosition = function () {
  32563. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32564. };
  32565. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32566. var position = this.getEmitterPosition();
  32567. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32568. this._positionX = position.x;
  32569. this._positionY = position.y;
  32570. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32571. if (position.z > 0) {
  32572. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32573. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32574. return true;
  32575. }
  32576. }
  32577. return false;
  32578. };
  32579. LensFlareSystem.prototype._isVisible = function () {
  32580. if (!this._isEnabled) {
  32581. return false;
  32582. }
  32583. var emitterPosition = this.getEmitterPosition();
  32584. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32585. var distance = direction.length();
  32586. direction.normalize();
  32587. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32588. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32589. return !pickInfo.hit || pickInfo.distance > distance;
  32590. };
  32591. LensFlareSystem.prototype.render = function () {
  32592. if (!this._effect.isReady())
  32593. return false;
  32594. var engine = this._scene.getEngine();
  32595. var viewport = this._scene.activeCamera.viewport;
  32596. var globalViewport = viewport.toGlobal(engine);
  32597. // Position
  32598. if (!this.computeEffectivePosition(globalViewport)) {
  32599. return false;
  32600. }
  32601. // Visibility
  32602. if (!this._isVisible()) {
  32603. return false;
  32604. }
  32605. // Intensity
  32606. var awayX;
  32607. var awayY;
  32608. if (this._positionX < this.borderLimit + globalViewport.x) {
  32609. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32610. }
  32611. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32612. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32613. }
  32614. else {
  32615. awayX = 0;
  32616. }
  32617. if (this._positionY < this.borderLimit + globalViewport.y) {
  32618. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32619. }
  32620. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32621. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32622. }
  32623. else {
  32624. awayY = 0;
  32625. }
  32626. var away = (awayX > awayY) ? awayX : awayY;
  32627. if (away > this.borderLimit) {
  32628. away = this.borderLimit;
  32629. }
  32630. var intensity = 1.0 - (away / this.borderLimit);
  32631. if (intensity < 0) {
  32632. return false;
  32633. }
  32634. if (intensity > 1.0) {
  32635. intensity = 1.0;
  32636. }
  32637. // Position
  32638. var centerX = globalViewport.x + globalViewport.width / 2;
  32639. var centerY = globalViewport.y + globalViewport.height / 2;
  32640. var distX = centerX - this._positionX;
  32641. var distY = centerY - this._positionY;
  32642. // Effects
  32643. engine.enableEffect(this._effect);
  32644. engine.setState(false);
  32645. engine.setDepthBuffer(false);
  32646. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32647. // VBOs
  32648. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32649. // Flares
  32650. for (var index = 0; index < this.lensFlares.length; index++) {
  32651. var flare = this.lensFlares[index];
  32652. var x = centerX - (distX * flare.position);
  32653. var y = centerY - (distY * flare.position);
  32654. var cw = flare.size;
  32655. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32656. var cx = 2 * (x / globalViewport.width) - 1.0;
  32657. var cy = 1.0 - 2 * (y / globalViewport.height);
  32658. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32659. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32660. // Texture
  32661. this._effect.setTexture("textureSampler", flare.texture);
  32662. // Color
  32663. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32664. // Draw order
  32665. engine.draw(true, 0, 6);
  32666. }
  32667. engine.setDepthBuffer(true);
  32668. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32669. return true;
  32670. };
  32671. LensFlareSystem.prototype.dispose = function () {
  32672. if (this._vertexBuffer) {
  32673. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32674. this._vertexBuffer = null;
  32675. }
  32676. if (this._indexBuffer) {
  32677. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32678. this._indexBuffer = null;
  32679. }
  32680. while (this.lensFlares.length) {
  32681. this.lensFlares[0].dispose();
  32682. }
  32683. // Remove from scene
  32684. var index = this._scene.lensFlareSystems.indexOf(this);
  32685. this._scene.lensFlareSystems.splice(index, 1);
  32686. };
  32687. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  32688. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32689. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32690. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32691. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32692. var parsedFlare = parsedLensFlareSystem.flares[index];
  32693. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32694. }
  32695. return lensFlareSystem;
  32696. };
  32697. LensFlareSystem.prototype.serialize = function () {
  32698. var serializationObject = {};
  32699. serializationObject.emitterId = this.getEmitter().id;
  32700. serializationObject.borderLimit = this.borderLimit;
  32701. serializationObject.flares = [];
  32702. for (var index = 0; index < this.lensFlares.length; index++) {
  32703. var flare = this.lensFlares[index];
  32704. serializationObject.flares.push({
  32705. size: flare.size,
  32706. position: flare.position,
  32707. color: flare.color.asArray(),
  32708. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32709. });
  32710. }
  32711. return serializationObject;
  32712. };
  32713. return LensFlareSystem;
  32714. })();
  32715. BABYLON.LensFlareSystem = LensFlareSystem;
  32716. })(BABYLON || (BABYLON = {}));
  32717. var BABYLON;
  32718. (function (BABYLON) {
  32719. // We're mainly based on the logic defined into the FreeCamera code
  32720. var DeviceOrientationCamera = (function (_super) {
  32721. __extends(DeviceOrientationCamera, _super);
  32722. function DeviceOrientationCamera(name, position, scene) {
  32723. var _this = this;
  32724. _super.call(this, name, position, scene);
  32725. this._offsetX = null;
  32726. this._offsetY = null;
  32727. this._orientationGamma = 0;
  32728. this._orientationBeta = 0;
  32729. this._initialOrientationGamma = 0;
  32730. this._initialOrientationBeta = 0;
  32731. this.angularSensibility = 10000.0;
  32732. this.moveSensibility = 50.0;
  32733. window.addEventListener("resize", function () {
  32734. _this._initialOrientationGamma = null;
  32735. }, false);
  32736. }
  32737. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32738. var _this = this;
  32739. if (this._attachedCanvas) {
  32740. return;
  32741. }
  32742. this._attachedCanvas = canvas;
  32743. if (!this._orientationChanged) {
  32744. this._orientationChanged = function (evt) {
  32745. if (!_this._initialOrientationGamma) {
  32746. _this._initialOrientationGamma = evt.gamma;
  32747. _this._initialOrientationBeta = evt.beta;
  32748. }
  32749. _this._orientationGamma = evt.gamma;
  32750. _this._orientationBeta = evt.beta;
  32751. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32752. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32753. };
  32754. }
  32755. window.addEventListener("deviceorientation", this._orientationChanged);
  32756. };
  32757. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32758. if (this._attachedCanvas !== canvas) {
  32759. return;
  32760. }
  32761. window.removeEventListener("deviceorientation", this._orientationChanged);
  32762. this._attachedCanvas = null;
  32763. this._orientationGamma = 0;
  32764. this._orientationBeta = 0;
  32765. this._initialOrientationGamma = 0;
  32766. this._initialOrientationBeta = 0;
  32767. };
  32768. DeviceOrientationCamera.prototype._checkInputs = function () {
  32769. if (!this._offsetX) {
  32770. return;
  32771. }
  32772. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32773. var speed = this._computeLocalCameraSpeed();
  32774. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32775. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32776. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32777. _super.prototype._checkInputs.call(this);
  32778. };
  32779. return DeviceOrientationCamera;
  32780. })(BABYLON.FreeCamera);
  32781. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32782. })(BABYLON || (BABYLON = {}));
  32783. var BABYLON;
  32784. (function (BABYLON) {
  32785. var Gamepads = (function () {
  32786. function Gamepads(ongamedpadconnected) {
  32787. var _this = this;
  32788. this.babylonGamepads = [];
  32789. this.oneGamepadConnected = false;
  32790. this.isMonitoring = false;
  32791. this.gamepadEventSupported = 'GamepadEvent' in window;
  32792. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32793. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32794. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  32795. this._callbackGamepadConnected = ongamedpadconnected;
  32796. if (this.gamepadSupportAvailable) {
  32797. // Checking if the gamepad connected event is supported (like in Firefox)
  32798. if (this.gamepadEventSupported) {
  32799. window.addEventListener('gamepadconnected', function (evt) {
  32800. _this._onGamepadConnected(evt);
  32801. }, false);
  32802. window.addEventListener('gamepaddisconnected', function (evt) {
  32803. _this._onGamepadDisconnected(evt);
  32804. }, false);
  32805. }
  32806. else {
  32807. this._startMonitoringGamepads();
  32808. }
  32809. if (!this.oneGamepadConnected) {
  32810. this._insertGamepadDOMInstructions();
  32811. }
  32812. }
  32813. else {
  32814. this._insertGamepadDOMNotSupported();
  32815. }
  32816. }
  32817. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32818. Gamepads.gamepadDOMInfo = document.createElement("div");
  32819. var buttonAImage = document.createElement("img");
  32820. buttonAImage.src = this.buttonADataURL;
  32821. var spanMessage = document.createElement("span");
  32822. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32823. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32824. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32825. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32826. Gamepads.gamepadDOMInfo.style.width = "100%";
  32827. Gamepads.gamepadDOMInfo.style.height = "48px";
  32828. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32829. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32830. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32831. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32832. buttonAImage.style.position = "relative";
  32833. buttonAImage.style.bottom = "8px";
  32834. spanMessage.style.position = "relative";
  32835. spanMessage.style.fontSize = "32px";
  32836. spanMessage.style.bottom = "32px";
  32837. spanMessage.style.color = "green";
  32838. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32839. };
  32840. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32841. Gamepads.gamepadDOMInfo = document.createElement("div");
  32842. var spanMessage = document.createElement("span");
  32843. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32844. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32845. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32846. Gamepads.gamepadDOMInfo.style.width = "100%";
  32847. Gamepads.gamepadDOMInfo.style.height = "40px";
  32848. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32849. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32850. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32851. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32852. spanMessage.style.position = "relative";
  32853. spanMessage.style.fontSize = "32px";
  32854. spanMessage.style.color = "red";
  32855. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32856. };
  32857. Gamepads.prototype.dispose = function () {
  32858. if (Gamepads.gamepadDOMInfo) {
  32859. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32860. }
  32861. };
  32862. Gamepads.prototype._onGamepadConnected = function (evt) {
  32863. var newGamepad = this._addNewGamepad(evt.gamepad);
  32864. if (this._callbackGamepadConnected)
  32865. this._callbackGamepadConnected(newGamepad);
  32866. this._startMonitoringGamepads();
  32867. };
  32868. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32869. if (!this.oneGamepadConnected) {
  32870. this.oneGamepadConnected = true;
  32871. if (Gamepads.gamepadDOMInfo) {
  32872. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32873. Gamepads.gamepadDOMInfo = null;
  32874. }
  32875. }
  32876. var newGamepad;
  32877. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32878. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32879. }
  32880. else {
  32881. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32882. }
  32883. this.babylonGamepads.push(newGamepad);
  32884. return newGamepad;
  32885. };
  32886. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32887. // Remove the gamepad from the list of gamepads to monitor.
  32888. for (var i in this.babylonGamepads) {
  32889. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32890. this.babylonGamepads.splice(i, 1);
  32891. break;
  32892. }
  32893. }
  32894. // If no gamepads are left, stop the polling loop.
  32895. if (this.babylonGamepads.length == 0) {
  32896. this._stopMonitoringGamepads();
  32897. }
  32898. };
  32899. Gamepads.prototype._startMonitoringGamepads = function () {
  32900. if (!this.isMonitoring) {
  32901. this.isMonitoring = true;
  32902. this._checkGamepadsStatus();
  32903. }
  32904. };
  32905. Gamepads.prototype._stopMonitoringGamepads = function () {
  32906. this.isMonitoring = false;
  32907. };
  32908. Gamepads.prototype._checkGamepadsStatus = function () {
  32909. var _this = this;
  32910. // updating gamepad objects
  32911. this._updateGamepadObjects();
  32912. for (var i in this.babylonGamepads) {
  32913. this.babylonGamepads[i].update();
  32914. }
  32915. if (this.isMonitoring) {
  32916. if (window.requestAnimationFrame) {
  32917. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32918. }
  32919. else if (window.mozRequestAnimationFrame) {
  32920. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32921. }
  32922. else if (window.webkitRequestAnimationFrame) {
  32923. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32924. }
  32925. }
  32926. };
  32927. // This function is called only on Chrome, which does not yet support
  32928. // connection/disconnection events, but requires you to monitor
  32929. // an array for changes.
  32930. Gamepads.prototype._updateGamepadObjects = function () {
  32931. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32932. for (var i = 0; i < gamepads.length; i++) {
  32933. if (gamepads[i]) {
  32934. if (!(gamepads[i].index in this.babylonGamepads)) {
  32935. var newGamepad = this._addNewGamepad(gamepads[i]);
  32936. if (this._callbackGamepadConnected) {
  32937. this._callbackGamepadConnected(newGamepad);
  32938. }
  32939. }
  32940. else {
  32941. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32942. }
  32943. }
  32944. }
  32945. };
  32946. return Gamepads;
  32947. })();
  32948. BABYLON.Gamepads = Gamepads;
  32949. var StickValues = (function () {
  32950. function StickValues(x, y) {
  32951. this.x = x;
  32952. this.y = y;
  32953. }
  32954. return StickValues;
  32955. })();
  32956. BABYLON.StickValues = StickValues;
  32957. var Gamepad = (function () {
  32958. function Gamepad(id, index, browserGamepad) {
  32959. this.id = id;
  32960. this.index = index;
  32961. this.browserGamepad = browserGamepad;
  32962. if (this.browserGamepad.axes.length >= 2) {
  32963. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32964. }
  32965. if (this.browserGamepad.axes.length >= 4) {
  32966. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32967. }
  32968. }
  32969. Gamepad.prototype.onleftstickchanged = function (callback) {
  32970. this._onleftstickchanged = callback;
  32971. };
  32972. Gamepad.prototype.onrightstickchanged = function (callback) {
  32973. this._onrightstickchanged = callback;
  32974. };
  32975. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32976. get: function () {
  32977. return this._leftStick;
  32978. },
  32979. set: function (newValues) {
  32980. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32981. this._onleftstickchanged(newValues);
  32982. }
  32983. this._leftStick = newValues;
  32984. },
  32985. enumerable: true,
  32986. configurable: true
  32987. });
  32988. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32989. get: function () {
  32990. return this._rightStick;
  32991. },
  32992. set: function (newValues) {
  32993. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32994. this._onrightstickchanged(newValues);
  32995. }
  32996. this._rightStick = newValues;
  32997. },
  32998. enumerable: true,
  32999. configurable: true
  33000. });
  33001. Gamepad.prototype.update = function () {
  33002. if (this._leftStick) {
  33003. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33004. }
  33005. if (this._rightStick) {
  33006. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33007. }
  33008. };
  33009. return Gamepad;
  33010. })();
  33011. BABYLON.Gamepad = Gamepad;
  33012. var GenericPad = (function (_super) {
  33013. __extends(GenericPad, _super);
  33014. function GenericPad(id, index, gamepad) {
  33015. _super.call(this, id, index, gamepad);
  33016. this.id = id;
  33017. this.index = index;
  33018. this.gamepad = gamepad;
  33019. this._buttons = new Array(gamepad.buttons.length);
  33020. }
  33021. GenericPad.prototype.onbuttondown = function (callback) {
  33022. this._onbuttondown = callback;
  33023. };
  33024. GenericPad.prototype.onbuttonup = function (callback) {
  33025. this._onbuttonup = callback;
  33026. };
  33027. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33028. if (newValue !== currentValue) {
  33029. if (this._onbuttondown && newValue === 1) {
  33030. this._onbuttondown(buttonIndex);
  33031. }
  33032. if (this._onbuttonup && newValue === 0) {
  33033. this._onbuttonup(buttonIndex);
  33034. }
  33035. }
  33036. return newValue;
  33037. };
  33038. GenericPad.prototype.update = function () {
  33039. _super.prototype.update.call(this);
  33040. for (var index = 0; index < this._buttons.length; index++) {
  33041. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33042. }
  33043. };
  33044. return GenericPad;
  33045. })(Gamepad);
  33046. BABYLON.GenericPad = GenericPad;
  33047. (function (Xbox360Button) {
  33048. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33049. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33050. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33051. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33052. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33053. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33054. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33055. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33056. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33057. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33058. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33059. var Xbox360Button = BABYLON.Xbox360Button;
  33060. (function (Xbox360Dpad) {
  33061. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33062. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33063. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33064. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33065. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33066. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33067. var Xbox360Pad = (function (_super) {
  33068. __extends(Xbox360Pad, _super);
  33069. function Xbox360Pad() {
  33070. _super.apply(this, arguments);
  33071. this._leftTrigger = 0;
  33072. this._rightTrigger = 0;
  33073. this._buttonA = 0;
  33074. this._buttonB = 0;
  33075. this._buttonX = 0;
  33076. this._buttonY = 0;
  33077. this._buttonBack = 0;
  33078. this._buttonStart = 0;
  33079. this._buttonLB = 0;
  33080. this._buttonRB = 0;
  33081. this._buttonLeftStick = 0;
  33082. this._buttonRightStick = 0;
  33083. this._dPadUp = 0;
  33084. this._dPadDown = 0;
  33085. this._dPadLeft = 0;
  33086. this._dPadRight = 0;
  33087. }
  33088. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33089. this._onlefttriggerchanged = callback;
  33090. };
  33091. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33092. this._onrighttriggerchanged = callback;
  33093. };
  33094. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33095. get: function () {
  33096. return this._leftTrigger;
  33097. },
  33098. set: function (newValue) {
  33099. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33100. this._onlefttriggerchanged(newValue);
  33101. }
  33102. this._leftTrigger = newValue;
  33103. },
  33104. enumerable: true,
  33105. configurable: true
  33106. });
  33107. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33108. get: function () {
  33109. return this._rightTrigger;
  33110. },
  33111. set: function (newValue) {
  33112. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33113. this._onrighttriggerchanged(newValue);
  33114. }
  33115. this._rightTrigger = newValue;
  33116. },
  33117. enumerable: true,
  33118. configurable: true
  33119. });
  33120. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33121. this._onbuttondown = callback;
  33122. };
  33123. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33124. this._onbuttonup = callback;
  33125. };
  33126. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33127. this._ondpaddown = callback;
  33128. };
  33129. Xbox360Pad.prototype.ondpadup = function (callback) {
  33130. this._ondpadup = callback;
  33131. };
  33132. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33133. if (newValue !== currentValue) {
  33134. if (this._onbuttondown && newValue === 1) {
  33135. this._onbuttondown(buttonType);
  33136. }
  33137. if (this._onbuttonup && newValue === 0) {
  33138. this._onbuttonup(buttonType);
  33139. }
  33140. }
  33141. return newValue;
  33142. };
  33143. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33144. if (newValue !== currentValue) {
  33145. if (this._ondpaddown && newValue === 1) {
  33146. this._ondpaddown(buttonType);
  33147. }
  33148. if (this._ondpadup && newValue === 0) {
  33149. this._ondpadup(buttonType);
  33150. }
  33151. }
  33152. return newValue;
  33153. };
  33154. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33155. get: function () {
  33156. return this._buttonA;
  33157. },
  33158. set: function (value) {
  33159. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33160. },
  33161. enumerable: true,
  33162. configurable: true
  33163. });
  33164. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33165. get: function () {
  33166. return this._buttonB;
  33167. },
  33168. set: function (value) {
  33169. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33170. },
  33171. enumerable: true,
  33172. configurable: true
  33173. });
  33174. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33175. get: function () {
  33176. return this._buttonX;
  33177. },
  33178. set: function (value) {
  33179. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33180. },
  33181. enumerable: true,
  33182. configurable: true
  33183. });
  33184. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33185. get: function () {
  33186. return this._buttonY;
  33187. },
  33188. set: function (value) {
  33189. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33190. },
  33191. enumerable: true,
  33192. configurable: true
  33193. });
  33194. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33195. get: function () {
  33196. return this._buttonStart;
  33197. },
  33198. set: function (value) {
  33199. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33200. },
  33201. enumerable: true,
  33202. configurable: true
  33203. });
  33204. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33205. get: function () {
  33206. return this._buttonBack;
  33207. },
  33208. set: function (value) {
  33209. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33210. },
  33211. enumerable: true,
  33212. configurable: true
  33213. });
  33214. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33215. get: function () {
  33216. return this._buttonLB;
  33217. },
  33218. set: function (value) {
  33219. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33220. },
  33221. enumerable: true,
  33222. configurable: true
  33223. });
  33224. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33225. get: function () {
  33226. return this._buttonRB;
  33227. },
  33228. set: function (value) {
  33229. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33230. },
  33231. enumerable: true,
  33232. configurable: true
  33233. });
  33234. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33235. get: function () {
  33236. return this._buttonLeftStick;
  33237. },
  33238. set: function (value) {
  33239. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33240. },
  33241. enumerable: true,
  33242. configurable: true
  33243. });
  33244. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33245. get: function () {
  33246. return this._buttonRightStick;
  33247. },
  33248. set: function (value) {
  33249. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33250. },
  33251. enumerable: true,
  33252. configurable: true
  33253. });
  33254. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33255. get: function () {
  33256. return this._dPadUp;
  33257. },
  33258. set: function (value) {
  33259. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33260. },
  33261. enumerable: true,
  33262. configurable: true
  33263. });
  33264. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33265. get: function () {
  33266. return this._dPadDown;
  33267. },
  33268. set: function (value) {
  33269. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33270. },
  33271. enumerable: true,
  33272. configurable: true
  33273. });
  33274. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33275. get: function () {
  33276. return this._dPadLeft;
  33277. },
  33278. set: function (value) {
  33279. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33285. get: function () {
  33286. return this._dPadRight;
  33287. },
  33288. set: function (value) {
  33289. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33290. },
  33291. enumerable: true,
  33292. configurable: true
  33293. });
  33294. Xbox360Pad.prototype.update = function () {
  33295. _super.prototype.update.call(this);
  33296. this.buttonA = this.browserGamepad.buttons[0].value;
  33297. this.buttonB = this.browserGamepad.buttons[1].value;
  33298. this.buttonX = this.browserGamepad.buttons[2].value;
  33299. this.buttonY = this.browserGamepad.buttons[3].value;
  33300. this.buttonLB = this.browserGamepad.buttons[4].value;
  33301. this.buttonRB = this.browserGamepad.buttons[5].value;
  33302. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33303. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33304. this.buttonBack = this.browserGamepad.buttons[8].value;
  33305. this.buttonStart = this.browserGamepad.buttons[9].value;
  33306. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33307. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33308. this.dPadUp = this.browserGamepad.buttons[12].value;
  33309. this.dPadDown = this.browserGamepad.buttons[13].value;
  33310. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33311. this.dPadRight = this.browserGamepad.buttons[15].value;
  33312. };
  33313. return Xbox360Pad;
  33314. })(Gamepad);
  33315. BABYLON.Xbox360Pad = Xbox360Pad;
  33316. })(BABYLON || (BABYLON = {}));
  33317. var BABYLON;
  33318. (function (BABYLON) {
  33319. // We're mainly based on the logic defined into the FreeCamera code
  33320. var GamepadCamera = (function (_super) {
  33321. __extends(GamepadCamera, _super);
  33322. function GamepadCamera(name, position, scene) {
  33323. var _this = this;
  33324. _super.call(this, name, position, scene);
  33325. this.angularSensibility = 200;
  33326. this.moveSensibility = 75;
  33327. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33328. }
  33329. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33330. // Only the first gamepad can control the camera
  33331. if (gamepad.index === 0) {
  33332. this._gamepad = gamepad;
  33333. }
  33334. };
  33335. GamepadCamera.prototype._checkInputs = function () {
  33336. if (this._gamepad) {
  33337. var LSValues = this._gamepad.leftStick;
  33338. var normalizedLX = LSValues.x / this.moveSensibility;
  33339. var normalizedLY = LSValues.y / this.moveSensibility;
  33340. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33341. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33342. var RSValues = this._gamepad.rightStick;
  33343. var normalizedRX = RSValues.x / this.angularSensibility;
  33344. var normalizedRY = RSValues.y / this.angularSensibility;
  33345. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33346. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33347. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33348. var speed = this._computeLocalCameraSpeed() * 50.0;
  33349. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33350. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33351. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33352. }
  33353. _super.prototype._checkInputs.call(this);
  33354. };
  33355. GamepadCamera.prototype.dispose = function () {
  33356. this._gamepads.dispose();
  33357. _super.prototype.dispose.call(this);
  33358. };
  33359. return GamepadCamera;
  33360. })(BABYLON.FreeCamera);
  33361. BABYLON.GamepadCamera = GamepadCamera;
  33362. })(BABYLON || (BABYLON = {}));
  33363. var BABYLON;
  33364. (function (BABYLON) {
  33365. var Analyser = (function () {
  33366. function Analyser(scene) {
  33367. this.SMOOTHING = 0.75;
  33368. this.FFT_SIZE = 512;
  33369. this.BARGRAPHAMPLITUDE = 256;
  33370. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33371. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33372. this._scene = scene;
  33373. this._audioEngine = BABYLON.Engine.audioEngine;
  33374. if (this._audioEngine.canUseWebAudio) {
  33375. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33376. this._webAudioAnalyser.minDecibels = -140;
  33377. this._webAudioAnalyser.maxDecibels = 0;
  33378. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33379. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33380. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33381. }
  33382. }
  33383. Analyser.prototype.getFrequencyBinCount = function () {
  33384. if (this._audioEngine.canUseWebAudio) {
  33385. return this._webAudioAnalyser.frequencyBinCount;
  33386. }
  33387. else {
  33388. return 0;
  33389. }
  33390. };
  33391. Analyser.prototype.getByteFrequencyData = function () {
  33392. if (this._audioEngine.canUseWebAudio) {
  33393. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33394. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33395. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33396. }
  33397. return this._byteFreqs;
  33398. };
  33399. Analyser.prototype.getByteTimeDomainData = function () {
  33400. if (this._audioEngine.canUseWebAudio) {
  33401. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33402. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33403. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33404. }
  33405. return this._byteTime;
  33406. };
  33407. Analyser.prototype.getFloatFrequencyData = function () {
  33408. if (this._audioEngine.canUseWebAudio) {
  33409. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33410. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33411. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33412. }
  33413. return this._floatFreqs;
  33414. };
  33415. Analyser.prototype.drawDebugCanvas = function () {
  33416. var _this = this;
  33417. if (this._audioEngine.canUseWebAudio) {
  33418. if (!this._debugCanvas) {
  33419. this._debugCanvas = document.createElement("canvas");
  33420. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33421. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33422. this._debugCanvas.style.position = "absolute";
  33423. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33424. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33425. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33426. document.body.appendChild(this._debugCanvas);
  33427. this._registerFunc = function () {
  33428. _this.drawDebugCanvas();
  33429. };
  33430. this._scene.registerBeforeRender(this._registerFunc);
  33431. }
  33432. if (this._registerFunc) {
  33433. var workingArray = this.getByteFrequencyData();
  33434. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33435. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33436. // Draw the frequency domain chart.
  33437. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33438. var value = workingArray[i];
  33439. var percent = value / this.BARGRAPHAMPLITUDE;
  33440. var height = this.DEBUGCANVASSIZE.height * percent;
  33441. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33442. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33443. var hue = i / this.getFrequencyBinCount() * 360;
  33444. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33445. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33446. }
  33447. }
  33448. }
  33449. };
  33450. Analyser.prototype.stopDebugCanvas = function () {
  33451. if (this._debugCanvas) {
  33452. this._scene.unregisterBeforeRender(this._registerFunc);
  33453. this._registerFunc = null;
  33454. document.body.removeChild(this._debugCanvas);
  33455. this._debugCanvas = null;
  33456. this._debugCanvasContext = null;
  33457. }
  33458. };
  33459. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33460. if (this._audioEngine.canUseWebAudio) {
  33461. inputAudioNode.connect(this._webAudioAnalyser);
  33462. this._webAudioAnalyser.connect(outputAudioNode);
  33463. }
  33464. };
  33465. Analyser.prototype.dispose = function () {
  33466. if (this._audioEngine.canUseWebAudio) {
  33467. this._webAudioAnalyser.disconnect();
  33468. }
  33469. };
  33470. return Analyser;
  33471. })();
  33472. BABYLON.Analyser = Analyser;
  33473. })(BABYLON || (BABYLON = {}));
  33474. var BABYLON;
  33475. (function (BABYLON) {
  33476. var AudioEngine = (function () {
  33477. function AudioEngine() {
  33478. this._audioContext = null;
  33479. this._audioContextInitialized = false;
  33480. this.canUseWebAudio = false;
  33481. this.WarnedWebAudioUnsupported = false;
  33482. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33483. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33484. this.canUseWebAudio = true;
  33485. }
  33486. }
  33487. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33488. get: function () {
  33489. if (!this._audioContextInitialized) {
  33490. this._initializeAudioContext();
  33491. }
  33492. return this._audioContext;
  33493. },
  33494. enumerable: true,
  33495. configurable: true
  33496. });
  33497. AudioEngine.prototype._initializeAudioContext = function () {
  33498. try {
  33499. if (this.canUseWebAudio) {
  33500. this._audioContext = new AudioContext();
  33501. // create a global volume gain node
  33502. this.masterGain = this._audioContext.createGain();
  33503. this.masterGain.gain.value = 1;
  33504. this.masterGain.connect(this._audioContext.destination);
  33505. this._audioContextInitialized = true;
  33506. }
  33507. }
  33508. catch (e) {
  33509. this.canUseWebAudio = false;
  33510. BABYLON.Tools.Error("Web Audio: " + e.message);
  33511. }
  33512. };
  33513. AudioEngine.prototype.dispose = function () {
  33514. if (this.canUseWebAudio && this._audioContextInitialized) {
  33515. if (this._connectedAnalyser) {
  33516. this._connectedAnalyser.stopDebugCanvas();
  33517. this._connectedAnalyser.dispose();
  33518. this.masterGain.disconnect();
  33519. this.masterGain.connect(this._audioContext.destination);
  33520. this._connectedAnalyser = null;
  33521. }
  33522. this.masterGain.gain.value = 1;
  33523. }
  33524. this.WarnedWebAudioUnsupported = false;
  33525. };
  33526. AudioEngine.prototype.getGlobalVolume = function () {
  33527. if (this.canUseWebAudio && this._audioContextInitialized) {
  33528. return this.masterGain.gain.value;
  33529. }
  33530. else {
  33531. return -1;
  33532. }
  33533. };
  33534. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33535. if (this.canUseWebAudio && this._audioContextInitialized) {
  33536. this.masterGain.gain.value = newVolume;
  33537. }
  33538. };
  33539. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33540. if (this._connectedAnalyser) {
  33541. this._connectedAnalyser.stopDebugCanvas();
  33542. }
  33543. if (this.canUseWebAudio && this._audioContextInitialized) {
  33544. this._connectedAnalyser = analyser;
  33545. this.masterGain.disconnect();
  33546. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33547. }
  33548. };
  33549. return AudioEngine;
  33550. })();
  33551. BABYLON.AudioEngine = AudioEngine;
  33552. })(BABYLON || (BABYLON = {}));
  33553. var BABYLON;
  33554. (function (BABYLON) {
  33555. var Sound = (function () {
  33556. /**
  33557. * Create a sound and attach it to a scene
  33558. * @param name Name of your sound
  33559. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33560. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33561. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33562. */
  33563. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33564. var _this = this;
  33565. this.autoplay = false;
  33566. this.loop = false;
  33567. this.useCustomAttenuation = false;
  33568. this.spatialSound = false;
  33569. this.refDistance = 1;
  33570. this.rolloffFactor = 1;
  33571. this.maxDistance = 100;
  33572. this.distanceModel = "linear";
  33573. this._panningModel = "equalpower";
  33574. this._playbackRate = 1;
  33575. this._streaming = false;
  33576. this._startTime = 0;
  33577. this._startOffset = 0;
  33578. this._position = BABYLON.Vector3.Zero();
  33579. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33580. this._volume = 1;
  33581. this._isLoaded = false;
  33582. this._isReadyToPlay = false;
  33583. this.isPlaying = false;
  33584. this.isPaused = false;
  33585. this._isDirectional = false;
  33586. // Used if you'd like to create a directional sound.
  33587. // If not set, the sound will be omnidirectional
  33588. this._coneInnerAngle = 360;
  33589. this._coneOuterAngle = 360;
  33590. this._coneOuterGain = 0;
  33591. this._isOutputConnected = false;
  33592. this.name = name;
  33593. this._scene = scene;
  33594. this._readyToPlayCallback = readyToPlayCallback;
  33595. // Default custom attenuation function is a linear attenuation
  33596. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33597. if (currentDistance < maxDistance) {
  33598. return currentVolume * (1 - currentDistance / maxDistance);
  33599. }
  33600. else {
  33601. return 0;
  33602. }
  33603. };
  33604. if (options) {
  33605. this.autoplay = options.autoplay || false;
  33606. this.loop = options.loop || false;
  33607. // if volume === 0, we need another way to check this option
  33608. if (options.volume !== undefined) {
  33609. this._volume = options.volume;
  33610. }
  33611. this.spatialSound = options.spatialSound || false;
  33612. this.maxDistance = options.maxDistance || 100;
  33613. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33614. this.rolloffFactor = options.rolloffFactor || 1;
  33615. this.refDistance = options.refDistance || 1;
  33616. this.distanceModel = options.distanceModel || "linear";
  33617. this._playbackRate = options.playbackRate || 1;
  33618. this._streaming = options.streaming || false;
  33619. }
  33620. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33621. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33622. this._soundGain.gain.value = this._volume;
  33623. this._inputAudioNode = this._soundGain;
  33624. this._ouputAudioNode = this._soundGain;
  33625. if (this.spatialSound) {
  33626. this._createSpatialParameters();
  33627. }
  33628. this._scene.mainSoundTrack.AddSound(this);
  33629. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33630. if (urlOrArrayBuffer) {
  33631. // If it's an URL
  33632. if (typeof (urlOrArrayBuffer) === "string") {
  33633. // Loading sound using XHR2
  33634. if (!this._streaming) {
  33635. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33636. }
  33637. else {
  33638. this._htmlAudioElement = new Audio();
  33639. this._htmlAudioElement.src = urlOrArrayBuffer;
  33640. this._htmlAudioElement.controls = false;
  33641. this._htmlAudioElement.loop = this.loop;
  33642. this._htmlAudioElement.crossOrigin = "anonymous";
  33643. this._isReadyToPlay = true;
  33644. document.body.appendChild(this._htmlAudioElement);
  33645. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33646. if (this._readyToPlayCallback) {
  33647. window.setTimeout(function () {
  33648. _this._readyToPlayCallback();
  33649. }, 1000);
  33650. }
  33651. if (this.autoplay) {
  33652. this.play();
  33653. }
  33654. }
  33655. }
  33656. else {
  33657. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33658. this._soundLoaded(urlOrArrayBuffer);
  33659. }
  33660. else {
  33661. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33662. }
  33663. }
  33664. }
  33665. }
  33666. else {
  33667. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33668. this._scene.mainSoundTrack.AddSound(this);
  33669. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33670. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33671. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33672. }
  33673. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33674. if (this._readyToPlayCallback) {
  33675. window.setTimeout(function () {
  33676. _this._readyToPlayCallback();
  33677. }, 1000);
  33678. }
  33679. }
  33680. }
  33681. Sound.prototype.dispose = function () {
  33682. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33683. if (this.isPlaying) {
  33684. this.stop();
  33685. }
  33686. this._isReadyToPlay = false;
  33687. if (this.soundTrackId === -1) {
  33688. this._scene.mainSoundTrack.RemoveSound(this);
  33689. }
  33690. else {
  33691. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33692. }
  33693. if (this._soundGain) {
  33694. this._soundGain.disconnect();
  33695. this._soundGain = null;
  33696. }
  33697. if (this._soundPanner) {
  33698. this._soundPanner.disconnect();
  33699. this._soundPanner = null;
  33700. }
  33701. if (this._soundSource) {
  33702. this._soundSource.disconnect();
  33703. this._soundSource = null;
  33704. }
  33705. this._audioBuffer = null;
  33706. if (this._htmlAudioElement) {
  33707. this._htmlAudioElement.pause();
  33708. this._htmlAudioElement.src = "";
  33709. document.body.removeChild(this._htmlAudioElement);
  33710. }
  33711. if (this._connectedMesh) {
  33712. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33713. this._connectedMesh = null;
  33714. }
  33715. }
  33716. };
  33717. Sound.prototype._soundLoaded = function (audioData) {
  33718. var _this = this;
  33719. this._isLoaded = true;
  33720. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33721. _this._audioBuffer = buffer;
  33722. _this._isReadyToPlay = true;
  33723. if (_this.autoplay) {
  33724. _this.play();
  33725. }
  33726. if (_this._readyToPlayCallback) {
  33727. _this._readyToPlayCallback();
  33728. }
  33729. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33730. };
  33731. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33732. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33733. this._audioBuffer = audioBuffer;
  33734. this._isReadyToPlay = true;
  33735. }
  33736. };
  33737. Sound.prototype.updateOptions = function (options) {
  33738. if (options) {
  33739. this.loop = options.loop || this.loop;
  33740. this.maxDistance = options.maxDistance || this.maxDistance;
  33741. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33742. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33743. this.refDistance = options.refDistance || this.refDistance;
  33744. this.distanceModel = options.distanceModel || this.distanceModel;
  33745. this._playbackRate = options.playbackRate || this._playbackRate;
  33746. this._updateSpatialParameters();
  33747. if (this.isPlaying) {
  33748. if (this._streaming) {
  33749. this._htmlAudioElement.playbackRate = this._playbackRate;
  33750. }
  33751. else {
  33752. this._soundSource.playbackRate.value = this._playbackRate;
  33753. }
  33754. }
  33755. }
  33756. };
  33757. Sound.prototype._createSpatialParameters = function () {
  33758. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33759. if (this._scene.headphone) {
  33760. this._panningModel = "HRTF";
  33761. }
  33762. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33763. this._updateSpatialParameters();
  33764. this._soundPanner.connect(this._ouputAudioNode);
  33765. this._inputAudioNode = this._soundPanner;
  33766. }
  33767. };
  33768. Sound.prototype._updateSpatialParameters = function () {
  33769. if (this.spatialSound) {
  33770. if (this.useCustomAttenuation) {
  33771. // Tricks to disable in a way embedded Web Audio attenuation
  33772. this._soundPanner.distanceModel = "linear";
  33773. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33774. this._soundPanner.refDistance = 1;
  33775. this._soundPanner.rolloffFactor = 1;
  33776. this._soundPanner.panningModel = this._panningModel;
  33777. }
  33778. else {
  33779. this._soundPanner.distanceModel = this.distanceModel;
  33780. this._soundPanner.maxDistance = this.maxDistance;
  33781. this._soundPanner.refDistance = this.refDistance;
  33782. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33783. this._soundPanner.panningModel = this._panningModel;
  33784. }
  33785. }
  33786. };
  33787. Sound.prototype.switchPanningModelToHRTF = function () {
  33788. this._panningModel = "HRTF";
  33789. this._switchPanningModel();
  33790. };
  33791. Sound.prototype.switchPanningModelToEqualPower = function () {
  33792. this._panningModel = "equalpower";
  33793. this._switchPanningModel();
  33794. };
  33795. Sound.prototype._switchPanningModel = function () {
  33796. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33797. this._soundPanner.panningModel = this._panningModel;
  33798. }
  33799. };
  33800. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33801. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33802. if (this._isOutputConnected) {
  33803. this._ouputAudioNode.disconnect();
  33804. }
  33805. this._ouputAudioNode.connect(soundTrackAudioNode);
  33806. this._isOutputConnected = true;
  33807. }
  33808. };
  33809. /**
  33810. * Transform this sound into a directional source
  33811. * @param coneInnerAngle Size of the inner cone in degree
  33812. * @param coneOuterAngle Size of the outer cone in degree
  33813. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33814. */
  33815. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33816. if (coneOuterAngle < coneInnerAngle) {
  33817. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33818. return;
  33819. }
  33820. this._coneInnerAngle = coneInnerAngle;
  33821. this._coneOuterAngle = coneOuterAngle;
  33822. this._coneOuterGain = coneOuterGain;
  33823. this._isDirectional = true;
  33824. if (this.isPlaying && this.loop) {
  33825. this.stop();
  33826. this.play();
  33827. }
  33828. };
  33829. Sound.prototype.setPosition = function (newPosition) {
  33830. this._position = newPosition;
  33831. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33832. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33833. }
  33834. };
  33835. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33836. this._localDirection = newLocalDirection;
  33837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33838. this._updateDirection();
  33839. }
  33840. };
  33841. Sound.prototype._updateDirection = function () {
  33842. var mat = this._connectedMesh.getWorldMatrix();
  33843. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33844. direction.normalize();
  33845. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33846. };
  33847. Sound.prototype.updateDistanceFromListener = function () {
  33848. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33849. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33850. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33851. }
  33852. };
  33853. Sound.prototype.setAttenuationFunction = function (callback) {
  33854. this._customAttenuationFunction = callback;
  33855. };
  33856. /**
  33857. * Play the sound
  33858. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33859. */
  33860. Sound.prototype.play = function (time) {
  33861. var _this = this;
  33862. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33863. try {
  33864. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33865. if (!this._soundSource || !this._streamingSource) {
  33866. if (this.spatialSound) {
  33867. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33868. if (this._isDirectional) {
  33869. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33870. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33871. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33872. if (this._connectedMesh) {
  33873. this._updateDirection();
  33874. }
  33875. else {
  33876. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33877. }
  33878. }
  33879. }
  33880. }
  33881. if (this._streaming) {
  33882. if (!this._streamingSource) {
  33883. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33884. this._htmlAudioElement.onended = function () { _this._onended(); };
  33885. this._htmlAudioElement.playbackRate = this._playbackRate;
  33886. }
  33887. this._streamingSource.disconnect();
  33888. this._streamingSource.connect(this._inputAudioNode);
  33889. this._htmlAudioElement.play();
  33890. }
  33891. else {
  33892. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33893. this._soundSource.buffer = this._audioBuffer;
  33894. this._soundSource.connect(this._inputAudioNode);
  33895. this._soundSource.loop = this.loop;
  33896. this._soundSource.playbackRate.value = this._playbackRate;
  33897. this._soundSource.onended = function () { _this._onended(); };
  33898. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33899. }
  33900. this._startTime = startTime;
  33901. this.isPlaying = true;
  33902. this.isPaused = false;
  33903. }
  33904. catch (ex) {
  33905. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33906. }
  33907. }
  33908. };
  33909. Sound.prototype._onended = function () {
  33910. this.isPlaying = false;
  33911. if (this.onended) {
  33912. this.onended();
  33913. }
  33914. };
  33915. /**
  33916. * Stop the sound
  33917. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33918. */
  33919. Sound.prototype.stop = function (time) {
  33920. if (this.isPlaying) {
  33921. if (this._streaming) {
  33922. this._htmlAudioElement.pause();
  33923. // Test needed for Firefox or it will generate an Invalid State Error
  33924. if (this._htmlAudioElement.currentTime > 0) {
  33925. this._htmlAudioElement.currentTime = 0;
  33926. }
  33927. }
  33928. else {
  33929. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33930. this._soundSource.stop(stopTime);
  33931. }
  33932. this.isPlaying = false;
  33933. }
  33934. };
  33935. Sound.prototype.pause = function () {
  33936. if (this.isPlaying) {
  33937. if (this._streaming) {
  33938. this._htmlAudioElement.pause();
  33939. }
  33940. else {
  33941. this.stop(0);
  33942. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33943. }
  33944. this.isPaused = true;
  33945. }
  33946. };
  33947. Sound.prototype.setVolume = function (newVolume, time) {
  33948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33949. if (time) {
  33950. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33951. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33952. }
  33953. else {
  33954. this._soundGain.gain.value = newVolume;
  33955. }
  33956. }
  33957. this._volume = newVolume;
  33958. };
  33959. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33960. this._playbackRate = newPlaybackRate;
  33961. if (this.isPlaying) {
  33962. if (this._streaming) {
  33963. this._htmlAudioElement.playbackRate = this._playbackRate;
  33964. }
  33965. else {
  33966. this._soundSource.playbackRate.value = this._playbackRate;
  33967. }
  33968. }
  33969. };
  33970. Sound.prototype.getVolume = function () {
  33971. return this._volume;
  33972. };
  33973. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33974. var _this = this;
  33975. this._connectedMesh = meshToConnectTo;
  33976. if (!this.spatialSound) {
  33977. this.spatialSound = true;
  33978. this._createSpatialParameters();
  33979. if (this.isPlaying && this.loop) {
  33980. this.stop();
  33981. this.play();
  33982. }
  33983. }
  33984. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33985. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33986. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33987. };
  33988. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33989. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33990. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33991. this._updateDirection();
  33992. }
  33993. };
  33994. Sound.Parse = function (parsedSound, scene, rootUrl) {
  33995. var soundName = parsedSound.name;
  33996. var soundUrl = rootUrl + soundName;
  33997. var options = {
  33998. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33999. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34000. rolloffFactor: parsedSound.rolloffFactor,
  34001. refDistance: parsedSound.refDistance,
  34002. distanceModel: parsedSound.distanceModel,
  34003. playbackRate: parsedSound.playbackRate
  34004. };
  34005. var newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34006. scene._addPendingData(newSound);
  34007. if (parsedSound.position) {
  34008. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34009. newSound.setPosition(soundPosition);
  34010. }
  34011. if (parsedSound.isDirectional) {
  34012. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34013. if (parsedSound.localDirectionToMesh) {
  34014. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34015. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34016. }
  34017. }
  34018. if (parsedSound.connectedMeshId) {
  34019. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34020. if (connectedMesh) {
  34021. newSound.attachToMesh(connectedMesh);
  34022. }
  34023. }
  34024. return newSound;
  34025. };
  34026. return Sound;
  34027. })();
  34028. BABYLON.Sound = Sound;
  34029. })(BABYLON || (BABYLON = {}));
  34030. var BABYLON;
  34031. (function (BABYLON) {
  34032. var SoundTrack = (function () {
  34033. function SoundTrack(scene, options) {
  34034. this.id = -1;
  34035. this._isMainTrack = false;
  34036. this._isInitialized = false;
  34037. this._scene = scene;
  34038. this.soundCollection = new Array();
  34039. this._options = options;
  34040. if (!this._isMainTrack) {
  34041. this._scene.soundTracks.push(this);
  34042. this.id = this._scene.soundTracks.length - 1;
  34043. }
  34044. }
  34045. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34047. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34048. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34049. if (this._options) {
  34050. if (this._options.volume) {
  34051. this._outputAudioNode.gain.value = this._options.volume;
  34052. }
  34053. if (this._options.mainTrack) {
  34054. this._isMainTrack = this._options.mainTrack;
  34055. }
  34056. }
  34057. this._isInitialized = true;
  34058. }
  34059. };
  34060. SoundTrack.prototype.dispose = function () {
  34061. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34062. if (this._connectedAnalyser) {
  34063. this._connectedAnalyser.stopDebugCanvas();
  34064. }
  34065. while (this.soundCollection.length) {
  34066. this.soundCollection[0].dispose();
  34067. }
  34068. if (this._outputAudioNode) {
  34069. this._outputAudioNode.disconnect();
  34070. }
  34071. this._outputAudioNode = null;
  34072. }
  34073. };
  34074. SoundTrack.prototype.AddSound = function (sound) {
  34075. if (!this._isInitialized) {
  34076. this._initializeSoundTrackAudioGraph();
  34077. }
  34078. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34079. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34080. }
  34081. if (sound.soundTrackId) {
  34082. if (sound.soundTrackId === -1) {
  34083. this._scene.mainSoundTrack.RemoveSound(sound);
  34084. }
  34085. else {
  34086. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34087. }
  34088. }
  34089. this.soundCollection.push(sound);
  34090. sound.soundTrackId = this.id;
  34091. };
  34092. SoundTrack.prototype.RemoveSound = function (sound) {
  34093. var index = this.soundCollection.indexOf(sound);
  34094. if (index !== -1) {
  34095. this.soundCollection.splice(index, 1);
  34096. }
  34097. };
  34098. SoundTrack.prototype.setVolume = function (newVolume) {
  34099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34100. this._outputAudioNode.gain.value = newVolume;
  34101. }
  34102. };
  34103. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34105. for (var i = 0; i < this.soundCollection.length; i++) {
  34106. this.soundCollection[i].switchPanningModelToHRTF();
  34107. }
  34108. }
  34109. };
  34110. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34111. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34112. for (var i = 0; i < this.soundCollection.length; i++) {
  34113. this.soundCollection[i].switchPanningModelToEqualPower();
  34114. }
  34115. }
  34116. };
  34117. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34118. if (this._connectedAnalyser) {
  34119. this._connectedAnalyser.stopDebugCanvas();
  34120. }
  34121. this._connectedAnalyser = analyser;
  34122. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34123. this._outputAudioNode.disconnect();
  34124. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34125. }
  34126. };
  34127. return SoundTrack;
  34128. })();
  34129. BABYLON.SoundTrack = SoundTrack;
  34130. })(BABYLON || (BABYLON = {}));
  34131. var BABYLON;
  34132. (function (BABYLON) {
  34133. var DepthRenderer = (function () {
  34134. function DepthRenderer(scene, type) {
  34135. var _this = this;
  34136. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34137. this._viewMatrix = BABYLON.Matrix.Zero();
  34138. this._projectionMatrix = BABYLON.Matrix.Zero();
  34139. this._transformMatrix = BABYLON.Matrix.Zero();
  34140. this._worldViewProjection = BABYLON.Matrix.Zero();
  34141. this._scene = scene;
  34142. var engine = scene.getEngine();
  34143. // Render target
  34144. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34145. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34146. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34147. this._depthMap.refreshRate = 1;
  34148. this._depthMap.renderParticles = false;
  34149. this._depthMap.renderList = null;
  34150. // set default depth value to 1.0 (far away)
  34151. this._depthMap.onClear = function (engine) {
  34152. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34153. };
  34154. // Custom render function
  34155. var renderSubMesh = function (subMesh) {
  34156. var mesh = subMesh.getRenderingMesh();
  34157. var scene = _this._scene;
  34158. var engine = scene.getEngine();
  34159. // Culling
  34160. engine.setState(subMesh.getMaterial().backFaceCulling);
  34161. // Managing instances
  34162. var batch = mesh._getInstancesRenderList(subMesh._id);
  34163. if (batch.mustReturn) {
  34164. return;
  34165. }
  34166. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34167. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34168. engine.enableEffect(_this._effect);
  34169. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34170. var material = subMesh.getMaterial();
  34171. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34172. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34173. // Alpha test
  34174. if (material && material.needAlphaTesting()) {
  34175. var alphaTexture = material.getAlphaTestTexture();
  34176. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34177. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34178. }
  34179. // Bones
  34180. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34181. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34182. }
  34183. // Draw
  34184. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34185. }
  34186. };
  34187. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34188. var index;
  34189. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34190. renderSubMesh(opaqueSubMeshes.data[index]);
  34191. }
  34192. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34193. renderSubMesh(alphaTestSubMeshes.data[index]);
  34194. }
  34195. };
  34196. }
  34197. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34198. var defines = [];
  34199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34200. var mesh = subMesh.getMesh();
  34201. var scene = mesh.getScene();
  34202. var material = subMesh.getMaterial();
  34203. // Alpha test
  34204. if (material && material.needAlphaTesting()) {
  34205. defines.push("#define ALPHATEST");
  34206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34207. attribs.push(BABYLON.VertexBuffer.UVKind);
  34208. defines.push("#define UV1");
  34209. }
  34210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34212. defines.push("#define UV2");
  34213. }
  34214. }
  34215. // Bones
  34216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34219. if (mesh.numBoneInfluencers > 4) {
  34220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34222. }
  34223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34224. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34225. }
  34226. else {
  34227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34228. }
  34229. // Instances
  34230. if (useInstances) {
  34231. defines.push("#define INSTANCES");
  34232. attribs.push("world0");
  34233. attribs.push("world1");
  34234. attribs.push("world2");
  34235. attribs.push("world3");
  34236. }
  34237. // Get correct effect
  34238. var join = defines.join("\n");
  34239. if (this._cachedDefines !== join) {
  34240. this._cachedDefines = join;
  34241. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34242. }
  34243. return this._effect.isReady();
  34244. };
  34245. DepthRenderer.prototype.getDepthMap = function () {
  34246. return this._depthMap;
  34247. };
  34248. // Methods
  34249. DepthRenderer.prototype.dispose = function () {
  34250. this._depthMap.dispose();
  34251. };
  34252. return DepthRenderer;
  34253. })();
  34254. BABYLON.DepthRenderer = DepthRenderer;
  34255. })(BABYLON || (BABYLON = {}));
  34256. var BABYLON;
  34257. (function (BABYLON) {
  34258. var SSAORenderingPipeline = (function (_super) {
  34259. __extends(SSAORenderingPipeline, _super);
  34260. /**
  34261. * @constructor
  34262. * @param {string} name - The rendering pipeline name
  34263. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34264. * @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 }
  34265. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34266. */
  34267. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34268. var _this = this;
  34269. _super.call(this, scene.getEngine(), name);
  34270. // Members
  34271. /**
  34272. * The PassPostProcess id in the pipeline that contains the original scene color
  34273. * @type {string}
  34274. */
  34275. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34276. /**
  34277. * The SSAO PostProcess id in the pipeline
  34278. * @type {string}
  34279. */
  34280. this.SSAORenderEffect = "SSAORenderEffect";
  34281. /**
  34282. * The horizontal blur PostProcess id in the pipeline
  34283. * @type {string}
  34284. */
  34285. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34286. /**
  34287. * The vertical blur PostProcess id in the pipeline
  34288. * @type {string}
  34289. */
  34290. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34291. /**
  34292. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34293. * @type {string}
  34294. */
  34295. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34296. /**
  34297. * The output strength of the SSAO post-process. Default value is 1.0.
  34298. * @type {number}
  34299. */
  34300. this.totalStrength = 1.0;
  34301. /**
  34302. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34303. * @type {number}
  34304. */
  34305. this.radius = 0.0001;
  34306. /**
  34307. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34308. * Must not be equal to fallOff and superior to fallOff.
  34309. * Default value is 0.975
  34310. * @type {number}
  34311. */
  34312. this.area = 0.0075;
  34313. /**
  34314. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34315. * Must not be equal to area and inferior to area.
  34316. * Default value is 0.0
  34317. * @type {number}
  34318. */
  34319. this.fallOff = 0.000001;
  34320. /**
  34321. * The base color of the SSAO post-process
  34322. * The final result is "base + ssao" between [0, 1]
  34323. * @type {number}
  34324. */
  34325. this.base = 0.5;
  34326. this._firstUpdate = true;
  34327. this._scene = scene;
  34328. // Set up assets
  34329. this._createRandomTexture();
  34330. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34331. var ssaoRatio = ratio.ssaoRatio || ratio;
  34332. var combineRatio = ratio.combineRatio || ratio;
  34333. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34334. this._createSSAOPostProcess(ssaoRatio);
  34335. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34336. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34337. this._createSSAOCombinePostProcess(combineRatio);
  34338. // Set up pipeline
  34339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34344. // Finish
  34345. scene.postProcessRenderPipelineManager.addPipeline(this);
  34346. if (cameras)
  34347. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34348. }
  34349. // Public Methods
  34350. /**
  34351. * Returns the horizontal blur PostProcess
  34352. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34353. */
  34354. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34355. return this._blurHPostProcess;
  34356. };
  34357. /**
  34358. * Returns the vertical blur PostProcess
  34359. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34360. */
  34361. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34362. return this._blurVPostProcess;
  34363. };
  34364. /**
  34365. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34366. */
  34367. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34368. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34369. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34370. this._originalColorPostProcess = undefined;
  34371. this._ssaoPostProcess = undefined;
  34372. this._blurHPostProcess = undefined;
  34373. this._blurVPostProcess = undefined;
  34374. this._ssaoCombinePostProcess = undefined;
  34375. this._randomTexture.dispose();
  34376. if (disableDepthRender)
  34377. this._scene.disableDepthRenderer();
  34378. };
  34379. // Private Methods
  34380. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34381. var _this = this;
  34382. var numSamples = 16;
  34383. var sampleSphere = [
  34384. 0.5381, 0.1856, -0.4319,
  34385. 0.1379, 0.2486, 0.4430,
  34386. 0.3371, 0.5679, -0.0057,
  34387. -0.6999, -0.0451, -0.0019,
  34388. 0.0689, -0.1598, -0.8547,
  34389. 0.0560, 0.0069, -0.1843,
  34390. -0.0146, 0.1402, 0.0762,
  34391. 0.0100, -0.1924, -0.0344,
  34392. -0.3577, -0.5301, -0.4358,
  34393. -0.3169, 0.1063, 0.0158,
  34394. 0.0103, -0.5869, 0.0046,
  34395. -0.0897, -0.4940, 0.3287,
  34396. 0.7119, -0.0154, -0.0918,
  34397. -0.0533, 0.0596, -0.5411,
  34398. 0.0352, -0.0631, 0.5460,
  34399. -0.4776, 0.2847, -0.0271
  34400. ];
  34401. var samplesFactor = 1.0 / numSamples;
  34402. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34403. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34404. "area", "fallOff", "base"
  34405. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34406. this._ssaoPostProcess.onApply = function (effect) {
  34407. if (_this._firstUpdate) {
  34408. effect.setArray3("sampleSphere", sampleSphere);
  34409. effect.setFloat("samplesFactor", samplesFactor);
  34410. effect.setFloat("randTextureTiles", 4.0);
  34411. _this._firstUpdate = false;
  34412. }
  34413. effect.setFloat("totalStrength", _this.totalStrength);
  34414. effect.setFloat("radius", _this.radius);
  34415. effect.setFloat("area", _this.area);
  34416. effect.setFloat("fallOff", _this.fallOff);
  34417. effect.setFloat("base", _this.base);
  34418. effect.setTexture("textureSampler", _this._depthTexture);
  34419. effect.setTexture("randomSampler", _this._randomTexture);
  34420. };
  34421. };
  34422. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34423. var _this = this;
  34424. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34425. this._ssaoCombinePostProcess.onApply = function (effect) {
  34426. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34427. };
  34428. };
  34429. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34430. var size = 512;
  34431. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34432. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34433. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34434. var context = this._randomTexture.getContext();
  34435. var rand = function (min, max) {
  34436. return Math.random() * (max - min) + min;
  34437. };
  34438. var randVector = BABYLON.Vector3.Zero();
  34439. for (var x = 0; x < size; x++) {
  34440. for (var y = 0; y < size; y++) {
  34441. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34442. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34443. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34444. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34445. context.fillRect(x, y, 1, 1);
  34446. }
  34447. }
  34448. this._randomTexture.update(false);
  34449. };
  34450. return SSAORenderingPipeline;
  34451. })(BABYLON.PostProcessRenderPipeline);
  34452. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34453. })(BABYLON || (BABYLON = {}));
  34454. var BABYLON;
  34455. (function (BABYLON) {
  34456. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34457. var VolumetricLightScatteringPostProcess = (function (_super) {
  34458. __extends(VolumetricLightScatteringPostProcess, _super);
  34459. /**
  34460. * @constructor
  34461. * @param {string} name - The post-process name
  34462. * @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)
  34463. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34464. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34465. * @param {number} samples - The post-process quality, default 100
  34466. * @param {number} samplingMode - The post-process filtering mode
  34467. * @param {BABYLON.Engine} engine - The babylon engine
  34468. * @param {boolean} reusable - If the post-process is reusable
  34469. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34470. */
  34471. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34472. var _this = this;
  34473. if (samples === void 0) { samples = 100; }
  34474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34475. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34476. this._screenCoordinates = BABYLON.Vector2.Zero();
  34477. /**
  34478. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34479. * @type {boolean}
  34480. */
  34481. this.useCustomMeshPosition = false;
  34482. /**
  34483. * If the post-process should inverse the light scattering direction
  34484. * @type {boolean}
  34485. */
  34486. this.invert = true;
  34487. /**
  34488. * Set to true to use the diffuseColor instead of the diffuseTexture
  34489. * @type {boolean}
  34490. */
  34491. this.useDiffuseColor = false;
  34492. /**
  34493. * Array containing the excluded meshes not rendered in the internal pass
  34494. */
  34495. this.excludedMeshes = new Array();
  34496. /**
  34497. * Controls the overall intensity of the post-process
  34498. * @type {number}
  34499. */
  34500. this.exposure = 0.3;
  34501. /**
  34502. * Dissipates each sample's contribution in range [0, 1]
  34503. * @type {number}
  34504. */
  34505. this.decay = 0.96815;
  34506. /**
  34507. * Controls the overall intensity of each sample
  34508. * @type {number}
  34509. */
  34510. this.weight = 0.58767;
  34511. /**
  34512. * Controls the density of each sample
  34513. * @type {number}
  34514. */
  34515. this.density = 0.926;
  34516. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34517. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34518. // Configure mesh
  34519. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34520. // Configure
  34521. this._createPass(scene, ratio.passRatio || ratio);
  34522. this.onActivate = function (camera) {
  34523. if (!_this.isSupported) {
  34524. _this.dispose(camera);
  34525. }
  34526. _this.onActivate = null;
  34527. };
  34528. this.onApply = function (effect) {
  34529. _this._updateMeshScreenCoordinates(scene);
  34530. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34531. effect.setFloat("exposure", _this.exposure);
  34532. effect.setFloat("decay", _this.decay);
  34533. effect.setFloat("weight", _this.weight);
  34534. effect.setFloat("density", _this.density);
  34535. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34536. };
  34537. }
  34538. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34539. var mesh = subMesh.getMesh();
  34540. var defines = [];
  34541. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34542. var material = subMesh.getMaterial();
  34543. var needUV = false;
  34544. // Render this.mesh as default
  34545. if (mesh === this.mesh) {
  34546. if (this.useDiffuseColor) {
  34547. defines.push("#define DIFFUSE_COLOR_RENDER");
  34548. }
  34549. else if (material) {
  34550. if (material.diffuseTexture !== undefined) {
  34551. defines.push("#define BASIC_RENDER");
  34552. }
  34553. else {
  34554. defines.push("#define DIFFUSE_COLOR_RENDER");
  34555. }
  34556. }
  34557. defines.push("#define NEED_UV");
  34558. needUV = true;
  34559. }
  34560. // Alpha test
  34561. if (material) {
  34562. if (material.needAlphaTesting()) {
  34563. defines.push("#define ALPHATEST");
  34564. }
  34565. if (material.opacityTexture !== undefined) {
  34566. defines.push("#define OPACITY");
  34567. if (material.opacityTexture.getAlphaFromRGB) {
  34568. defines.push("#define OPACITYRGB");
  34569. }
  34570. if (!needUV) {
  34571. defines.push("#define NEED_UV");
  34572. }
  34573. }
  34574. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34575. attribs.push(BABYLON.VertexBuffer.UVKind);
  34576. defines.push("#define UV1");
  34577. }
  34578. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34579. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34580. defines.push("#define UV2");
  34581. }
  34582. }
  34583. // Bones
  34584. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34585. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34586. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34587. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34588. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34589. }
  34590. else {
  34591. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34592. }
  34593. // Instances
  34594. if (useInstances) {
  34595. defines.push("#define INSTANCES");
  34596. attribs.push("world0");
  34597. attribs.push("world1");
  34598. attribs.push("world2");
  34599. attribs.push("world3");
  34600. }
  34601. // Get correct effect
  34602. var join = defines.join("\n");
  34603. if (this._cachedDefines !== join) {
  34604. this._cachedDefines = join;
  34605. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34606. }
  34607. return this._volumetricLightScatteringPass.isReady();
  34608. };
  34609. /**
  34610. * Sets the new light position for light scattering effect
  34611. * @param {BABYLON.Vector3} The new custom light position
  34612. */
  34613. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34614. this._customMeshPosition = position;
  34615. };
  34616. /**
  34617. * Returns the light position for light scattering effect
  34618. * @return {BABYLON.Vector3} The custom light position
  34619. */
  34620. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34621. return this._customMeshPosition;
  34622. };
  34623. /**
  34624. * Disposes the internal assets and detaches the post-process from the camera
  34625. */
  34626. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34627. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34628. if (rttIndex !== -1) {
  34629. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34630. }
  34631. this._volumetricLightScatteringRTT.dispose();
  34632. _super.prototype.dispose.call(this, camera);
  34633. };
  34634. /**
  34635. * Returns the render target texture used by the post-process
  34636. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34637. */
  34638. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34639. return this._volumetricLightScatteringRTT;
  34640. };
  34641. // Private methods
  34642. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34643. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34644. return true;
  34645. }
  34646. return false;
  34647. };
  34648. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34649. var _this = this;
  34650. var engine = scene.getEngine();
  34651. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34652. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34653. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34654. this._volumetricLightScatteringRTT.renderList = null;
  34655. this._volumetricLightScatteringRTT.renderParticles = false;
  34656. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34657. // Custom render function for submeshes
  34658. var renderSubMesh = function (subMesh) {
  34659. var mesh = subMesh.getRenderingMesh();
  34660. if (_this._meshExcluded(mesh)) {
  34661. return;
  34662. }
  34663. var scene = mesh.getScene();
  34664. var engine = scene.getEngine();
  34665. // Culling
  34666. engine.setState(subMesh.getMaterial().backFaceCulling);
  34667. // Managing instances
  34668. var batch = mesh._getInstancesRenderList(subMesh._id);
  34669. if (batch.mustReturn) {
  34670. return;
  34671. }
  34672. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34673. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34674. engine.enableEffect(_this._volumetricLightScatteringPass);
  34675. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34676. var material = subMesh.getMaterial();
  34677. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34678. // Alpha test
  34679. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34680. var alphaTexture = material.getAlphaTestTexture();
  34681. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34682. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34683. }
  34684. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34685. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34686. if (alphaTexture) {
  34687. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34688. }
  34689. }
  34690. if (material.opacityTexture !== undefined) {
  34691. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34692. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34693. }
  34694. }
  34695. // Bones
  34696. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34697. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34698. }
  34699. // Draw
  34700. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34701. }
  34702. };
  34703. // Render target texture callbacks
  34704. var savedSceneClearColor;
  34705. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34706. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34707. savedSceneClearColor = scene.clearColor;
  34708. scene.clearColor = sceneClearColor;
  34709. };
  34710. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34711. scene.clearColor = savedSceneClearColor;
  34712. };
  34713. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34714. var engine = scene.getEngine();
  34715. var index;
  34716. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34717. renderSubMesh(opaqueSubMeshes.data[index]);
  34718. }
  34719. engine.setAlphaTesting(true);
  34720. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34721. renderSubMesh(alphaTestSubMeshes.data[index]);
  34722. }
  34723. engine.setAlphaTesting(false);
  34724. if (transparentSubMeshes.length) {
  34725. // Sort sub meshes
  34726. for (index = 0; index < transparentSubMeshes.length; index++) {
  34727. var submesh = transparentSubMeshes.data[index];
  34728. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34729. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34730. }
  34731. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34732. sortedArray.sort(function (a, b) {
  34733. // Alpha index first
  34734. if (a._alphaIndex > b._alphaIndex) {
  34735. return 1;
  34736. }
  34737. if (a._alphaIndex < b._alphaIndex) {
  34738. return -1;
  34739. }
  34740. // Then distance to camera
  34741. if (a._distanceToCamera < b._distanceToCamera) {
  34742. return 1;
  34743. }
  34744. if (a._distanceToCamera > b._distanceToCamera) {
  34745. return -1;
  34746. }
  34747. return 0;
  34748. });
  34749. // Render sub meshes
  34750. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34751. for (index = 0; index < sortedArray.length; index++) {
  34752. renderSubMesh(sortedArray[index]);
  34753. }
  34754. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34755. }
  34756. };
  34757. };
  34758. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34759. var transform = scene.getTransformMatrix();
  34760. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34761. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34762. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34763. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34764. if (this.invert)
  34765. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34766. };
  34767. // Static methods
  34768. /**
  34769. * Creates a default mesh for the Volumeric Light Scattering post-process
  34770. * @param {string} The mesh name
  34771. * @param {BABYLON.Scene} The scene where to create the mesh
  34772. * @return {BABYLON.Mesh} the default mesh
  34773. */
  34774. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34775. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34776. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34777. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34778. return mesh;
  34779. };
  34780. return VolumetricLightScatteringPostProcess;
  34781. })(BABYLON.PostProcess);
  34782. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34783. })(BABYLON || (BABYLON = {}));
  34784. // BABYLON.JS Chromatic Aberration GLSL Shader
  34785. // Author: Olivier Guyot
  34786. // Separates very slightly R, G and B colors on the edges of the screen
  34787. // Inspired by Francois Tarlier & Martins Upitis
  34788. var BABYLON;
  34789. (function (BABYLON) {
  34790. var LensRenderingPipeline = (function (_super) {
  34791. __extends(LensRenderingPipeline, _super);
  34792. /**
  34793. * @constructor
  34794. *
  34795. * Effect parameters are as follow:
  34796. * {
  34797. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34798. * edge_blur: number; // from 0 to x (1 for realism)
  34799. * distortion: number; // from 0 to x (1 for realism)
  34800. * grain_amount: number; // from 0 to 1
  34801. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34802. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34803. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34804. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34805. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34806. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34807. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34808. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34809. * }
  34810. * Note: if an effect parameter is unset, effect is disabled
  34811. *
  34812. * @param {string} name - The rendering pipeline name
  34813. * @param {object} parameters - An object containing all parameters (see above)
  34814. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34815. * @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)
  34816. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34817. */
  34818. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34819. var _this = this;
  34820. if (ratio === void 0) { ratio = 1.0; }
  34821. _super.call(this, scene.getEngine(), name);
  34822. // Lens effects can be of the following:
  34823. // - chromatic aberration (slight shift of RGB colors)
  34824. // - blur on the edge of the lens
  34825. // - lens distortion
  34826. // - depth-of-field blur & highlights enhancing
  34827. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34828. // - grain effect (noise or custom texture)
  34829. // Two additional texture samplers are needed:
  34830. // - depth map (for depth-of-field)
  34831. // - grain texture
  34832. /**
  34833. * The chromatic aberration PostProcess id in the pipeline
  34834. * @type {string}
  34835. */
  34836. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34837. /**
  34838. * The highlights enhancing PostProcess id in the pipeline
  34839. * @type {string}
  34840. */
  34841. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34842. /**
  34843. * The depth-of-field PostProcess id in the pipeline
  34844. * @type {string}
  34845. */
  34846. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34847. this._scene = scene;
  34848. // Fetch texture samplers
  34849. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34850. if (parameters.grain_texture) {
  34851. this._grainTexture = parameters.grain_texture;
  34852. }
  34853. else {
  34854. this._createGrainTexture();
  34855. }
  34856. // save parameters
  34857. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34858. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34859. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34860. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34861. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34862. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34863. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34864. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34865. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34866. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34867. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34868. // Create effects
  34869. this._createChromaticAberrationPostProcess(ratio);
  34870. this._createHighlightsPostProcess(ratio);
  34871. this._createDepthOfFieldPostProcess(ratio / 4);
  34872. // Set up pipeline
  34873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34876. if (this._highlightsGain === -1) {
  34877. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34878. }
  34879. // Finish
  34880. scene.postProcessRenderPipelineManager.addPipeline(this);
  34881. if (cameras) {
  34882. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34883. }
  34884. }
  34885. // public methods (self explanatory)
  34886. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34887. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34888. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34889. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34890. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34891. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34892. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34893. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34894. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34895. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34896. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34897. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34898. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34899. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34900. };
  34901. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34902. this._highlightsPostProcess.updateEffect();
  34903. };
  34904. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34905. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34906. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34907. this._highlightsGain = amount;
  34908. };
  34909. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34910. if (this._highlightsGain === -1) {
  34911. this._highlightsGain = 1.0;
  34912. }
  34913. this._highlightsThreshold = amount;
  34914. };
  34915. LensRenderingPipeline.prototype.disableHighlights = function () {
  34916. this._highlightsGain = -1;
  34917. };
  34918. /**
  34919. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34920. */
  34921. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34922. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34923. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34924. this._chromaticAberrationPostProcess = undefined;
  34925. this._highlightsPostProcess = undefined;
  34926. this._depthOfFieldPostProcess = undefined;
  34927. this._grainTexture.dispose();
  34928. if (disableDepthRender)
  34929. this._scene.disableDepthRenderer();
  34930. };
  34931. // colors shifting and distortion
  34932. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34933. var _this = this;
  34934. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34935. [], // samplers
  34936. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34937. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34938. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34939. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34940. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34941. };
  34942. };
  34943. // highlights enhancing
  34944. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34945. var _this = this;
  34946. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34947. [], // samplers
  34948. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34949. this._highlightsPostProcess.onApply = function (effect) {
  34950. effect.setFloat('gain', _this._highlightsGain);
  34951. effect.setFloat('threshold', _this._highlightsThreshold);
  34952. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34953. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34954. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34955. };
  34956. };
  34957. // colors shifting and distortion
  34958. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34959. var _this = this;
  34960. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34961. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34962. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34963. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34964. this._depthOfFieldPostProcess.onApply = function (effect) {
  34965. effect.setTexture("depthSampler", _this._depthTexture);
  34966. effect.setTexture("grainSampler", _this._grainTexture);
  34967. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34968. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34969. effect.setFloat('grain_amount', _this._grainAmount);
  34970. effect.setBool('blur_noise', _this._blurNoise);
  34971. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34972. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34973. effect.setFloat('distortion', _this._distortion);
  34974. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34975. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34976. effect.setFloat('aperture', _this._dofAperture);
  34977. effect.setFloat('darken', _this._dofDarken);
  34978. effect.setFloat('edge_blur', _this._edgeBlur);
  34979. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34980. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34981. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34982. };
  34983. };
  34984. // creates a black and white random noise texture, 512x512
  34985. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34986. var size = 512;
  34987. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34988. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34989. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34990. var context = this._grainTexture.getContext();
  34991. var rand = function (min, max) {
  34992. return Math.random() * (max - min) + min;
  34993. };
  34994. var value;
  34995. for (var x = 0; x < size; x++) {
  34996. for (var y = 0; y < size; y++) {
  34997. value = Math.floor(rand(0.42, 0.58) * 255);
  34998. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34999. context.fillRect(x, y, 1, 1);
  35000. }
  35001. }
  35002. this._grainTexture.update(false);
  35003. };
  35004. return LensRenderingPipeline;
  35005. })(BABYLON.PostProcessRenderPipeline);
  35006. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35007. })(BABYLON || (BABYLON = {}));
  35008. //
  35009. // This post-process allows the modification of rendered colors by using
  35010. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35011. //
  35012. // The object needs to be provided an url to a texture containing the color
  35013. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35014. // Use an image editing software to tweak the LUT to match your needs.
  35015. //
  35016. // For an example of a color LUT, see here:
  35017. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35018. // For explanations on color grading, see here:
  35019. // http://udn.epicgames.com/Three/ColorGrading.html
  35020. //
  35021. var BABYLON;
  35022. (function (BABYLON) {
  35023. var ColorCorrectionPostProcess = (function (_super) {
  35024. __extends(ColorCorrectionPostProcess, _super);
  35025. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35026. var _this = this;
  35027. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35028. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35029. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35030. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35031. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35032. this.onApply = function (effect) {
  35033. effect.setTexture("colorTable", _this._colorTableTexture);
  35034. };
  35035. }
  35036. return ColorCorrectionPostProcess;
  35037. })(BABYLON.PostProcess);
  35038. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35039. })(BABYLON || (BABYLON = {}));
  35040. var BABYLON;
  35041. (function (BABYLON) {
  35042. var AnaglyphFreeCamera = (function (_super) {
  35043. __extends(AnaglyphFreeCamera, _super);
  35044. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35045. _super.call(this, name, position, scene);
  35046. this.interaxialDistance = interaxialDistance;
  35047. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35048. }
  35049. return AnaglyphFreeCamera;
  35050. })(BABYLON.FreeCamera);
  35051. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35052. var AnaglyphArcRotateCamera = (function (_super) {
  35053. __extends(AnaglyphArcRotateCamera, _super);
  35054. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35055. _super.call(this, name, alpha, beta, radius, target, scene);
  35056. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35057. }
  35058. return AnaglyphArcRotateCamera;
  35059. })(BABYLON.ArcRotateCamera);
  35060. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35061. var AnaglyphGamepadCamera = (function (_super) {
  35062. __extends(AnaglyphGamepadCamera, _super);
  35063. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35064. _super.call(this, name, position, scene);
  35065. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35066. }
  35067. return AnaglyphGamepadCamera;
  35068. })(BABYLON.GamepadCamera);
  35069. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35070. var StereoscopicFreeCamera = (function (_super) {
  35071. __extends(StereoscopicFreeCamera, _super);
  35072. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35073. _super.call(this, name, position, scene);
  35074. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35075. }
  35076. return StereoscopicFreeCamera;
  35077. })(BABYLON.FreeCamera);
  35078. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35079. var StereoscopicArcRotateCamera = (function (_super) {
  35080. __extends(StereoscopicArcRotateCamera, _super);
  35081. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35082. _super.call(this, name, alpha, beta, radius, target, scene);
  35083. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35084. }
  35085. return StereoscopicArcRotateCamera;
  35086. })(BABYLON.ArcRotateCamera);
  35087. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35088. var StereoscopicGamepadCamera = (function (_super) {
  35089. __extends(StereoscopicGamepadCamera, _super);
  35090. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35091. _super.call(this, name, position, scene);
  35092. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35093. }
  35094. return StereoscopicGamepadCamera;
  35095. })(BABYLON.GamepadCamera);
  35096. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35097. })(BABYLON || (BABYLON = {}));
  35098. var BABYLON;
  35099. (function (BABYLON) {
  35100. var HDRRenderingPipeline = (function (_super) {
  35101. __extends(HDRRenderingPipeline, _super);
  35102. /**
  35103. * @constructor
  35104. * @param {string} name - The rendering pipeline name
  35105. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35106. * @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)
  35107. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35108. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35109. */
  35110. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35111. var _this = this;
  35112. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35113. _super.call(this, scene.getEngine(), name);
  35114. /**
  35115. * Public members
  35116. */
  35117. // Gaussian Blur
  35118. /**
  35119. * Gaussian blur coefficient
  35120. * @type {number}
  35121. */
  35122. this.gaussCoeff = 0.3;
  35123. /**
  35124. * Gaussian blur mean
  35125. * @type {number}
  35126. */
  35127. this.gaussMean = 1.0;
  35128. /**
  35129. * Gaussian blur standard deviation
  35130. * @type {number}
  35131. */
  35132. this.gaussStandDev = 0.8;
  35133. /**
  35134. * Gaussian blur multiplier. Multiplies the blur effect
  35135. * @type {number}
  35136. */
  35137. this.gaussMultiplier = 4.0;
  35138. // HDR
  35139. /**
  35140. * Exposure, controls the overall intensity of the pipeline
  35141. * @type {number}
  35142. */
  35143. this.exposure = 1.0;
  35144. /**
  35145. * Minimum luminance that the post-process can output. Luminance is >= 0
  35146. * @type {number}
  35147. */
  35148. this.minimumLuminance = 1.0;
  35149. /**
  35150. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35151. * @type {number}
  35152. */
  35153. this.maximumLuminance = 1e20;
  35154. /**
  35155. * Increase rate for luminance: eye adaptation speed to dark
  35156. * @type {number}
  35157. */
  35158. this.luminanceIncreaserate = 0.5;
  35159. /**
  35160. * Decrease rate for luminance: eye adaptation speed to bright
  35161. * @type {number}
  35162. */
  35163. this.luminanceDecreaseRate = 0.5;
  35164. // Bright pass
  35165. /**
  35166. * Minimum luminance needed to compute HDR
  35167. * @type {number}
  35168. */
  35169. this.brightThreshold = 0.8;
  35170. this._needUpdate = true;
  35171. this._scene = scene;
  35172. // Bright pass
  35173. this._createBrightPassPostProcess(scene, ratio);
  35174. // Down sample X4
  35175. this._createDownSampleX4PostProcess(scene, ratio);
  35176. // Create gaussian blur post-processes
  35177. this._createGaussianBlurPostProcess(scene, ratio);
  35178. // Texture adder
  35179. this._createTextureAdderPostProcess(scene, ratio);
  35180. // Luminance generator
  35181. this._createLuminanceGeneratorPostProcess(scene);
  35182. // HDR
  35183. this._createHDRPostProcess(scene, ratio);
  35184. // Pass postprocess
  35185. if (originalPostProcess === null) {
  35186. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35187. }
  35188. else {
  35189. this._originalPostProcess = originalPostProcess;
  35190. }
  35191. // Configure pipeline
  35192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35193. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35198. var addDownSamplerPostProcess = function (id) {
  35199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35200. };
  35201. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35202. addDownSamplerPostProcess(i);
  35203. }
  35204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35205. // Finish
  35206. scene.postProcessRenderPipelineManager.addPipeline(this);
  35207. if (cameras !== null) {
  35208. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35209. }
  35210. this.update();
  35211. }
  35212. /**
  35213. * Tells the pipeline to update its post-processes
  35214. */
  35215. HDRRenderingPipeline.prototype.update = function () {
  35216. this._needUpdate = true;
  35217. };
  35218. /**
  35219. * Returns the current calculated luminance
  35220. */
  35221. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35222. return this._hdrCurrentLuminance;
  35223. };
  35224. /**
  35225. * Returns the currently drawn luminance
  35226. */
  35227. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35228. return this._hdrOutputLuminance;
  35229. };
  35230. /**
  35231. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35232. */
  35233. HDRRenderingPipeline.prototype.dispose = function () {
  35234. this._originalPostProcess = undefined;
  35235. this._brightPassPostProcess = undefined;
  35236. this._downSampleX4PostProcess = undefined;
  35237. this._guassianBlurHPostProcess = undefined;
  35238. this._guassianBlurVPostProcess = undefined;
  35239. this._textureAdderPostProcess = undefined;
  35240. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35241. this._downSamplePostProcesses[i] = undefined;
  35242. }
  35243. this._hdrPostProcess = undefined;
  35244. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35245. };
  35246. /**
  35247. * Creates the HDR post-process and computes the luminance adaptation
  35248. */
  35249. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35250. var _this = this;
  35251. var hdrLastLuminance = 0.0;
  35252. this._hdrOutputLuminance = -1.0;
  35253. this._hdrCurrentLuminance = 1.0;
  35254. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35255. this._hdrPostProcess.onApply = function (effect) {
  35256. if (_this._hdrOutputLuminance < 0.0) {
  35257. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35258. }
  35259. else {
  35260. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35261. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35262. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35263. }
  35264. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35265. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35266. }
  35267. else {
  35268. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35269. }
  35270. }
  35271. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35272. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35273. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35274. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35275. effect.setFloat("exposure", _this.exposure);
  35276. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35277. _this._needUpdate = false;
  35278. };
  35279. };
  35280. /**
  35281. * Texture Adder post-process
  35282. */
  35283. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35284. var _this = this;
  35285. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35286. this._textureAdderPostProcess.onApply = function (effect) {
  35287. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35288. };
  35289. };
  35290. /**
  35291. * Down sample X4 post-process
  35292. */
  35293. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35294. var _this = this;
  35295. var downSampleX4Offsets = new Array(32);
  35296. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35297. this._downSampleX4PostProcess.onApply = function (effect) {
  35298. if (_this._needUpdate) {
  35299. var id = 0;
  35300. for (var i = -2; i < 2; i++) {
  35301. for (var j = -2; j < 2; j++) {
  35302. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35303. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35304. id += 2;
  35305. }
  35306. }
  35307. }
  35308. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35309. };
  35310. };
  35311. /**
  35312. * Bright pass post-process
  35313. */
  35314. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35315. var _this = this;
  35316. var brightOffsets = new Array(8);
  35317. var brightPassCallback = function (effect) {
  35318. if (_this._needUpdate) {
  35319. var sU = (1.0 / _this._brightPassPostProcess.width);
  35320. var sV = (1.0 / _this._brightPassPostProcess.height);
  35321. brightOffsets[0] = -0.5 * sU;
  35322. brightOffsets[1] = 0.5 * sV;
  35323. brightOffsets[2] = 0.5 * sU;
  35324. brightOffsets[3] = 0.5 * sV;
  35325. brightOffsets[4] = -0.5 * sU;
  35326. brightOffsets[5] = -0.5 * sV;
  35327. brightOffsets[6] = 0.5 * sU;
  35328. brightOffsets[7] = -0.5 * sV;
  35329. }
  35330. effect.setArray2("dsOffsets", brightOffsets);
  35331. effect.setFloat("brightThreshold", _this.brightThreshold);
  35332. };
  35333. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35334. this._brightPassPostProcess.onApply = brightPassCallback;
  35335. };
  35336. /**
  35337. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35338. */
  35339. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35340. var _this = this;
  35341. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35342. var luminanceOffsets = new Array(8);
  35343. var downSampleOffsets = new Array(18);
  35344. var halfDestPixelSize;
  35345. this._downSamplePostProcesses = new Array(lumSteps);
  35346. // Utils for luminance
  35347. var luminanceUpdateSourceOffsets = function (width, height) {
  35348. var sU = (1.0 / width);
  35349. var sV = (1.0 / height);
  35350. luminanceOffsets[0] = -0.5 * sU;
  35351. luminanceOffsets[1] = 0.5 * sV;
  35352. luminanceOffsets[2] = 0.5 * sU;
  35353. luminanceOffsets[3] = 0.5 * sV;
  35354. luminanceOffsets[4] = -0.5 * sU;
  35355. luminanceOffsets[5] = -0.5 * sV;
  35356. luminanceOffsets[6] = 0.5 * sU;
  35357. luminanceOffsets[7] = -0.5 * sV;
  35358. };
  35359. var luminanceUpdateDestOffsets = function (width, height) {
  35360. var id = 0;
  35361. for (var x = -1; x < 2; x++) {
  35362. for (var y = -1; y < 2; y++) {
  35363. downSampleOffsets[id] = (x) / width;
  35364. downSampleOffsets[id + 1] = (y) / height;
  35365. id += 2;
  35366. }
  35367. }
  35368. };
  35369. // Luminance callback
  35370. var luminanceCallback = function (effect) {
  35371. if (_this._needUpdate) {
  35372. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35373. }
  35374. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35375. effect.setArray2("lumOffsets", luminanceOffsets);
  35376. };
  35377. // Down sample callbacks
  35378. var downSampleCallback = function (indice) {
  35379. var i = indice;
  35380. return function (effect) {
  35381. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35382. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35383. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35384. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35385. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35386. effect.setArray2("dsOffsets", downSampleOffsets);
  35387. };
  35388. };
  35389. var downSampleAfterRenderCallback = function (effect) {
  35390. // Unpack result
  35391. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35392. 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);
  35393. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35394. };
  35395. // Create luminance post-process
  35396. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35397. 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);
  35398. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35399. // Create down sample post-processes
  35400. for (var i = lumSteps - 2; i >= 0; i--) {
  35401. var length = Math.pow(3, i);
  35402. ratio = { width: length, height: length };
  35403. var defines = "#define DOWN_SAMPLE\n";
  35404. if (i === 0) {
  35405. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35406. }
  35407. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35408. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35409. if (i === 0) {
  35410. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35411. }
  35412. }
  35413. };
  35414. /**
  35415. * Gaussian blur post-processes. Horizontal and Vertical
  35416. */
  35417. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35418. var _this = this;
  35419. var blurOffsetsW = new Array(9);
  35420. var blurOffsetsH = new Array(9);
  35421. var blurWeights = new Array(9);
  35422. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35423. // Utils for gaussian blur
  35424. var calculateBlurOffsets = function (height) {
  35425. var lastOutputDimensions = {
  35426. width: scene.getEngine().getRenderWidth(),
  35427. height: scene.getEngine().getRenderHeight()
  35428. };
  35429. for (var i = 0; i < 9; i++) {
  35430. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35431. if (height) {
  35432. blurOffsetsH[i] = value;
  35433. }
  35434. else {
  35435. blurOffsetsW[i] = value;
  35436. }
  35437. }
  35438. };
  35439. var calculateWeights = function () {
  35440. var x = 0.0;
  35441. for (var i = 0; i < 9; i++) {
  35442. x = (i - 4.0) / 4.0;
  35443. 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));
  35444. }
  35445. };
  35446. // Callback
  35447. var gaussianBlurCallback = function (height) {
  35448. return function (effect) {
  35449. if (_this._needUpdate) {
  35450. calculateWeights();
  35451. calculateBlurOffsets(height);
  35452. }
  35453. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35454. effect.setArray("blurWeights", blurWeights);
  35455. effect.setFloat("multiplier", _this.gaussMultiplier);
  35456. };
  35457. };
  35458. // Create horizontal gaussian blur post-processes
  35459. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35460. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35461. // Create vertical gaussian blur post-process
  35462. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35463. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35464. };
  35465. // Luminance generator
  35466. HDRRenderingPipeline.LUM_STEPS = 6;
  35467. return HDRRenderingPipeline;
  35468. })(BABYLON.PostProcessRenderPipeline);
  35469. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35470. })(BABYLON || (BABYLON = {}));
  35471. var BABYLON;
  35472. (function (BABYLON) {
  35473. var FaceAdjacencies = (function () {
  35474. function FaceAdjacencies() {
  35475. this.edges = new Array();
  35476. this.edgesConnectedCount = 0;
  35477. }
  35478. return FaceAdjacencies;
  35479. })();
  35480. var EdgesRenderer = (function () {
  35481. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35482. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35483. if (epsilon === void 0) { epsilon = 0.95; }
  35484. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35485. this._linesPositions = new Array();
  35486. this._linesNormals = new Array();
  35487. this._linesIndices = new Array();
  35488. this._buffers = new Array();
  35489. this._checkVerticesInsteadOfIndices = false;
  35490. this._source = source;
  35491. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35492. this._epsilon = epsilon;
  35493. this._prepareRessources();
  35494. this._generateEdgesLines();
  35495. }
  35496. EdgesRenderer.prototype._prepareRessources = function () {
  35497. if (this._lineShader) {
  35498. return;
  35499. }
  35500. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35501. attributes: ["position", "normal"],
  35502. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35503. });
  35504. this._lineShader.disableDepthWrite = true;
  35505. this._lineShader.backFaceCulling = false;
  35506. };
  35507. EdgesRenderer.prototype.dispose = function () {
  35508. this._vb0.dispose();
  35509. this._vb1.dispose();
  35510. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35511. this._lineShader.dispose();
  35512. };
  35513. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35514. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35515. return 0;
  35516. }
  35517. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35518. return 1;
  35519. }
  35520. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35521. return 2;
  35522. }
  35523. return -1;
  35524. };
  35525. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35526. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35527. return 0;
  35528. }
  35529. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35530. return 1;
  35531. }
  35532. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35533. return 2;
  35534. }
  35535. return -1;
  35536. };
  35537. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35538. var needToCreateLine;
  35539. if (edge === undefined) {
  35540. needToCreateLine = true;
  35541. }
  35542. else {
  35543. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35544. needToCreateLine = dotProduct < this._epsilon;
  35545. }
  35546. if (needToCreateLine) {
  35547. var offset = this._linesPositions.length / 3;
  35548. var normal = p0.subtract(p1);
  35549. normal.normalize();
  35550. // Positions
  35551. this._linesPositions.push(p0.x);
  35552. this._linesPositions.push(p0.y);
  35553. this._linesPositions.push(p0.z);
  35554. this._linesPositions.push(p0.x);
  35555. this._linesPositions.push(p0.y);
  35556. this._linesPositions.push(p0.z);
  35557. this._linesPositions.push(p1.x);
  35558. this._linesPositions.push(p1.y);
  35559. this._linesPositions.push(p1.z);
  35560. this._linesPositions.push(p1.x);
  35561. this._linesPositions.push(p1.y);
  35562. this._linesPositions.push(p1.z);
  35563. // Normals
  35564. this._linesNormals.push(p1.x);
  35565. this._linesNormals.push(p1.y);
  35566. this._linesNormals.push(p1.z);
  35567. this._linesNormals.push(-1);
  35568. this._linesNormals.push(p1.x);
  35569. this._linesNormals.push(p1.y);
  35570. this._linesNormals.push(p1.z);
  35571. this._linesNormals.push(1);
  35572. this._linesNormals.push(p0.x);
  35573. this._linesNormals.push(p0.y);
  35574. this._linesNormals.push(p0.z);
  35575. this._linesNormals.push(-1);
  35576. this._linesNormals.push(p0.x);
  35577. this._linesNormals.push(p0.y);
  35578. this._linesNormals.push(p0.z);
  35579. this._linesNormals.push(1);
  35580. // Indices
  35581. this._linesIndices.push(offset);
  35582. this._linesIndices.push(offset + 1);
  35583. this._linesIndices.push(offset + 2);
  35584. this._linesIndices.push(offset);
  35585. this._linesIndices.push(offset + 2);
  35586. this._linesIndices.push(offset + 3);
  35587. }
  35588. };
  35589. EdgesRenderer.prototype._generateEdgesLines = function () {
  35590. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35591. var indices = this._source.getIndices();
  35592. // First let's find adjacencies
  35593. var adjacencies = new Array();
  35594. var faceNormals = new Array();
  35595. var index;
  35596. var faceAdjacencies;
  35597. // Prepare faces
  35598. for (index = 0; index < indices.length; index += 3) {
  35599. faceAdjacencies = new FaceAdjacencies();
  35600. var p0Index = indices[index];
  35601. var p1Index = indices[index + 1];
  35602. var p2Index = indices[index + 2];
  35603. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35604. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35605. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35606. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35607. faceNormal.normalize();
  35608. faceNormals.push(faceNormal);
  35609. adjacencies.push(faceAdjacencies);
  35610. }
  35611. // Scan
  35612. for (index = 0; index < adjacencies.length; index++) {
  35613. faceAdjacencies = adjacencies[index];
  35614. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35615. var otherFaceAdjacencies = adjacencies[otherIndex];
  35616. if (faceAdjacencies.edgesConnectedCount === 3) {
  35617. break;
  35618. }
  35619. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35620. continue;
  35621. }
  35622. var otherP0 = indices[otherIndex * 3];
  35623. var otherP1 = indices[otherIndex * 3 + 1];
  35624. var otherP2 = indices[otherIndex * 3 + 2];
  35625. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35626. var otherEdgeIndex;
  35627. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35628. continue;
  35629. }
  35630. switch (edgeIndex) {
  35631. case 0:
  35632. if (this._checkVerticesInsteadOfIndices) {
  35633. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35634. }
  35635. else {
  35636. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35637. }
  35638. break;
  35639. case 1:
  35640. if (this._checkVerticesInsteadOfIndices) {
  35641. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35642. }
  35643. else {
  35644. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35645. }
  35646. break;
  35647. case 2:
  35648. if (this._checkVerticesInsteadOfIndices) {
  35649. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35650. }
  35651. else {
  35652. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35653. }
  35654. break;
  35655. }
  35656. if (otherEdgeIndex === -1) {
  35657. continue;
  35658. }
  35659. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35660. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35661. faceAdjacencies.edgesConnectedCount++;
  35662. otherFaceAdjacencies.edgesConnectedCount++;
  35663. if (faceAdjacencies.edgesConnectedCount === 3) {
  35664. break;
  35665. }
  35666. }
  35667. }
  35668. }
  35669. // Create lines
  35670. for (index = 0; index < adjacencies.length; index++) {
  35671. // 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
  35672. var current = adjacencies[index];
  35673. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35674. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35675. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35676. }
  35677. // Merge into a single mesh
  35678. var engine = this._source.getScene().getEngine();
  35679. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35680. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35681. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35682. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35683. this._ib = engine.createIndexBuffer(this._linesIndices);
  35684. this._indicesCount = this._linesIndices.length;
  35685. };
  35686. EdgesRenderer.prototype.render = function () {
  35687. if (!this._lineShader.isReady()) {
  35688. return;
  35689. }
  35690. var scene = this._source.getScene();
  35691. var engine = scene.getEngine();
  35692. this._lineShader._preBind();
  35693. // VBOs
  35694. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35695. scene.resetCachedMaterial();
  35696. this._lineShader.setColor4("color", this._source.edgesColor);
  35697. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35698. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35699. this._lineShader.bind(this._source.getWorldMatrix());
  35700. // Draw order
  35701. engine.draw(true, 0, this._indicesCount);
  35702. this._lineShader.unbind();
  35703. engine.setDepthWrite(true);
  35704. };
  35705. return EdgesRenderer;
  35706. })();
  35707. BABYLON.EdgesRenderer = EdgesRenderer;
  35708. })(BABYLON || (BABYLON = {}));
  35709. var BABYLON;
  35710. (function (BABYLON) {
  35711. (function (TonemappingOperator) {
  35712. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35713. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35714. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35715. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35716. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35717. var TonemappingOperator = BABYLON.TonemappingOperator;
  35718. ;
  35719. var TonemapPostProcess = (function (_super) {
  35720. __extends(TonemapPostProcess, _super);
  35721. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35722. var _this = this;
  35723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35724. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35725. this._operator = operator;
  35726. this._exposureAdjustment = exposureAdjustment;
  35727. var params = ["_ExposureAdjustment"];
  35728. var defines = "#define ";
  35729. if (operator === TonemappingOperator.Hable)
  35730. defines += "HABLE_TONEMAPPING";
  35731. else if (operator === TonemappingOperator.Reinhard)
  35732. defines += "REINHARD_TONEMAPPING";
  35733. else if (operator === TonemappingOperator.HejiDawson)
  35734. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35735. else if (operator === TonemappingOperator.Photographic)
  35736. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35737. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35738. this.onApply = function (effect) {
  35739. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35740. };
  35741. }
  35742. return TonemapPostProcess;
  35743. })(BABYLON.PostProcess);
  35744. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35745. })(BABYLON || (BABYLON = {}));
  35746. var BABYLON;
  35747. (function (BABYLON) {
  35748. var ReflectionProbe = (function () {
  35749. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35750. var _this = this;
  35751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35752. this.name = name;
  35753. this._viewMatrix = BABYLON.Matrix.Identity();
  35754. this._target = BABYLON.Vector3.Zero();
  35755. this._add = BABYLON.Vector3.Zero();
  35756. this.position = BABYLON.Vector3.Zero();
  35757. this._scene = scene;
  35758. this._scene.reflectionProbes.push(this);
  35759. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35760. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35761. switch (faceIndex) {
  35762. case 0:
  35763. _this._add.copyFromFloats(1, 0, 0);
  35764. break;
  35765. case 1:
  35766. _this._add.copyFromFloats(-1, 0, 0);
  35767. break;
  35768. case 2:
  35769. _this._add.copyFromFloats(0, -1, 0);
  35770. break;
  35771. case 3:
  35772. _this._add.copyFromFloats(0, 1, 0);
  35773. break;
  35774. case 4:
  35775. _this._add.copyFromFloats(0, 0, 1);
  35776. break;
  35777. case 5:
  35778. _this._add.copyFromFloats(0, 0, -1);
  35779. break;
  35780. }
  35781. if (_this._attachedMesh) {
  35782. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35783. }
  35784. _this.position.addToRef(_this._add, _this._target);
  35785. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35786. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35787. };
  35788. this._renderTargetTexture.onAfterUnbind = function () {
  35789. scene.updateTransformMatrix(true);
  35790. };
  35791. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35792. }
  35793. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35794. get: function () {
  35795. return this._renderTargetTexture.refreshRate;
  35796. },
  35797. set: function (value) {
  35798. this._renderTargetTexture.refreshRate = value;
  35799. },
  35800. enumerable: true,
  35801. configurable: true
  35802. });
  35803. ReflectionProbe.prototype.getScene = function () {
  35804. return this._scene;
  35805. };
  35806. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35807. get: function () {
  35808. return this._renderTargetTexture;
  35809. },
  35810. enumerable: true,
  35811. configurable: true
  35812. });
  35813. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35814. get: function () {
  35815. return this._renderTargetTexture.renderList;
  35816. },
  35817. enumerable: true,
  35818. configurable: true
  35819. });
  35820. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35821. this._attachedMesh = mesh;
  35822. };
  35823. ReflectionProbe.prototype.dispose = function () {
  35824. var index = this._scene.reflectionProbes.indexOf(this);
  35825. if (index !== -1) {
  35826. // Remove from the scene if found
  35827. this._scene.reflectionProbes.splice(index, 1);
  35828. }
  35829. if (this._renderTargetTexture) {
  35830. this._renderTargetTexture.dispose();
  35831. this._renderTargetTexture = null;
  35832. }
  35833. };
  35834. return ReflectionProbe;
  35835. })();
  35836. BABYLON.ReflectionProbe = ReflectionProbe;
  35837. })(BABYLON || (BABYLON = {}));
  35838. var BABYLON;
  35839. (function (BABYLON) {
  35840. var SolidParticle = (function () {
  35841. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35842. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35843. this.position = BABYLON.Vector3.Zero(); // position
  35844. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35845. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35846. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35847. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35848. this.alive = true; // alive
  35849. this.idx = particleIndex;
  35850. this._pos = positionIndex;
  35851. this._model = model;
  35852. this.shapeId = shapeId;
  35853. this.idxInShape = idxInShape;
  35854. }
  35855. return SolidParticle;
  35856. })();
  35857. BABYLON.SolidParticle = SolidParticle;
  35858. var ModelShape = (function () {
  35859. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35860. this.shapeID = id;
  35861. this._shape = shape;
  35862. this._shapeUV = shapeUV;
  35863. this._positionFunction = posFunction;
  35864. this._vertexFunction = vtxFunction;
  35865. }
  35866. return ModelShape;
  35867. })();
  35868. BABYLON.ModelShape = ModelShape;
  35869. })(BABYLON || (BABYLON = {}));
  35870. var BABYLON;
  35871. (function (BABYLON) {
  35872. var SolidParticleSystem = (function () {
  35873. function SolidParticleSystem(name, scene, options) {
  35874. // public members
  35875. this.particles = new Array();
  35876. this.nbParticles = 0;
  35877. this.billboard = false;
  35878. this.counter = 0;
  35879. this.vars = {};
  35880. this._positions = new Array();
  35881. this._indices = new Array();
  35882. this._normals = new Array();
  35883. this._colors = new Array();
  35884. this._uvs = new Array();
  35885. this._index = 0; // indices index
  35886. this._updatable = true;
  35887. this._pickable = false;
  35888. this._alwaysVisible = false;
  35889. this._shapeCounter = 0;
  35890. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35891. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35892. this._computeParticleColor = true;
  35893. this._computeParticleTexture = true;
  35894. this._computeParticleRotation = true;
  35895. this._computeParticleVertex = false;
  35896. this._cam_axisZ = BABYLON.Vector3.Zero();
  35897. this._cam_axisY = BABYLON.Vector3.Zero();
  35898. this._cam_axisX = BABYLON.Vector3.Zero();
  35899. this._axisX = BABYLON.Axis.X;
  35900. this._axisY = BABYLON.Axis.Y;
  35901. this._axisZ = BABYLON.Axis.Z;
  35902. this._fakeCamPos = BABYLON.Vector3.Zero();
  35903. this._rotMatrix = new BABYLON.Matrix();
  35904. this._invertMatrix = new BABYLON.Matrix();
  35905. this._rotated = BABYLON.Vector3.Zero();
  35906. this._quaternion = new BABYLON.Quaternion();
  35907. this._vertex = BABYLON.Vector3.Zero();
  35908. this._normal = BABYLON.Vector3.Zero();
  35909. this._yaw = 0.0;
  35910. this._pitch = 0.0;
  35911. this._roll = 0.0;
  35912. this._halfroll = 0.0;
  35913. this._halfpitch = 0.0;
  35914. this._halfyaw = 0.0;
  35915. this._sinRoll = 0.0;
  35916. this._cosRoll = 0.0;
  35917. this._sinPitch = 0.0;
  35918. this._cosPitch = 0.0;
  35919. this._sinYaw = 0.0;
  35920. this._cosYaw = 0.0;
  35921. this._w = 0.0;
  35922. this.name = name;
  35923. this._scene = scene;
  35924. this._camera = scene.activeCamera;
  35925. this._pickable = options ? options.isPickable : false;
  35926. if (options && options.updatable) {
  35927. this._updatable = options.updatable;
  35928. }
  35929. else {
  35930. this._updatable = true;
  35931. }
  35932. if (this._pickable) {
  35933. this.pickedParticles = [];
  35934. }
  35935. }
  35936. // build the SPS mesh : returns the mesh
  35937. SolidParticleSystem.prototype.buildMesh = function () {
  35938. if (this.nbParticles === 0) {
  35939. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35940. this.addShape(triangle, 1);
  35941. triangle.dispose();
  35942. }
  35943. this._positions32 = new Float32Array(this._positions);
  35944. this._uvs32 = new Float32Array(this._uvs);
  35945. this._colors32 = new Float32Array(this._colors);
  35946. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35947. this._normals32 = new Float32Array(this._normals);
  35948. this._fixedNormal32 = new Float32Array(this._normals);
  35949. var vertexData = new BABYLON.VertexData();
  35950. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35951. vertexData.indices = this._indices;
  35952. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35953. if (this._uvs32) {
  35954. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35955. ;
  35956. }
  35957. if (this._colors32) {
  35958. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35959. }
  35960. var mesh = new BABYLON.Mesh(name, this._scene);
  35961. vertexData.applyToMesh(mesh, this._updatable);
  35962. this.mesh = mesh;
  35963. this.mesh.isPickable = this._pickable;
  35964. // free memory
  35965. this._positions = null;
  35966. this._normals = null;
  35967. this._uvs = null;
  35968. this._colors = null;
  35969. if (!this._updatable) {
  35970. this.particles.length = 0;
  35971. }
  35972. return mesh;
  35973. };
  35974. //reset copy
  35975. SolidParticleSystem.prototype._resetCopy = function () {
  35976. this._copy.position.x = 0;
  35977. this._copy.position.y = 0;
  35978. this._copy.position.z = 0;
  35979. this._copy.rotation.x = 0;
  35980. this._copy.rotation.y = 0;
  35981. this._copy.rotation.z = 0;
  35982. this._copy.quaternion = null;
  35983. this._copy.scale.x = 1;
  35984. this._copy.scale.y = 1;
  35985. this._copy.scale.z = 1;
  35986. this._copy.uvs.x = 0;
  35987. this._copy.uvs.y = 0;
  35988. this._copy.uvs.z = 1;
  35989. this._copy.uvs.w = 1;
  35990. this._copy.color = null;
  35991. };
  35992. // _meshBuilder : inserts the shape model in the global SPS mesh
  35993. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35994. var i;
  35995. var u = 0;
  35996. var c = 0;
  35997. this._resetCopy();
  35998. if (options && options.positionFunction) {
  35999. options.positionFunction(this._copy, idx, idxInShape);
  36000. }
  36001. if (this._copy.quaternion) {
  36002. this._quaternion.x = this._copy.quaternion.x;
  36003. this._quaternion.y = this._copy.quaternion.y;
  36004. this._quaternion.z = this._copy.quaternion.z;
  36005. this._quaternion.w = this._copy.quaternion.w;
  36006. }
  36007. else {
  36008. this._yaw = this._copy.rotation.y;
  36009. this._pitch = this._copy.rotation.x;
  36010. this._roll = this._copy.rotation.z;
  36011. this._quaternionRotationYPR();
  36012. }
  36013. this._quaternionToRotationMatrix();
  36014. for (i = 0; i < shape.length; i++) {
  36015. this._vertex.x = shape[i].x;
  36016. this._vertex.y = shape[i].y;
  36017. this._vertex.z = shape[i].z;
  36018. if (options && options.vertexFunction) {
  36019. options.vertexFunction(this._copy, this._vertex, i);
  36020. }
  36021. this._vertex.x *= this._copy.scale.x;
  36022. this._vertex.y *= this._copy.scale.y;
  36023. this._vertex.z *= this._copy.scale.z;
  36024. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36025. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36026. if (meshUV) {
  36027. 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);
  36028. u += 2;
  36029. }
  36030. if (this._copy.color) {
  36031. this._color = this._copy.color;
  36032. }
  36033. else if (meshCol && meshCol[c]) {
  36034. this._color.r = meshCol[c];
  36035. this._color.g = meshCol[c + 1];
  36036. this._color.b = meshCol[c + 2];
  36037. this._color.a = meshCol[c + 3];
  36038. }
  36039. else {
  36040. this._color.r = 1;
  36041. this._color.g = 1;
  36042. this._color.b = 1;
  36043. this._color.a = 1;
  36044. }
  36045. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36046. c += 4;
  36047. }
  36048. for (i = 0; i < meshInd.length; i++) {
  36049. indices.push(p + meshInd[i]);
  36050. }
  36051. if (this._pickable) {
  36052. var nbfaces = meshInd.length / 3;
  36053. for (i = 0; i < nbfaces; i++) {
  36054. this.pickedParticles.push({ idx: idx, faceId: i });
  36055. }
  36056. }
  36057. };
  36058. // returns a shape array from positions array
  36059. SolidParticleSystem.prototype._posToShape = function (positions) {
  36060. var shape = [];
  36061. for (var i = 0; i < positions.length; i += 3) {
  36062. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36063. }
  36064. return shape;
  36065. };
  36066. // returns a shapeUV array from a Vector4 uvs
  36067. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36068. var shapeUV = [];
  36069. if (uvs) {
  36070. for (var i = 0; i < uvs.length; i++)
  36071. shapeUV.push(uvs[i]);
  36072. }
  36073. return shapeUV;
  36074. };
  36075. // adds a new particle object in the particles array
  36076. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36077. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36078. };
  36079. // add solid particles from a shape model in the particles array
  36080. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36081. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36082. var meshInd = mesh.getIndices();
  36083. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36084. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36085. var shape = this._posToShape(meshPos);
  36086. var shapeUV = this._uvsToShapeUV(meshUV);
  36087. var posfunc = options ? options.positionFunction : null;
  36088. var vtxfunc = options ? options.vertexFunction : null;
  36089. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36090. // particles
  36091. var idx = this.nbParticles;
  36092. for (var i = 0; i < nb; i++) {
  36093. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36094. if (this._updatable) {
  36095. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36096. }
  36097. this._index += shape.length;
  36098. idx++;
  36099. }
  36100. this.nbParticles += nb;
  36101. this._shapeCounter++;
  36102. return this._shapeCounter;
  36103. };
  36104. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36105. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36106. this._resetCopy();
  36107. if (particle._model._positionFunction) {
  36108. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36109. }
  36110. if (this._copy.quaternion) {
  36111. this._quaternion.x = this._copy.quaternion.x;
  36112. this._quaternion.y = this._copy.quaternion.y;
  36113. this._quaternion.z = this._copy.quaternion.z;
  36114. this._quaternion.w = this._copy.quaternion.w;
  36115. }
  36116. else {
  36117. this._yaw = this._copy.rotation.y;
  36118. this._pitch = this._copy.rotation.x;
  36119. this._roll = this._copy.rotation.z;
  36120. this._quaternionRotationYPR();
  36121. }
  36122. this._quaternionToRotationMatrix();
  36123. this._shape = particle._model._shape;
  36124. for (var pt = 0; pt < this._shape.length; pt++) {
  36125. this._vertex.x = this._shape[pt].x;
  36126. this._vertex.y = this._shape[pt].y;
  36127. this._vertex.z = this._shape[pt].z;
  36128. if (particle._model._vertexFunction) {
  36129. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36130. }
  36131. this._vertex.x *= this._copy.scale.x;
  36132. this._vertex.y *= this._copy.scale.y;
  36133. this._vertex.z *= this._copy.scale.z;
  36134. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36135. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36136. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36137. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36138. }
  36139. particle.position.x = 0;
  36140. particle.position.y = 0;
  36141. particle.position.z = 0;
  36142. particle.rotation.x = 0;
  36143. particle.rotation.y = 0;
  36144. particle.rotation.z = 0;
  36145. particle.quaternion = null;
  36146. particle.scale.x = 1;
  36147. particle.scale.y = 1;
  36148. particle.scale.z = 1;
  36149. };
  36150. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36151. SolidParticleSystem.prototype.rebuildMesh = function () {
  36152. for (var p = 0; p < this.particles.length; p++) {
  36153. this._rebuildParticle(this.particles[p]);
  36154. }
  36155. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36156. };
  36157. // sets all the particles : updates the VBO
  36158. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36159. if (start === void 0) { start = 0; }
  36160. if (end === void 0) { end = this.nbParticles - 1; }
  36161. if (update === void 0) { update = true; }
  36162. if (!this._updatable) {
  36163. return;
  36164. }
  36165. // custom beforeUpdate
  36166. this.beforeUpdateParticles(start, end, update);
  36167. this._cam_axisX.x = 1;
  36168. this._cam_axisX.y = 0;
  36169. this._cam_axisX.z = 0;
  36170. this._cam_axisY.x = 0;
  36171. this._cam_axisY.y = 1;
  36172. this._cam_axisY.z = 0;
  36173. this._cam_axisZ.x = 0;
  36174. this._cam_axisZ.y = 0;
  36175. this._cam_axisZ.z = 1;
  36176. // if the particles will always face the camera
  36177. if (this.billboard) {
  36178. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36179. this._yaw = this.mesh.rotation.y;
  36180. this._pitch = this.mesh.rotation.x;
  36181. this._roll = this.mesh.rotation.z;
  36182. this._quaternionRotationYPR();
  36183. this._quaternionToRotationMatrix();
  36184. this._rotMatrix.invertToRef(this._invertMatrix);
  36185. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36186. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36187. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36188. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36189. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36190. this._cam_axisY.normalize();
  36191. this._cam_axisX.normalize();
  36192. this._cam_axisZ.normalize();
  36193. }
  36194. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36195. var idx = 0;
  36196. var index = 0;
  36197. var colidx = 0;
  36198. var colorIndex = 0;
  36199. var uvidx = 0;
  36200. var uvIndex = 0;
  36201. // particle loop
  36202. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36203. for (var p = start; p <= end; p++) {
  36204. this._particle = this.particles[p];
  36205. this._shape = this._particle._model._shape;
  36206. this._shapeUV = this._particle._model._shapeUV;
  36207. // call to custom user function to update the particle properties
  36208. this.updateParticle(this._particle);
  36209. // particle rotation matrix
  36210. if (this.billboard) {
  36211. this._particle.rotation.x = 0.0;
  36212. this._particle.rotation.y = 0.0;
  36213. }
  36214. if (this._computeParticleRotation) {
  36215. if (this._particle.quaternion) {
  36216. this._quaternion.x = this._particle.quaternion.x;
  36217. this._quaternion.y = this._particle.quaternion.y;
  36218. this._quaternion.z = this._particle.quaternion.z;
  36219. this._quaternion.w = this._particle.quaternion.w;
  36220. }
  36221. else {
  36222. this._yaw = this._particle.rotation.y;
  36223. this._pitch = this._particle.rotation.x;
  36224. this._roll = this._particle.rotation.z;
  36225. this._quaternionRotationYPR();
  36226. }
  36227. this._quaternionToRotationMatrix();
  36228. }
  36229. for (var pt = 0; pt < this._shape.length; pt++) {
  36230. idx = index + pt * 3;
  36231. colidx = colorIndex + pt * 4;
  36232. uvidx = uvIndex + pt * 2;
  36233. this._vertex.x = this._shape[pt].x;
  36234. this._vertex.y = this._shape[pt].y;
  36235. this._vertex.z = this._shape[pt].z;
  36236. if (this._computeParticleVertex) {
  36237. this.updateParticleVertex(this._particle, this._vertex, pt);
  36238. }
  36239. // positions
  36240. this._vertex.x *= this._particle.scale.x;
  36241. this._vertex.y *= this._particle.scale.y;
  36242. this._vertex.z *= this._particle.scale.z;
  36243. 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];
  36244. 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;
  36245. 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;
  36246. 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;
  36247. 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;
  36248. 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;
  36249. 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;
  36250. // normals : if the particles can't be morphed then just rotate the normals
  36251. if (!this._computeParticleVertex && !this.billboard) {
  36252. this._normal.x = this._fixedNormal32[idx];
  36253. this._normal.y = this._fixedNormal32[idx + 1];
  36254. this._normal.z = this._fixedNormal32[idx + 2];
  36255. 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];
  36256. 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;
  36257. 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;
  36258. 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;
  36259. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36260. 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;
  36261. 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;
  36262. }
  36263. if (this._computeParticleColor) {
  36264. this._colors32[colidx] = this._particle.color.r;
  36265. this._colors32[colidx + 1] = this._particle.color.g;
  36266. this._colors32[colidx + 2] = this._particle.color.b;
  36267. this._colors32[colidx + 3] = this._particle.color.a;
  36268. }
  36269. if (this._computeParticleTexture) {
  36270. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36271. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36272. }
  36273. }
  36274. index = idx + 3;
  36275. colorIndex = colidx + 4;
  36276. uvIndex = uvidx + 2;
  36277. }
  36278. if (update) {
  36279. if (this._computeParticleColor) {
  36280. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36281. }
  36282. if (this._computeParticleTexture) {
  36283. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36284. }
  36285. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36286. if (!this.mesh.areNormalsFrozen) {
  36287. if (this._computeParticleVertex || this.billboard) {
  36288. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36289. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36290. for (var i = 0; i < this._normals32.length; i++) {
  36291. this._fixedNormal32[i] = this._normals32[i];
  36292. }
  36293. }
  36294. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36295. }
  36296. }
  36297. this.afterUpdateParticles(start, end, update);
  36298. };
  36299. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36300. this._halfroll = this._roll * 0.5;
  36301. this._halfpitch = this._pitch * 0.5;
  36302. this._halfyaw = this._yaw * 0.5;
  36303. this._sinRoll = Math.sin(this._halfroll);
  36304. this._cosRoll = Math.cos(this._halfroll);
  36305. this._sinPitch = Math.sin(this._halfpitch);
  36306. this._cosPitch = Math.cos(this._halfpitch);
  36307. this._sinYaw = Math.sin(this._halfyaw);
  36308. this._cosYaw = Math.cos(this._halfyaw);
  36309. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36310. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36311. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36312. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36313. };
  36314. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36315. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36316. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36317. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36318. this._rotMatrix.m[3] = 0;
  36319. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36320. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36321. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36322. this._rotMatrix.m[7] = 0;
  36323. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36324. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36325. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36326. this._rotMatrix.m[11] = 0;
  36327. this._rotMatrix.m[12] = 0;
  36328. this._rotMatrix.m[13] = 0;
  36329. this._rotMatrix.m[14] = 0;
  36330. this._rotMatrix.m[15] = 1.0;
  36331. };
  36332. // dispose the SPS
  36333. SolidParticleSystem.prototype.dispose = function () {
  36334. this.mesh.dispose();
  36335. this.vars = null;
  36336. // drop references to internal big arrays for the GC
  36337. this._positions = null;
  36338. this._indices = null;
  36339. this._normals = null;
  36340. this._uvs = null;
  36341. this._colors = null;
  36342. this._positions32 = null;
  36343. this._normals32 = null;
  36344. this._fixedNormal32 = null;
  36345. this._uvs32 = null;
  36346. this._colors32 = null;
  36347. this.pickedParticles = null;
  36348. };
  36349. // Visibilty helpers
  36350. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36351. this.mesh.refreshBoundingInfo();
  36352. };
  36353. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36354. // getter and setter
  36355. get: function () {
  36356. return this._alwaysVisible;
  36357. },
  36358. set: function (val) {
  36359. this._alwaysVisible = val;
  36360. this.mesh.alwaysSelectAsActiveMesh = val;
  36361. },
  36362. enumerable: true,
  36363. configurable: true
  36364. });
  36365. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36366. // getters
  36367. get: function () {
  36368. return this._computeParticleRotation;
  36369. },
  36370. // Optimizer setters
  36371. set: function (val) {
  36372. this._computeParticleRotation = val;
  36373. },
  36374. enumerable: true,
  36375. configurable: true
  36376. });
  36377. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36378. get: function () {
  36379. return this._computeParticleColor;
  36380. },
  36381. set: function (val) {
  36382. this._computeParticleColor = val;
  36383. },
  36384. enumerable: true,
  36385. configurable: true
  36386. });
  36387. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36388. get: function () {
  36389. return this._computeParticleTexture;
  36390. },
  36391. set: function (val) {
  36392. this._computeParticleTexture = val;
  36393. },
  36394. enumerable: true,
  36395. configurable: true
  36396. });
  36397. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36398. get: function () {
  36399. return this._computeParticleVertex;
  36400. },
  36401. set: function (val) {
  36402. this._computeParticleVertex = val;
  36403. },
  36404. enumerable: true,
  36405. configurable: true
  36406. });
  36407. // =======================================================================
  36408. // Particle behavior logic
  36409. // these following methods may be overwritten by the user to fit his needs
  36410. // init : sets all particles first values and calls updateParticle to set them in space
  36411. // can be overwritten by the user
  36412. SolidParticleSystem.prototype.initParticles = function () {
  36413. };
  36414. // recycles a particle : can by overwritten by the user
  36415. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36416. return particle;
  36417. };
  36418. // updates a particle : can be overwritten by the user
  36419. // will be called on each particle by setParticles() :
  36420. // ex : just set a particle position or velocity and recycle conditions
  36421. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36422. return particle;
  36423. };
  36424. // updates a vertex of a particle : can be overwritten by the user
  36425. // will be called on each vertex particle by setParticles() :
  36426. // particle : the current particle
  36427. // vertex : the current index of the current particle
  36428. // pt : the index of the current vertex in the particle shape
  36429. // ex : just set a vertex particle position
  36430. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36431. return vertex;
  36432. };
  36433. // will be called before any other treatment by setParticles()
  36434. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36435. };
  36436. // will be called after all setParticles() treatments
  36437. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36438. };
  36439. return SolidParticleSystem;
  36440. })();
  36441. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36442. })(BABYLON || (BABYLON = {}));
  36443. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  36444. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*S+o*D)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*S-n*Z+o*W)*b,t.m[15]=(i*D-n*N+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;\nt.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}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36445. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36446. module.exports = BABYLON;
  36447. };