babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888
  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.GetConstructorName = function (obj) {
  3903. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3904. var cname = str.match(/function\s(\w*)/)[1];
  3905. var aliases = ["", "anonymous", "Anonymous"];
  3906. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3907. };
  3908. Tools.ToHex = function (i) {
  3909. var str = i.toString(16);
  3910. if (i <= 15) {
  3911. return ("0" + str).toUpperCase();
  3912. }
  3913. return str.toUpperCase();
  3914. };
  3915. Tools.SetImmediate = function (action) {
  3916. if (window.setImmediate) {
  3917. window.setImmediate(action);
  3918. }
  3919. else {
  3920. setTimeout(action, 1);
  3921. }
  3922. };
  3923. Tools.IsExponentOfTwo = function (value) {
  3924. var count = 1;
  3925. do {
  3926. count *= 2;
  3927. } while (count < value);
  3928. return count === value;
  3929. };
  3930. Tools.GetExponentOfTwo = function (value, max) {
  3931. var count = 1;
  3932. do {
  3933. count *= 2;
  3934. } while (count < value);
  3935. if (count > max)
  3936. count = max;
  3937. return count;
  3938. };
  3939. Tools.GetFilename = function (path) {
  3940. var index = path.lastIndexOf("/");
  3941. if (index < 0)
  3942. return path;
  3943. return path.substring(index + 1);
  3944. };
  3945. Tools.GetDOMTextContent = function (element) {
  3946. var result = "";
  3947. var child = element.firstChild;
  3948. while (child) {
  3949. if (child.nodeType === 3) {
  3950. result += child.textContent;
  3951. }
  3952. child = child.nextSibling;
  3953. }
  3954. return result;
  3955. };
  3956. Tools.ToDegrees = function (angle) {
  3957. return angle * 180 / Math.PI;
  3958. };
  3959. Tools.ToRadians = function (angle) {
  3960. return angle * Math.PI / 180;
  3961. };
  3962. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3963. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3964. var output = "";
  3965. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3966. var i = 0;
  3967. var bytes = new Uint8Array(buffer);
  3968. while (i < bytes.length) {
  3969. chr1 = bytes[i++];
  3970. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3971. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3972. enc1 = chr1 >> 2;
  3973. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3974. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3975. enc4 = chr3 & 63;
  3976. if (isNaN(chr2)) {
  3977. enc3 = enc4 = 64;
  3978. }
  3979. else if (isNaN(chr3)) {
  3980. enc4 = 64;
  3981. }
  3982. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3983. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3984. }
  3985. return "data:image/png;base64," + output;
  3986. };
  3987. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3988. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3989. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3990. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3991. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3992. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3993. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3994. }
  3995. return {
  3996. minimum: minimum,
  3997. maximum: maximum
  3998. };
  3999. };
  4000. Tools.ExtractMinAndMax = function (positions, start, count) {
  4001. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4002. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4003. for (var index = start; index < start + count; index++) {
  4004. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4005. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4006. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4007. }
  4008. return {
  4009. minimum: minimum,
  4010. maximum: maximum
  4011. };
  4012. };
  4013. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4014. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4015. return undefined;
  4016. return Array.isArray(obj) ? obj : [obj];
  4017. };
  4018. // Misc.
  4019. Tools.GetPointerPrefix = function () {
  4020. var eventPrefix = "pointer";
  4021. // Check if hand.js is referenced or if the browser natively supports pointer events
  4022. if (!navigator.pointerEnabled) {
  4023. eventPrefix = "mouse";
  4024. }
  4025. return eventPrefix;
  4026. };
  4027. Tools.QueueNewFrame = function (func) {
  4028. if (window.requestAnimationFrame)
  4029. window.requestAnimationFrame(func);
  4030. else if (window.msRequestAnimationFrame)
  4031. window.msRequestAnimationFrame(func);
  4032. else if (window.webkitRequestAnimationFrame)
  4033. window.webkitRequestAnimationFrame(func);
  4034. else if (window.mozRequestAnimationFrame)
  4035. window.mozRequestAnimationFrame(func);
  4036. else if (window.oRequestAnimationFrame)
  4037. window.oRequestAnimationFrame(func);
  4038. else {
  4039. window.setTimeout(func, 16);
  4040. }
  4041. };
  4042. Tools.RequestFullscreen = function (element) {
  4043. if (element.requestFullscreen)
  4044. element.requestFullscreen();
  4045. else if (element.msRequestFullscreen)
  4046. element.msRequestFullscreen();
  4047. else if (element.webkitRequestFullscreen)
  4048. element.webkitRequestFullscreen();
  4049. else if (element.mozRequestFullScreen)
  4050. element.mozRequestFullScreen();
  4051. };
  4052. Tools.ExitFullscreen = function () {
  4053. if (document.exitFullscreen) {
  4054. document.exitFullscreen();
  4055. }
  4056. else if (document.mozCancelFullScreen) {
  4057. document.mozCancelFullScreen();
  4058. }
  4059. else if (document.webkitCancelFullScreen) {
  4060. document.webkitCancelFullScreen();
  4061. }
  4062. else if (document.msCancelFullScreen) {
  4063. document.msCancelFullScreen();
  4064. }
  4065. };
  4066. // External files
  4067. Tools.CleanUrl = function (url) {
  4068. url = url.replace(/#/mg, "%23");
  4069. return url;
  4070. };
  4071. Tools.LoadImage = function (url, onload, onerror, database) {
  4072. if (url instanceof ArrayBuffer) {
  4073. url = Tools.EncodeArrayBufferTobase64(url);
  4074. }
  4075. url = Tools.CleanUrl(url);
  4076. var img = new Image();
  4077. if (url.substr(0, 5) !== "data:") {
  4078. if (Tools.CorsBehavior) {
  4079. switch (typeof (Tools.CorsBehavior)) {
  4080. case "function":
  4081. var result = Tools.CorsBehavior(url);
  4082. if (result) {
  4083. img.crossOrigin = result;
  4084. }
  4085. break;
  4086. case "string":
  4087. default:
  4088. img.crossOrigin = Tools.CorsBehavior;
  4089. break;
  4090. }
  4091. }
  4092. }
  4093. img.onload = function () {
  4094. onload(img);
  4095. };
  4096. img.onerror = function (err) {
  4097. Tools.Error("Error while trying to load texture: " + url);
  4098. 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";
  4099. onload(img);
  4100. };
  4101. var noIndexedDB = function () {
  4102. img.src = url;
  4103. };
  4104. var loadFromIndexedDB = function () {
  4105. database.loadImageFromDB(url, img);
  4106. };
  4107. //ANY database to do!
  4108. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4109. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4110. }
  4111. else {
  4112. if (url.indexOf("file:") === -1) {
  4113. noIndexedDB();
  4114. }
  4115. else {
  4116. try {
  4117. var textureName = url.substring(5);
  4118. var blobURL;
  4119. try {
  4120. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4121. }
  4122. catch (ex) {
  4123. // Chrome doesn't support oneTimeOnly parameter
  4124. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4125. }
  4126. img.src = blobURL;
  4127. }
  4128. catch (e) {
  4129. img.src = null;
  4130. }
  4131. }
  4132. }
  4133. return img;
  4134. };
  4135. //ANY
  4136. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4137. url = Tools.CleanUrl(url);
  4138. var noIndexedDB = function () {
  4139. var request = new XMLHttpRequest();
  4140. var loadUrl = Tools.BaseUrl + url;
  4141. request.open('GET', loadUrl, true);
  4142. if (useArrayBuffer) {
  4143. request.responseType = "arraybuffer";
  4144. }
  4145. request.onprogress = progressCallBack;
  4146. request.onreadystatechange = function () {
  4147. if (request.readyState === 4) {
  4148. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4149. callback(!useArrayBuffer ? request.responseText : request.response);
  4150. }
  4151. else {
  4152. if (onError) {
  4153. onError();
  4154. }
  4155. else {
  4156. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4157. }
  4158. }
  4159. }
  4160. };
  4161. request.send(null);
  4162. };
  4163. var loadFromIndexedDB = function () {
  4164. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4165. };
  4166. if (url.indexOf("file:") !== -1) {
  4167. var fileName = url.substring(5);
  4168. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4169. }
  4170. else {
  4171. // Caching all files
  4172. if (database && database.enableSceneOffline) {
  4173. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4174. }
  4175. else {
  4176. noIndexedDB();
  4177. }
  4178. }
  4179. };
  4180. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4181. var reader = new FileReader();
  4182. reader.onload = function (e) {
  4183. //target doesn't have result from ts 1.3
  4184. callback(e.target['result']);
  4185. };
  4186. reader.onprogress = progressCallback;
  4187. reader.readAsDataURL(fileToLoad);
  4188. };
  4189. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4190. var reader = new FileReader();
  4191. reader.onerror = function (e) {
  4192. Tools.Log("Error while reading file: " + fileToLoad.name);
  4193. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4194. };
  4195. reader.onload = function (e) {
  4196. //target doesn't have result from ts 1.3
  4197. callback(e.target['result']);
  4198. };
  4199. reader.onprogress = progressCallBack;
  4200. if (!useArrayBuffer) {
  4201. // Asynchronous read
  4202. reader.readAsText(fileToLoad);
  4203. }
  4204. else {
  4205. reader.readAsArrayBuffer(fileToLoad);
  4206. }
  4207. };
  4208. //returns a downloadable url to a file content.
  4209. Tools.FileAsURL = function (content) {
  4210. var fileBlob = new Blob([content]);
  4211. var url = window.URL || window.webkitURL;
  4212. var link = url.createObjectURL(fileBlob);
  4213. return link;
  4214. };
  4215. // Misc.
  4216. Tools.Clamp = function (value, min, max) {
  4217. if (min === void 0) { min = 0; }
  4218. if (max === void 0) { max = 1; }
  4219. return Math.min(max, Math.max(min, value));
  4220. };
  4221. // Returns -1 when value is a negative number and
  4222. // +1 when value is a positive number.
  4223. Tools.Sign = function (value) {
  4224. value = +value; // convert to a number
  4225. if (value === 0 || isNaN(value))
  4226. return value;
  4227. return value > 0 ? 1 : -1;
  4228. };
  4229. Tools.Format = function (value, decimals) {
  4230. if (decimals === void 0) { decimals = 2; }
  4231. return value.toFixed(decimals);
  4232. };
  4233. Tools.CheckExtends = function (v, min, max) {
  4234. if (v.x < min.x)
  4235. min.x = v.x;
  4236. if (v.y < min.y)
  4237. min.y = v.y;
  4238. if (v.z < min.z)
  4239. min.z = v.z;
  4240. if (v.x > max.x)
  4241. max.x = v.x;
  4242. if (v.y > max.y)
  4243. max.y = v.y;
  4244. if (v.z > max.z)
  4245. max.z = v.z;
  4246. };
  4247. Tools.WithinEpsilon = function (a, b, epsilon) {
  4248. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4249. var num = a - b;
  4250. return -epsilon <= num && num <= epsilon;
  4251. };
  4252. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4253. for (var prop in source) {
  4254. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4255. continue;
  4256. }
  4257. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4258. continue;
  4259. }
  4260. var sourceValue = source[prop];
  4261. var typeOfSourceValue = typeof sourceValue;
  4262. if (typeOfSourceValue === "function") {
  4263. continue;
  4264. }
  4265. if (typeOfSourceValue === "object") {
  4266. if (sourceValue instanceof Array) {
  4267. destination[prop] = [];
  4268. if (sourceValue.length > 0) {
  4269. if (typeof sourceValue[0] == "object") {
  4270. for (var index = 0; index < sourceValue.length; index++) {
  4271. var clonedValue = cloneValue(sourceValue[index], destination);
  4272. if (destination[prop].indexOf(clonedValue) === -1) {
  4273. destination[prop].push(clonedValue);
  4274. }
  4275. }
  4276. }
  4277. else {
  4278. destination[prop] = sourceValue.slice(0);
  4279. }
  4280. }
  4281. }
  4282. else {
  4283. destination[prop] = cloneValue(sourceValue, destination);
  4284. }
  4285. }
  4286. else {
  4287. destination[prop] = sourceValue;
  4288. }
  4289. }
  4290. };
  4291. Tools.IsEmpty = function (obj) {
  4292. for (var i in obj) {
  4293. return false;
  4294. }
  4295. return true;
  4296. };
  4297. Tools.RegisterTopRootEvents = function (events) {
  4298. for (var index = 0; index < events.length; index++) {
  4299. var event = events[index];
  4300. window.addEventListener(event.name, event.handler, false);
  4301. try {
  4302. if (window.parent) {
  4303. window.parent.addEventListener(event.name, event.handler, false);
  4304. }
  4305. }
  4306. catch (e) {
  4307. }
  4308. }
  4309. };
  4310. Tools.UnregisterTopRootEvents = function (events) {
  4311. for (var index = 0; index < events.length; index++) {
  4312. var event = events[index];
  4313. window.removeEventListener(event.name, event.handler);
  4314. try {
  4315. if (window.parent) {
  4316. window.parent.removeEventListener(event.name, event.handler);
  4317. }
  4318. }
  4319. catch (e) {
  4320. }
  4321. }
  4322. };
  4323. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4324. // Read the contents of the framebuffer
  4325. var numberOfChannelsByLine = width * 4;
  4326. var halfHeight = height / 2;
  4327. //Reading datas from WebGL
  4328. var data = engine.readPixels(0, 0, width, height);
  4329. //To flip image on Y axis.
  4330. for (var i = 0; i < halfHeight; i++) {
  4331. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4332. var currentCell = j + i * numberOfChannelsByLine;
  4333. var targetLine = height - i - 1;
  4334. var targetCell = j + targetLine * numberOfChannelsByLine;
  4335. var temp = data[currentCell];
  4336. data[currentCell] = data[targetCell];
  4337. data[targetCell] = temp;
  4338. }
  4339. }
  4340. // Create a 2D canvas to store the result
  4341. if (!screenshotCanvas) {
  4342. screenshotCanvas = document.createElement('canvas');
  4343. }
  4344. screenshotCanvas.width = width;
  4345. screenshotCanvas.height = height;
  4346. var context = screenshotCanvas.getContext('2d');
  4347. // Copy the pixels to a 2D canvas
  4348. var imageData = context.createImageData(width, height);
  4349. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4350. var castData = imageData.data;
  4351. castData.set(data);
  4352. context.putImageData(imageData, 0, 0);
  4353. var base64Image = screenshotCanvas.toDataURL();
  4354. if (successCallback) {
  4355. successCallback(base64Image);
  4356. }
  4357. else {
  4358. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4359. if (("download" in document.createElement("a"))) {
  4360. var a = window.document.createElement("a");
  4361. a.href = base64Image;
  4362. var date = new Date();
  4363. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4364. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4365. window.document.body.appendChild(a);
  4366. a.addEventListener("click", function () {
  4367. a.parentElement.removeChild(a);
  4368. });
  4369. a.click();
  4370. }
  4371. else {
  4372. var newWindow = window.open("");
  4373. var img = newWindow.document.createElement("img");
  4374. img.src = base64Image;
  4375. newWindow.document.body.appendChild(img);
  4376. }
  4377. }
  4378. };
  4379. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4380. var width;
  4381. var height;
  4382. //If a precision value is specified
  4383. if (size.precision) {
  4384. width = Math.round(engine.getRenderWidth() * size.precision);
  4385. height = Math.round(width / engine.getAspectRatio(camera));
  4386. size = { width: width, height: height };
  4387. }
  4388. else if (size.width && size.height) {
  4389. width = size.width;
  4390. height = size.height;
  4391. }
  4392. else if (size.width && !size.height) {
  4393. width = size.width;
  4394. height = Math.round(width / engine.getAspectRatio(camera));
  4395. size = { width: width, height: height };
  4396. }
  4397. else if (size.height && !size.width) {
  4398. height = size.height;
  4399. width = Math.round(height * engine.getAspectRatio(camera));
  4400. size = { width: width, height: height };
  4401. }
  4402. else if (!isNaN(size)) {
  4403. height = size;
  4404. width = size;
  4405. }
  4406. else {
  4407. Tools.Error("Invalid 'size' parameter !");
  4408. return;
  4409. }
  4410. var scene = camera.getScene();
  4411. var previousCamera = null;
  4412. if (scene.activeCamera !== camera) {
  4413. previousCamera = scene.activeCamera;
  4414. scene.activeCamera = camera;
  4415. }
  4416. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4417. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4418. texture.renderList = scene.meshes;
  4419. texture.onAfterRender = function () {
  4420. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4421. };
  4422. scene.incrementRenderId();
  4423. texture.render(true);
  4424. texture.dispose();
  4425. if (previousCamera) {
  4426. scene.activeCamera = previousCamera;
  4427. }
  4428. };
  4429. // XHR response validator for local file scenario
  4430. Tools.ValidateXHRData = function (xhr, dataType) {
  4431. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4432. if (dataType === void 0) { dataType = 7; }
  4433. try {
  4434. if (dataType & 1) {
  4435. if (xhr.responseText && xhr.responseText.length > 0) {
  4436. return true;
  4437. }
  4438. else if (dataType === 1) {
  4439. return false;
  4440. }
  4441. }
  4442. if (dataType & 2) {
  4443. // Check header width and height since there is no "TGA" magic number
  4444. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4445. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4446. return true;
  4447. }
  4448. else if (dataType === 2) {
  4449. return false;
  4450. }
  4451. }
  4452. if (dataType & 4) {
  4453. // Check for the "DDS" magic number
  4454. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4455. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4456. return true;
  4457. }
  4458. else {
  4459. return false;
  4460. }
  4461. }
  4462. }
  4463. catch (e) {
  4464. }
  4465. return false;
  4466. };
  4467. Object.defineProperty(Tools, "NoneLogLevel", {
  4468. get: function () {
  4469. return Tools._NoneLogLevel;
  4470. },
  4471. enumerable: true,
  4472. configurable: true
  4473. });
  4474. Object.defineProperty(Tools, "MessageLogLevel", {
  4475. get: function () {
  4476. return Tools._MessageLogLevel;
  4477. },
  4478. enumerable: true,
  4479. configurable: true
  4480. });
  4481. Object.defineProperty(Tools, "WarningLogLevel", {
  4482. get: function () {
  4483. return Tools._WarningLogLevel;
  4484. },
  4485. enumerable: true,
  4486. configurable: true
  4487. });
  4488. Object.defineProperty(Tools, "ErrorLogLevel", {
  4489. get: function () {
  4490. return Tools._ErrorLogLevel;
  4491. },
  4492. enumerable: true,
  4493. configurable: true
  4494. });
  4495. Object.defineProperty(Tools, "AllLogLevel", {
  4496. get: function () {
  4497. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4498. },
  4499. enumerable: true,
  4500. configurable: true
  4501. });
  4502. Tools._AddLogEntry = function (entry) {
  4503. Tools._LogCache = entry + Tools._LogCache;
  4504. if (Tools.OnNewCacheEntry) {
  4505. Tools.OnNewCacheEntry(entry);
  4506. }
  4507. };
  4508. Tools._FormatMessage = function (message) {
  4509. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4510. var date = new Date();
  4511. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4512. };
  4513. Tools._LogDisabled = function (message) {
  4514. // nothing to do
  4515. };
  4516. Tools._LogEnabled = function (message) {
  4517. var formattedMessage = Tools._FormatMessage(message);
  4518. console.log("BJS - " + formattedMessage);
  4519. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4520. Tools._AddLogEntry(entry);
  4521. };
  4522. Tools._WarnDisabled = function (message) {
  4523. // nothing to do
  4524. };
  4525. Tools._WarnEnabled = function (message) {
  4526. var formattedMessage = Tools._FormatMessage(message);
  4527. console.warn("BJS - " + formattedMessage);
  4528. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4529. Tools._AddLogEntry(entry);
  4530. };
  4531. Tools._ErrorDisabled = function (message) {
  4532. // nothing to do
  4533. };
  4534. Tools._ErrorEnabled = function (message) {
  4535. Tools.errorsCount++;
  4536. var formattedMessage = Tools._FormatMessage(message);
  4537. console.error("BJS - " + formattedMessage);
  4538. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4539. Tools._AddLogEntry(entry);
  4540. };
  4541. Object.defineProperty(Tools, "LogCache", {
  4542. get: function () {
  4543. return Tools._LogCache;
  4544. },
  4545. enumerable: true,
  4546. configurable: true
  4547. });
  4548. Tools.ClearLogCache = function () {
  4549. Tools._LogCache = "";
  4550. Tools.errorsCount = 0;
  4551. };
  4552. Object.defineProperty(Tools, "LogLevels", {
  4553. set: function (level) {
  4554. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4555. Tools.Log = Tools._LogEnabled;
  4556. }
  4557. else {
  4558. Tools.Log = Tools._LogDisabled;
  4559. }
  4560. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4561. Tools.Warn = Tools._WarnEnabled;
  4562. }
  4563. else {
  4564. Tools.Warn = Tools._WarnDisabled;
  4565. }
  4566. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4567. Tools.Error = Tools._ErrorEnabled;
  4568. }
  4569. else {
  4570. Tools.Error = Tools._ErrorDisabled;
  4571. }
  4572. },
  4573. enumerable: true,
  4574. configurable: true
  4575. });
  4576. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4577. get: function () {
  4578. return Tools._PerformanceNoneLogLevel;
  4579. },
  4580. enumerable: true,
  4581. configurable: true
  4582. });
  4583. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4584. get: function () {
  4585. return Tools._PerformanceUserMarkLogLevel;
  4586. },
  4587. enumerable: true,
  4588. configurable: true
  4589. });
  4590. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4591. get: function () {
  4592. return Tools._PerformanceConsoleLogLevel;
  4593. },
  4594. enumerable: true,
  4595. configurable: true
  4596. });
  4597. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4598. set: function (level) {
  4599. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4600. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4601. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4602. return;
  4603. }
  4604. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4605. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4606. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4607. return;
  4608. }
  4609. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4610. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4611. },
  4612. enumerable: true,
  4613. configurable: true
  4614. });
  4615. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4616. };
  4617. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4618. };
  4619. Tools._StartUserMark = function (counterName, condition) {
  4620. if (condition === void 0) { condition = true; }
  4621. if (!condition || !Tools._performance.mark) {
  4622. return;
  4623. }
  4624. Tools._performance.mark(counterName + "-Begin");
  4625. };
  4626. Tools._EndUserMark = function (counterName, condition) {
  4627. if (condition === void 0) { condition = true; }
  4628. if (!condition || !Tools._performance.mark) {
  4629. return;
  4630. }
  4631. Tools._performance.mark(counterName + "-End");
  4632. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4633. };
  4634. Tools._StartPerformanceConsole = function (counterName, condition) {
  4635. if (condition === void 0) { condition = true; }
  4636. if (!condition) {
  4637. return;
  4638. }
  4639. Tools._StartUserMark(counterName, condition);
  4640. if (console.time) {
  4641. console.time(counterName);
  4642. }
  4643. };
  4644. Tools._EndPerformanceConsole = function (counterName, condition) {
  4645. if (condition === void 0) { condition = true; }
  4646. if (!condition) {
  4647. return;
  4648. }
  4649. Tools._EndUserMark(counterName, condition);
  4650. if (console.time) {
  4651. console.timeEnd(counterName);
  4652. }
  4653. };
  4654. Object.defineProperty(Tools, "Now", {
  4655. get: function () {
  4656. if (window.performance && window.performance.now) {
  4657. return window.performance.now();
  4658. }
  4659. return new Date().getTime();
  4660. },
  4661. enumerable: true,
  4662. configurable: true
  4663. });
  4664. Tools.BaseUrl = "";
  4665. Tools.CorsBehavior = "anonymous";
  4666. // Logs
  4667. Tools._NoneLogLevel = 0;
  4668. Tools._MessageLogLevel = 1;
  4669. Tools._WarningLogLevel = 2;
  4670. Tools._ErrorLogLevel = 4;
  4671. Tools._LogCache = "";
  4672. Tools.errorsCount = 0;
  4673. Tools.Log = Tools._LogEnabled;
  4674. Tools.Warn = Tools._WarnEnabled;
  4675. Tools.Error = Tools._ErrorEnabled;
  4676. // Performances
  4677. Tools._PerformanceNoneLogLevel = 0;
  4678. Tools._PerformanceUserMarkLogLevel = 1;
  4679. Tools._PerformanceConsoleLogLevel = 2;
  4680. Tools._performance = window.performance;
  4681. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4682. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4683. return Tools;
  4684. })();
  4685. BABYLON.Tools = Tools;
  4686. /**
  4687. * An implementation of a loop for asynchronous functions.
  4688. */
  4689. var AsyncLoop = (function () {
  4690. /**
  4691. * Constroctor.
  4692. * @param iterations the number of iterations.
  4693. * @param _fn the function to run each iteration
  4694. * @param _successCallback the callback that will be called upon succesful execution
  4695. * @param offset starting offset.
  4696. */
  4697. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4698. if (offset === void 0) { offset = 0; }
  4699. this.iterations = iterations;
  4700. this._fn = _fn;
  4701. this._successCallback = _successCallback;
  4702. this.index = offset - 1;
  4703. this._done = false;
  4704. }
  4705. /**
  4706. * Execute the next iteration. Must be called after the last iteration was finished.
  4707. */
  4708. AsyncLoop.prototype.executeNext = function () {
  4709. if (!this._done) {
  4710. if (this.index + 1 < this.iterations) {
  4711. ++this.index;
  4712. this._fn(this);
  4713. }
  4714. else {
  4715. this.breakLoop();
  4716. }
  4717. }
  4718. };
  4719. /**
  4720. * Break the loop and run the success callback.
  4721. */
  4722. AsyncLoop.prototype.breakLoop = function () {
  4723. this._done = true;
  4724. this._successCallback();
  4725. };
  4726. /**
  4727. * Helper function
  4728. */
  4729. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4730. if (offset === void 0) { offset = 0; }
  4731. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4732. loop.executeNext();
  4733. return loop;
  4734. };
  4735. /**
  4736. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4737. * @param iterations total number of iterations
  4738. * @param syncedIterations number of synchronous iterations in each async iteration.
  4739. * @param fn the function to call each iteration.
  4740. * @param callback a success call back that will be called when iterating stops.
  4741. * @param breakFunction a break condition (optional)
  4742. * @param timeout timeout settings for the setTimeout function. default - 0.
  4743. * @constructor
  4744. */
  4745. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4746. if (timeout === void 0) { timeout = 0; }
  4747. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4748. if (breakFunction && breakFunction())
  4749. loop.breakLoop();
  4750. else {
  4751. setTimeout(function () {
  4752. for (var i = 0; i < syncedIterations; ++i) {
  4753. var iteration = (loop.index * syncedIterations) + i;
  4754. if (iteration >= iterations)
  4755. break;
  4756. fn(iteration);
  4757. if (breakFunction && breakFunction()) {
  4758. loop.breakLoop();
  4759. break;
  4760. }
  4761. }
  4762. loop.executeNext();
  4763. }, timeout);
  4764. }
  4765. }, callback);
  4766. };
  4767. return AsyncLoop;
  4768. })();
  4769. BABYLON.AsyncLoop = AsyncLoop;
  4770. })(BABYLON || (BABYLON = {}));
  4771. var BABYLON;
  4772. (function (BABYLON) {
  4773. var _DepthCullingState = (function () {
  4774. function _DepthCullingState() {
  4775. this._isDepthTestDirty = false;
  4776. this._isDepthMaskDirty = false;
  4777. this._isDepthFuncDirty = false;
  4778. this._isCullFaceDirty = false;
  4779. this._isCullDirty = false;
  4780. this._isZOffsetDirty = false;
  4781. }
  4782. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4783. get: function () {
  4784. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4785. },
  4786. enumerable: true,
  4787. configurable: true
  4788. });
  4789. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4790. get: function () {
  4791. return this._zOffset;
  4792. },
  4793. set: function (value) {
  4794. if (this._zOffset === value) {
  4795. return;
  4796. }
  4797. this._zOffset = value;
  4798. this._isZOffsetDirty = true;
  4799. },
  4800. enumerable: true,
  4801. configurable: true
  4802. });
  4803. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4804. get: function () {
  4805. return this._cullFace;
  4806. },
  4807. set: function (value) {
  4808. if (this._cullFace === value) {
  4809. return;
  4810. }
  4811. this._cullFace = value;
  4812. this._isCullFaceDirty = true;
  4813. },
  4814. enumerable: true,
  4815. configurable: true
  4816. });
  4817. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4818. get: function () {
  4819. return this._cull;
  4820. },
  4821. set: function (value) {
  4822. if (this._cull === value) {
  4823. return;
  4824. }
  4825. this._cull = value;
  4826. this._isCullDirty = true;
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4832. get: function () {
  4833. return this._depthFunc;
  4834. },
  4835. set: function (value) {
  4836. if (this._depthFunc === value) {
  4837. return;
  4838. }
  4839. this._depthFunc = value;
  4840. this._isDepthFuncDirty = true;
  4841. },
  4842. enumerable: true,
  4843. configurable: true
  4844. });
  4845. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4846. get: function () {
  4847. return this._depthMask;
  4848. },
  4849. set: function (value) {
  4850. if (this._depthMask === value) {
  4851. return;
  4852. }
  4853. this._depthMask = value;
  4854. this._isDepthMaskDirty = true;
  4855. },
  4856. enumerable: true,
  4857. configurable: true
  4858. });
  4859. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4860. get: function () {
  4861. return this._depthTest;
  4862. },
  4863. set: function (value) {
  4864. if (this._depthTest === value) {
  4865. return;
  4866. }
  4867. this._depthTest = value;
  4868. this._isDepthTestDirty = true;
  4869. },
  4870. enumerable: true,
  4871. configurable: true
  4872. });
  4873. _DepthCullingState.prototype.reset = function () {
  4874. this._depthMask = true;
  4875. this._depthTest = true;
  4876. this._depthFunc = null;
  4877. this._cull = null;
  4878. this._cullFace = null;
  4879. this._zOffset = 0;
  4880. this._isDepthTestDirty = true;
  4881. this._isDepthMaskDirty = true;
  4882. this._isDepthFuncDirty = false;
  4883. this._isCullFaceDirty = false;
  4884. this._isCullDirty = false;
  4885. this._isZOffsetDirty = false;
  4886. };
  4887. _DepthCullingState.prototype.apply = function (gl) {
  4888. if (!this.isDirty) {
  4889. return;
  4890. }
  4891. // Cull
  4892. if (this._isCullDirty) {
  4893. if (this.cull) {
  4894. gl.enable(gl.CULL_FACE);
  4895. }
  4896. else {
  4897. gl.disable(gl.CULL_FACE);
  4898. }
  4899. this._isCullDirty = false;
  4900. }
  4901. // Cull face
  4902. if (this._isCullFaceDirty) {
  4903. gl.cullFace(this.cullFace);
  4904. this._isCullFaceDirty = false;
  4905. }
  4906. // Depth mask
  4907. if (this._isDepthMaskDirty) {
  4908. gl.depthMask(this.depthMask);
  4909. this._isDepthMaskDirty = false;
  4910. }
  4911. // Depth test
  4912. if (this._isDepthTestDirty) {
  4913. if (this.depthTest) {
  4914. gl.enable(gl.DEPTH_TEST);
  4915. }
  4916. else {
  4917. gl.disable(gl.DEPTH_TEST);
  4918. }
  4919. this._isDepthTestDirty = false;
  4920. }
  4921. // Depth func
  4922. if (this._isDepthFuncDirty) {
  4923. gl.depthFunc(this.depthFunc);
  4924. this._isDepthFuncDirty = false;
  4925. }
  4926. // zOffset
  4927. if (this._isZOffsetDirty) {
  4928. if (this.zOffset) {
  4929. gl.enable(gl.POLYGON_OFFSET_FILL);
  4930. gl.polygonOffset(this.zOffset, 0);
  4931. }
  4932. else {
  4933. gl.disable(gl.POLYGON_OFFSET_FILL);
  4934. }
  4935. this._isZOffsetDirty = false;
  4936. }
  4937. };
  4938. return _DepthCullingState;
  4939. })();
  4940. BABYLON._DepthCullingState = _DepthCullingState;
  4941. var _AlphaState = (function () {
  4942. function _AlphaState() {
  4943. this._isAlphaBlendDirty = false;
  4944. this._isBlendFunctionParametersDirty = false;
  4945. this._alphaBlend = false;
  4946. this._blendFunctionParameters = new Array(4);
  4947. }
  4948. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4949. get: function () {
  4950. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4951. },
  4952. enumerable: true,
  4953. configurable: true
  4954. });
  4955. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4956. get: function () {
  4957. return this._alphaBlend;
  4958. },
  4959. set: function (value) {
  4960. if (this._alphaBlend === value) {
  4961. return;
  4962. }
  4963. this._alphaBlend = value;
  4964. this._isAlphaBlendDirty = true;
  4965. },
  4966. enumerable: true,
  4967. configurable: true
  4968. });
  4969. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4970. if (this._blendFunctionParameters[0] === value0 &&
  4971. this._blendFunctionParameters[1] === value1 &&
  4972. this._blendFunctionParameters[2] === value2 &&
  4973. this._blendFunctionParameters[3] === value3) {
  4974. return;
  4975. }
  4976. this._blendFunctionParameters[0] = value0;
  4977. this._blendFunctionParameters[1] = value1;
  4978. this._blendFunctionParameters[2] = value2;
  4979. this._blendFunctionParameters[3] = value3;
  4980. this._isBlendFunctionParametersDirty = true;
  4981. };
  4982. _AlphaState.prototype.reset = function () {
  4983. this._alphaBlend = false;
  4984. this._blendFunctionParameters[0] = null;
  4985. this._blendFunctionParameters[1] = null;
  4986. this._blendFunctionParameters[2] = null;
  4987. this._blendFunctionParameters[3] = null;
  4988. this._isAlphaBlendDirty = true;
  4989. this._isBlendFunctionParametersDirty = false;
  4990. };
  4991. _AlphaState.prototype.apply = function (gl) {
  4992. if (!this.isDirty) {
  4993. return;
  4994. }
  4995. // Alpha blend
  4996. if (this._isAlphaBlendDirty) {
  4997. if (this._alphaBlend) {
  4998. gl.enable(gl.BLEND);
  4999. }
  5000. else {
  5001. gl.disable(gl.BLEND);
  5002. }
  5003. this._isAlphaBlendDirty = false;
  5004. }
  5005. // Alpha function
  5006. if (this._isBlendFunctionParametersDirty) {
  5007. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5008. this._isBlendFunctionParametersDirty = false;
  5009. }
  5010. };
  5011. return _AlphaState;
  5012. })();
  5013. BABYLON._AlphaState = _AlphaState;
  5014. var compileShader = function (gl, source, type, defines) {
  5015. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5016. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5017. gl.compileShader(shader);
  5018. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5019. throw new Error(gl.getShaderInfoLog(shader));
  5020. }
  5021. return shader;
  5022. };
  5023. var getWebGLTextureType = function (gl, type) {
  5024. var textureType = gl.UNSIGNED_BYTE;
  5025. if (type === Engine.TEXTURETYPE_FLOAT)
  5026. textureType = gl.FLOAT;
  5027. return textureType;
  5028. };
  5029. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5030. var magFilter = gl.NEAREST;
  5031. var minFilter = gl.NEAREST;
  5032. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5033. magFilter = gl.LINEAR;
  5034. if (generateMipMaps) {
  5035. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5036. }
  5037. else {
  5038. minFilter = gl.LINEAR;
  5039. }
  5040. }
  5041. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5042. magFilter = gl.LINEAR;
  5043. if (generateMipMaps) {
  5044. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5045. }
  5046. else {
  5047. minFilter = gl.LINEAR;
  5048. }
  5049. }
  5050. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5051. magFilter = gl.NEAREST;
  5052. if (generateMipMaps) {
  5053. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5054. }
  5055. else {
  5056. minFilter = gl.NEAREST;
  5057. }
  5058. }
  5059. return {
  5060. min: minFilter,
  5061. mag: magFilter
  5062. };
  5063. };
  5064. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5066. var engine = scene.getEngine();
  5067. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5068. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5069. gl.bindTexture(gl.TEXTURE_2D, texture);
  5070. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5071. texture._baseWidth = width;
  5072. texture._baseHeight = height;
  5073. texture._width = potWidth;
  5074. texture._height = potHeight;
  5075. texture.isReady = true;
  5076. processFunction(potWidth, potHeight);
  5077. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5080. if (!noMipmap && !isCompressed) {
  5081. gl.generateMipmap(gl.TEXTURE_2D);
  5082. }
  5083. gl.bindTexture(gl.TEXTURE_2D, null);
  5084. engine.resetTextureCache();
  5085. scene._removePendingData(texture);
  5086. };
  5087. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5088. var img;
  5089. var onload = function () {
  5090. loadedImages[index] = img;
  5091. loadedImages._internalCount++;
  5092. scene._removePendingData(img);
  5093. if (loadedImages._internalCount === 6) {
  5094. onfinish(loadedImages);
  5095. }
  5096. };
  5097. var onerror = function () {
  5098. scene._removePendingData(img);
  5099. };
  5100. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5101. scene._addPendingData(img);
  5102. };
  5103. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5104. var loadedImages = [];
  5105. loadedImages._internalCount = 0;
  5106. for (var index = 0; index < 6; index++) {
  5107. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5108. }
  5109. };
  5110. var EngineCapabilities = (function () {
  5111. function EngineCapabilities() {
  5112. }
  5113. return EngineCapabilities;
  5114. })();
  5115. BABYLON.EngineCapabilities = EngineCapabilities;
  5116. /**
  5117. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5118. */
  5119. var Engine = (function () {
  5120. /**
  5121. * @constructor
  5122. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5123. * @param {boolean} [antialias] - enable antialias
  5124. * @param options - further options to be sent to the getContext function
  5125. */
  5126. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5127. var _this = this;
  5128. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5129. // Public members
  5130. this.isFullscreen = false;
  5131. this.isPointerLock = false;
  5132. this.cullBackFaces = true;
  5133. this.renderEvenInBackground = true;
  5134. // To enable/disable IDB support and avoid XHR on .manifest
  5135. this.enableOfflineSupport = true;
  5136. this.scenes = new Array();
  5137. this._windowIsBackground = false;
  5138. this._drawCalls = 0;
  5139. this._renderingQueueLaunched = false;
  5140. this._activeRenderLoops = [];
  5141. // FPS
  5142. this.fpsRange = 60;
  5143. this.previousFramesDuration = [];
  5144. this.fps = 60;
  5145. this.deltaTime = 0;
  5146. // States
  5147. this._depthCullingState = new _DepthCullingState();
  5148. this._alphaState = new _AlphaState();
  5149. this._alphaMode = Engine.ALPHA_DISABLE;
  5150. // Cache
  5151. this._loadedTexturesCache = new Array();
  5152. this._maxTextureChannels = 16;
  5153. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5154. this._compiledEffects = {};
  5155. this._uintIndicesCurrentlySet = false;
  5156. this._renderingCanvas = canvas;
  5157. options = options || {};
  5158. options.antialias = antialias;
  5159. if (options.preserveDrawingBuffer === undefined) {
  5160. options.preserveDrawingBuffer = false;
  5161. }
  5162. // GL
  5163. try {
  5164. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5165. }
  5166. catch (e) {
  5167. throw new Error("WebGL not supported");
  5168. }
  5169. if (!this._gl) {
  5170. throw new Error("WebGL not supported");
  5171. }
  5172. this._onBlur = function () {
  5173. _this._windowIsBackground = true;
  5174. };
  5175. this._onFocus = function () {
  5176. _this._windowIsBackground = false;
  5177. };
  5178. window.addEventListener("blur", this._onBlur);
  5179. window.addEventListener("focus", this._onFocus);
  5180. // Viewport
  5181. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5182. this.resize();
  5183. // Caps
  5184. this._caps = new EngineCapabilities();
  5185. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5186. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5187. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5188. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5189. // Infos
  5190. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5191. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5192. if (rendererInfo != null) {
  5193. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5194. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5195. }
  5196. if (!this._glVendor) {
  5197. this._glVendor = "Unknown vendor";
  5198. }
  5199. if (!this._glRenderer) {
  5200. this._glRenderer = "Unknown renderer";
  5201. }
  5202. // Extensions
  5203. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5204. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5205. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5206. 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');
  5207. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5208. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5209. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5210. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5211. this._caps.highPrecisionShaderSupported = true;
  5212. if (this._gl.getShaderPrecisionFormat) {
  5213. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5214. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5215. }
  5216. // Depth buffer
  5217. this.setDepthBuffer(true);
  5218. this.setDepthFunctionToLessOrEqual();
  5219. this.setDepthWrite(true);
  5220. // Fullscreen
  5221. this._onFullscreenChange = function () {
  5222. if (document.fullscreen !== undefined) {
  5223. _this.isFullscreen = document.fullscreen;
  5224. }
  5225. else if (document.mozFullScreen !== undefined) {
  5226. _this.isFullscreen = document.mozFullScreen;
  5227. }
  5228. else if (document.webkitIsFullScreen !== undefined) {
  5229. _this.isFullscreen = document.webkitIsFullScreen;
  5230. }
  5231. else if (document.msIsFullScreen !== undefined) {
  5232. _this.isFullscreen = document.msIsFullScreen;
  5233. }
  5234. // Pointer lock
  5235. if (_this.isFullscreen && _this._pointerLockRequested) {
  5236. canvas.requestPointerLock = canvas.requestPointerLock ||
  5237. canvas.msRequestPointerLock ||
  5238. canvas.mozRequestPointerLock ||
  5239. canvas.webkitRequestPointerLock;
  5240. if (canvas.requestPointerLock) {
  5241. canvas.requestPointerLock();
  5242. }
  5243. }
  5244. };
  5245. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5246. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5247. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5248. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5249. // Pointer lock
  5250. this._onPointerLockChange = function () {
  5251. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5252. document.webkitPointerLockElement === canvas ||
  5253. document.msPointerLockElement === canvas ||
  5254. document.pointerLockElement === canvas);
  5255. };
  5256. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5257. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5258. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5259. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5260. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5261. Engine.audioEngine = new BABYLON.AudioEngine();
  5262. }
  5263. //default loading screen
  5264. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5265. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5266. }
  5267. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5268. get: function () {
  5269. return Engine._ALPHA_DISABLE;
  5270. },
  5271. enumerable: true,
  5272. configurable: true
  5273. });
  5274. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5275. get: function () {
  5276. return Engine._ALPHA_ONEONE;
  5277. },
  5278. enumerable: true,
  5279. configurable: true
  5280. });
  5281. Object.defineProperty(Engine, "ALPHA_ADD", {
  5282. get: function () {
  5283. return Engine._ALPHA_ADD;
  5284. },
  5285. enumerable: true,
  5286. configurable: true
  5287. });
  5288. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5289. get: function () {
  5290. return Engine._ALPHA_COMBINE;
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5296. get: function () {
  5297. return Engine._ALPHA_SUBTRACT;
  5298. },
  5299. enumerable: true,
  5300. configurable: true
  5301. });
  5302. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5303. get: function () {
  5304. return Engine._ALPHA_MULTIPLY;
  5305. },
  5306. enumerable: true,
  5307. configurable: true
  5308. });
  5309. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5310. get: function () {
  5311. return Engine._ALPHA_MAXIMIZED;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5317. get: function () {
  5318. return Engine._DELAYLOADSTATE_NONE;
  5319. },
  5320. enumerable: true,
  5321. configurable: true
  5322. });
  5323. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5324. get: function () {
  5325. return Engine._DELAYLOADSTATE_LOADED;
  5326. },
  5327. enumerable: true,
  5328. configurable: true
  5329. });
  5330. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5331. get: function () {
  5332. return Engine._DELAYLOADSTATE_LOADING;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5338. get: function () {
  5339. return Engine._DELAYLOADSTATE_NOTLOADED;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5345. get: function () {
  5346. return Engine._TEXTUREFORMAT_ALPHA;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5352. get: function () {
  5353. return Engine._TEXTUREFORMAT_LUMINANCE;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5359. get: function () {
  5360. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5361. },
  5362. enumerable: true,
  5363. configurable: true
  5364. });
  5365. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5366. get: function () {
  5367. return Engine._TEXTUREFORMAT_RGB;
  5368. },
  5369. enumerable: true,
  5370. configurable: true
  5371. });
  5372. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5373. get: function () {
  5374. return Engine._TEXTUREFORMAT_RGBA;
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5380. get: function () {
  5381. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5387. get: function () {
  5388. return Engine._TEXTURETYPE_FLOAT;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Engine, "Version", {
  5394. get: function () {
  5395. return "2.3.0-alpha";
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Engine.prototype._prepareWorkingCanvas = function () {
  5401. if (this._workingCanvas) {
  5402. return;
  5403. }
  5404. this._workingCanvas = document.createElement("canvas");
  5405. this._workingContext = this._workingCanvas.getContext("2d");
  5406. };
  5407. Engine.prototype.resetTextureCache = function () {
  5408. for (var index = 0; index < this._maxTextureChannels; index++) {
  5409. this._activeTexturesCache[index] = null;
  5410. }
  5411. };
  5412. Engine.prototype.getGlInfo = function () {
  5413. return {
  5414. vendor: this._glVendor,
  5415. renderer: this._glRenderer,
  5416. version: this._glVersion
  5417. };
  5418. };
  5419. Engine.prototype.getAspectRatio = function (camera) {
  5420. var viewport = camera.viewport;
  5421. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5422. };
  5423. Engine.prototype.getRenderWidth = function () {
  5424. if (this._currentRenderTarget) {
  5425. return this._currentRenderTarget._width;
  5426. }
  5427. return this._renderingCanvas.width;
  5428. };
  5429. Engine.prototype.getRenderHeight = function () {
  5430. if (this._currentRenderTarget) {
  5431. return this._currentRenderTarget._height;
  5432. }
  5433. return this._renderingCanvas.height;
  5434. };
  5435. Engine.prototype.getRenderingCanvas = function () {
  5436. return this._renderingCanvas;
  5437. };
  5438. Engine.prototype.getRenderingCanvasClientRect = function () {
  5439. return this._renderingCanvas.getBoundingClientRect();
  5440. };
  5441. Engine.prototype.setHardwareScalingLevel = function (level) {
  5442. this._hardwareScalingLevel = level;
  5443. this.resize();
  5444. };
  5445. Engine.prototype.getHardwareScalingLevel = function () {
  5446. return this._hardwareScalingLevel;
  5447. };
  5448. Engine.prototype.getLoadedTexturesCache = function () {
  5449. return this._loadedTexturesCache;
  5450. };
  5451. Engine.prototype.getCaps = function () {
  5452. return this._caps;
  5453. };
  5454. Object.defineProperty(Engine.prototype, "drawCalls", {
  5455. get: function () {
  5456. return this._drawCalls;
  5457. },
  5458. enumerable: true,
  5459. configurable: true
  5460. });
  5461. // Methods
  5462. Engine.prototype.resetDrawCalls = function () {
  5463. this._drawCalls = 0;
  5464. };
  5465. Engine.prototype.setDepthFunctionToGreater = function () {
  5466. this._depthCullingState.depthFunc = this._gl.GREATER;
  5467. };
  5468. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5469. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5470. };
  5471. Engine.prototype.setDepthFunctionToLess = function () {
  5472. this._depthCullingState.depthFunc = this._gl.LESS;
  5473. };
  5474. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5475. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5476. };
  5477. /**
  5478. * stop executing a render loop function and remove it from the execution array
  5479. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5480. */
  5481. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5482. if (!renderFunction) {
  5483. this._activeRenderLoops = [];
  5484. return;
  5485. }
  5486. var index = this._activeRenderLoops.indexOf(renderFunction);
  5487. if (index >= 0) {
  5488. this._activeRenderLoops.splice(index, 1);
  5489. }
  5490. };
  5491. Engine.prototype._renderLoop = function () {
  5492. var shouldRender = true;
  5493. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5494. shouldRender = false;
  5495. }
  5496. if (shouldRender) {
  5497. // Start new frame
  5498. this.beginFrame();
  5499. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5500. var renderFunction = this._activeRenderLoops[index];
  5501. renderFunction();
  5502. }
  5503. // Present
  5504. this.endFrame();
  5505. }
  5506. if (this._activeRenderLoops.length > 0) {
  5507. // Register new frame
  5508. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5509. }
  5510. else {
  5511. this._renderingQueueLaunched = false;
  5512. }
  5513. };
  5514. /**
  5515. * Register and execute a render loop. The engine can have more than one render function.
  5516. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5517. * @example
  5518. * engine.runRenderLoop(function () {
  5519. * scene.render()
  5520. * })
  5521. */
  5522. Engine.prototype.runRenderLoop = function (renderFunction) {
  5523. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5524. return;
  5525. }
  5526. this._activeRenderLoops.push(renderFunction);
  5527. if (!this._renderingQueueLaunched) {
  5528. this._renderingQueueLaunched = true;
  5529. this._bindedRenderFunction = this._renderLoop.bind(this);
  5530. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5531. }
  5532. };
  5533. /**
  5534. * Toggle full screen mode.
  5535. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5536. */
  5537. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5538. if (this.isFullscreen) {
  5539. BABYLON.Tools.ExitFullscreen();
  5540. }
  5541. else {
  5542. this._pointerLockRequested = requestPointerLock;
  5543. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5544. }
  5545. };
  5546. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5547. this.applyStates();
  5548. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5549. if (this._depthCullingState.depthMask) {
  5550. this._gl.clearDepth(1.0);
  5551. }
  5552. var mode = 0;
  5553. if (backBuffer)
  5554. mode |= this._gl.COLOR_BUFFER_BIT;
  5555. if (depthStencil && this._depthCullingState.depthMask)
  5556. mode |= this._gl.DEPTH_BUFFER_BIT;
  5557. this._gl.clear(mode);
  5558. };
  5559. /**
  5560. * Set the WebGL's viewport
  5561. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5562. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5563. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5564. */
  5565. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5566. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5567. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5568. var x = viewport.x || 0;
  5569. var y = viewport.y || 0;
  5570. this._cachedViewport = viewport;
  5571. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5572. };
  5573. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5574. this._cachedViewport = null;
  5575. this._gl.viewport(x, y, width, height);
  5576. };
  5577. Engine.prototype.beginFrame = function () {
  5578. this._measureFps();
  5579. };
  5580. Engine.prototype.endFrame = function () {
  5581. //this.flushFramebuffer();
  5582. };
  5583. /**
  5584. * resize the view according to the canvas' size.
  5585. * @example
  5586. * window.addEventListener("resize", function () {
  5587. * engine.resize();
  5588. * });
  5589. */
  5590. Engine.prototype.resize = function () {
  5591. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5592. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5593. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5594. for (var index = 0; index < this.scenes.length; index++) {
  5595. var scene = this.scenes[index];
  5596. if (scene.debugLayer.isVisible()) {
  5597. scene.debugLayer._syncPositions();
  5598. }
  5599. }
  5600. };
  5601. /**
  5602. * force a specific size of the canvas
  5603. * @param {number} width - the new canvas' width
  5604. * @param {number} height - the new canvas' height
  5605. */
  5606. Engine.prototype.setSize = function (width, height) {
  5607. this._renderingCanvas.width = width;
  5608. this._renderingCanvas.height = height;
  5609. for (var index = 0; index < this.scenes.length; index++) {
  5610. var scene = this.scenes[index];
  5611. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5612. var cam = scene.cameras[camIndex];
  5613. cam._currentRenderId = 0;
  5614. }
  5615. }
  5616. };
  5617. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5618. this._currentRenderTarget = texture;
  5619. var gl = this._gl;
  5620. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5621. if (texture.isCube) {
  5622. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5623. }
  5624. else {
  5625. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5626. }
  5627. this._gl.viewport(0, 0, texture._width, texture._height);
  5628. this.wipeCaches();
  5629. };
  5630. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5631. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5632. this._currentRenderTarget = null;
  5633. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5634. var gl = this._gl;
  5635. gl.bindTexture(gl.TEXTURE_2D, texture);
  5636. gl.generateMipmap(gl.TEXTURE_2D);
  5637. gl.bindTexture(gl.TEXTURE_2D, null);
  5638. }
  5639. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5640. };
  5641. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5642. if (texture.generateMipMaps) {
  5643. var gl = this._gl;
  5644. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5645. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5646. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5647. }
  5648. };
  5649. Engine.prototype.flushFramebuffer = function () {
  5650. this._gl.flush();
  5651. };
  5652. Engine.prototype.restoreDefaultFramebuffer = function () {
  5653. this._currentRenderTarget = null;
  5654. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5655. this.setViewport(this._cachedViewport);
  5656. this.wipeCaches();
  5657. };
  5658. // VBOs
  5659. Engine.prototype._resetVertexBufferBinding = function () {
  5660. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5661. this._cachedVertexBuffers = null;
  5662. };
  5663. Engine.prototype.createVertexBuffer = function (vertices) {
  5664. var vbo = this._gl.createBuffer();
  5665. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5666. if (vertices instanceof Float32Array) {
  5667. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5668. }
  5669. else {
  5670. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5671. }
  5672. this._resetVertexBufferBinding();
  5673. vbo.references = 1;
  5674. return vbo;
  5675. };
  5676. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5677. var vbo = this._gl.createBuffer();
  5678. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5679. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5680. this._resetVertexBufferBinding();
  5681. vbo.references = 1;
  5682. return vbo;
  5683. };
  5684. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5685. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5686. if (offset === undefined) {
  5687. offset = 0;
  5688. }
  5689. if (vertices instanceof Float32Array) {
  5690. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5691. }
  5692. else {
  5693. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5694. }
  5695. this._resetVertexBufferBinding();
  5696. };
  5697. Engine.prototype._resetIndexBufferBinding = function () {
  5698. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5699. this._cachedIndexBuffer = null;
  5700. };
  5701. Engine.prototype.createIndexBuffer = function (indices) {
  5702. var vbo = this._gl.createBuffer();
  5703. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5704. // Check for 32 bits indices
  5705. var arrayBuffer;
  5706. var need32Bits = false;
  5707. if (this._caps.uintIndices) {
  5708. for (var index = 0; index < indices.length; index++) {
  5709. if (indices[index] > 65535) {
  5710. need32Bits = true;
  5711. break;
  5712. }
  5713. }
  5714. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5715. }
  5716. else {
  5717. arrayBuffer = new Uint16Array(indices);
  5718. }
  5719. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5720. this._resetIndexBufferBinding();
  5721. vbo.references = 1;
  5722. vbo.is32Bits = need32Bits;
  5723. return vbo;
  5724. };
  5725. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5726. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5727. this._cachedVertexBuffers = vertexBuffer;
  5728. this._cachedEffectForVertexBuffers = effect;
  5729. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5730. var offset = 0;
  5731. for (var index = 0; index < vertexDeclaration.length; index++) {
  5732. var order = effect.getAttributeLocation(index);
  5733. if (order >= 0) {
  5734. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5735. }
  5736. offset += vertexDeclaration[index] * 4;
  5737. }
  5738. }
  5739. if (this._cachedIndexBuffer !== indexBuffer) {
  5740. this._cachedIndexBuffer = indexBuffer;
  5741. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5742. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5743. }
  5744. };
  5745. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5746. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5747. this._cachedVertexBuffers = vertexBuffers;
  5748. this._cachedEffectForVertexBuffers = effect;
  5749. var attributes = effect.getAttributesNames();
  5750. for (var index = 0; index < attributes.length; index++) {
  5751. var order = effect.getAttributeLocation(index);
  5752. if (order >= 0) {
  5753. var vertexBuffer = vertexBuffers[attributes[index]];
  5754. if (!vertexBuffer) {
  5755. continue;
  5756. }
  5757. var stride = vertexBuffer.getStrideSize();
  5758. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5759. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5760. }
  5761. }
  5762. }
  5763. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5764. this._cachedIndexBuffer = indexBuffer;
  5765. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5766. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5767. }
  5768. };
  5769. Engine.prototype._releaseBuffer = function (buffer) {
  5770. buffer.references--;
  5771. if (buffer.references === 0) {
  5772. this._gl.deleteBuffer(buffer);
  5773. return true;
  5774. }
  5775. return false;
  5776. };
  5777. Engine.prototype.createInstancesBuffer = function (capacity) {
  5778. var buffer = this._gl.createBuffer();
  5779. buffer.capacity = capacity;
  5780. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5781. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5782. return buffer;
  5783. };
  5784. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5785. this._gl.deleteBuffer(buffer);
  5786. };
  5787. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5788. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5789. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5790. for (var index = 0; index < 4; index++) {
  5791. var offsetLocation = offsetLocations[index];
  5792. this._gl.enableVertexAttribArray(offsetLocation);
  5793. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5794. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5795. }
  5796. };
  5797. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5798. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5799. for (var index = 0; index < 4; index++) {
  5800. var offsetLocation = offsetLocations[index];
  5801. this._gl.disableVertexAttribArray(offsetLocation);
  5802. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5803. }
  5804. };
  5805. Engine.prototype.applyStates = function () {
  5806. this._depthCullingState.apply(this._gl);
  5807. this._alphaState.apply(this._gl);
  5808. };
  5809. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5810. // Apply states
  5811. this.applyStates();
  5812. this._drawCalls++;
  5813. // Render
  5814. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5815. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5816. if (instancesCount) {
  5817. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5818. return;
  5819. }
  5820. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5821. };
  5822. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5823. // Apply states
  5824. this.applyStates();
  5825. this._drawCalls++;
  5826. if (instancesCount) {
  5827. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5828. return;
  5829. }
  5830. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5831. };
  5832. // Shaders
  5833. Engine.prototype._releaseEffect = function (effect) {
  5834. if (this._compiledEffects[effect._key]) {
  5835. delete this._compiledEffects[effect._key];
  5836. if (effect.getProgram()) {
  5837. this._gl.deleteProgram(effect.getProgram());
  5838. }
  5839. }
  5840. };
  5841. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5842. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5843. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5844. var name = vertex + "+" + fragment + "@" + defines;
  5845. if (this._compiledEffects[name]) {
  5846. return this._compiledEffects[name];
  5847. }
  5848. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5849. effect._key = name;
  5850. this._compiledEffects[name] = effect;
  5851. return effect;
  5852. };
  5853. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5854. if (uniformsNames === void 0) { uniformsNames = []; }
  5855. if (samplers === void 0) { samplers = []; }
  5856. if (defines === void 0) { defines = ""; }
  5857. return this.createEffect({
  5858. vertex: "particles",
  5859. fragmentElement: fragmentName
  5860. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5861. };
  5862. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5863. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5864. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5865. var shaderProgram = this._gl.createProgram();
  5866. this._gl.attachShader(shaderProgram, vertexShader);
  5867. this._gl.attachShader(shaderProgram, fragmentShader);
  5868. this._gl.linkProgram(shaderProgram);
  5869. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5870. if (!linked) {
  5871. var error = this._gl.getProgramInfoLog(shaderProgram);
  5872. if (error) {
  5873. throw new Error(error);
  5874. }
  5875. }
  5876. this._gl.deleteShader(vertexShader);
  5877. this._gl.deleteShader(fragmentShader);
  5878. return shaderProgram;
  5879. };
  5880. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5881. var results = [];
  5882. for (var index = 0; index < uniformsNames.length; index++) {
  5883. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5884. }
  5885. return results;
  5886. };
  5887. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5888. var results = [];
  5889. for (var index = 0; index < attributesNames.length; index++) {
  5890. try {
  5891. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5892. }
  5893. catch (e) {
  5894. results.push(-1);
  5895. }
  5896. }
  5897. return results;
  5898. };
  5899. Engine.prototype.enableEffect = function (effect) {
  5900. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5901. if (effect && effect.onBind) {
  5902. effect.onBind(effect);
  5903. }
  5904. return;
  5905. }
  5906. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5907. // Use program
  5908. this._gl.useProgram(effect.getProgram());
  5909. for (var i in this._vertexAttribArrays) {
  5910. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5911. continue;
  5912. }
  5913. this._vertexAttribArrays[i] = false;
  5914. this._gl.disableVertexAttribArray(i);
  5915. }
  5916. var attributesCount = effect.getAttributesCount();
  5917. for (var index = 0; index < attributesCount; index++) {
  5918. // Attributes
  5919. var order = effect.getAttributeLocation(index);
  5920. if (order >= 0) {
  5921. this._vertexAttribArrays[order] = true;
  5922. this._gl.enableVertexAttribArray(order);
  5923. }
  5924. }
  5925. this._currentEffect = effect;
  5926. if (effect.onBind) {
  5927. effect.onBind(effect);
  5928. }
  5929. };
  5930. Engine.prototype.setArray = function (uniform, array) {
  5931. if (!uniform)
  5932. return;
  5933. this._gl.uniform1fv(uniform, array);
  5934. };
  5935. Engine.prototype.setArray2 = function (uniform, array) {
  5936. if (!uniform || array.length % 2 !== 0)
  5937. return;
  5938. this._gl.uniform2fv(uniform, array);
  5939. };
  5940. Engine.prototype.setArray3 = function (uniform, array) {
  5941. if (!uniform || array.length % 3 !== 0)
  5942. return;
  5943. this._gl.uniform3fv(uniform, array);
  5944. };
  5945. Engine.prototype.setArray4 = function (uniform, array) {
  5946. if (!uniform || array.length % 4 !== 0)
  5947. return;
  5948. this._gl.uniform4fv(uniform, array);
  5949. };
  5950. Engine.prototype.setMatrices = function (uniform, matrices) {
  5951. if (!uniform)
  5952. return;
  5953. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5954. };
  5955. Engine.prototype.setMatrix = function (uniform, matrix) {
  5956. if (!uniform)
  5957. return;
  5958. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5959. };
  5960. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5961. if (!uniform)
  5962. return;
  5963. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5964. };
  5965. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5966. if (!uniform)
  5967. return;
  5968. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5969. };
  5970. Engine.prototype.setFloat = function (uniform, value) {
  5971. if (!uniform)
  5972. return;
  5973. this._gl.uniform1f(uniform, value);
  5974. };
  5975. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5976. if (!uniform)
  5977. return;
  5978. this._gl.uniform2f(uniform, x, y);
  5979. };
  5980. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5981. if (!uniform)
  5982. return;
  5983. this._gl.uniform3f(uniform, x, y, z);
  5984. };
  5985. Engine.prototype.setBool = function (uniform, bool) {
  5986. if (!uniform)
  5987. return;
  5988. this._gl.uniform1i(uniform, bool);
  5989. };
  5990. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5991. if (!uniform)
  5992. return;
  5993. this._gl.uniform4f(uniform, x, y, z, w);
  5994. };
  5995. Engine.prototype.setColor3 = function (uniform, color3) {
  5996. if (!uniform)
  5997. return;
  5998. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5999. };
  6000. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6001. if (!uniform)
  6002. return;
  6003. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6004. };
  6005. // States
  6006. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6007. if (zOffset === void 0) { zOffset = 0; }
  6008. if (reverseSide === void 0) { reverseSide = false; }
  6009. // Culling
  6010. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6011. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6012. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6013. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6014. if (culling) {
  6015. this._depthCullingState.cullFace = cullFace;
  6016. this._depthCullingState.cull = true;
  6017. }
  6018. else {
  6019. this._depthCullingState.cull = false;
  6020. }
  6021. }
  6022. // Z offset
  6023. this._depthCullingState.zOffset = zOffset;
  6024. };
  6025. Engine.prototype.setDepthBuffer = function (enable) {
  6026. this._depthCullingState.depthTest = enable;
  6027. };
  6028. Engine.prototype.getDepthWrite = function () {
  6029. return this._depthCullingState.depthMask;
  6030. };
  6031. Engine.prototype.setDepthWrite = function (enable) {
  6032. this._depthCullingState.depthMask = enable;
  6033. };
  6034. Engine.prototype.setColorWrite = function (enable) {
  6035. this._gl.colorMask(enable, enable, enable, enable);
  6036. };
  6037. Engine.prototype.setAlphaMode = function (mode) {
  6038. if (this._alphaMode === mode) {
  6039. return;
  6040. }
  6041. switch (mode) {
  6042. case Engine.ALPHA_DISABLE:
  6043. this.setDepthWrite(true);
  6044. this._alphaState.alphaBlend = false;
  6045. break;
  6046. case Engine.ALPHA_COMBINE:
  6047. this.setDepthWrite(false);
  6048. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6049. this._alphaState.alphaBlend = true;
  6050. break;
  6051. case Engine.ALPHA_ONEONE:
  6052. this.setDepthWrite(false);
  6053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6054. this._alphaState.alphaBlend = true;
  6055. break;
  6056. case Engine.ALPHA_ADD:
  6057. this.setDepthWrite(false);
  6058. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6059. this._alphaState.alphaBlend = true;
  6060. break;
  6061. case Engine.ALPHA_SUBTRACT:
  6062. this.setDepthWrite(false);
  6063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6064. this._alphaState.alphaBlend = true;
  6065. break;
  6066. case Engine.ALPHA_MULTIPLY:
  6067. this.setDepthWrite(false);
  6068. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6069. this._alphaState.alphaBlend = true;
  6070. break;
  6071. case Engine.ALPHA_MAXIMIZED:
  6072. this.setDepthWrite(false);
  6073. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6074. this._alphaState.alphaBlend = true;
  6075. break;
  6076. }
  6077. this._alphaMode = mode;
  6078. };
  6079. Engine.prototype.getAlphaMode = function () {
  6080. return this._alphaMode;
  6081. };
  6082. Engine.prototype.setAlphaTesting = function (enable) {
  6083. this._alphaTest = enable;
  6084. };
  6085. Engine.prototype.getAlphaTesting = function () {
  6086. return this._alphaTest;
  6087. };
  6088. // Textures
  6089. Engine.prototype.wipeCaches = function () {
  6090. this.resetTextureCache();
  6091. this._currentEffect = null;
  6092. this._depthCullingState.reset();
  6093. this._alphaState.reset();
  6094. this._cachedVertexBuffers = null;
  6095. this._cachedIndexBuffer = null;
  6096. this._cachedEffectForVertexBuffers = null;
  6097. };
  6098. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6099. var gl = this._gl;
  6100. gl.bindTexture(gl.TEXTURE_2D, texture);
  6101. var magFilter = gl.NEAREST;
  6102. var minFilter = gl.NEAREST;
  6103. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6104. magFilter = gl.LINEAR;
  6105. minFilter = gl.LINEAR;
  6106. }
  6107. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6108. magFilter = gl.LINEAR;
  6109. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6110. }
  6111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6113. gl.bindTexture(gl.TEXTURE_2D, null);
  6114. texture.samplingMode = samplingMode;
  6115. };
  6116. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6117. var _this = this;
  6118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6119. if (onLoad === void 0) { onLoad = null; }
  6120. if (onError === void 0) { onError = null; }
  6121. if (buffer === void 0) { buffer = null; }
  6122. var texture = this._gl.createTexture();
  6123. var extension;
  6124. var fromData = false;
  6125. if (url.substr(0, 5) === "data:") {
  6126. fromData = true;
  6127. }
  6128. if (!fromData)
  6129. extension = url.substr(url.length - 4, 4).toLowerCase();
  6130. else {
  6131. var oldUrl = url;
  6132. fromData = oldUrl.split(':');
  6133. url = oldUrl;
  6134. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6135. }
  6136. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6137. var isTGA = (extension === ".tga");
  6138. scene._addPendingData(texture);
  6139. texture.url = url;
  6140. texture.noMipmap = noMipmap;
  6141. texture.references = 1;
  6142. texture.samplingMode = samplingMode;
  6143. this._loadedTexturesCache.push(texture);
  6144. var onerror = function () {
  6145. scene._removePendingData(texture);
  6146. if (onError) {
  6147. onError();
  6148. }
  6149. };
  6150. var callback;
  6151. if (isTGA) {
  6152. callback = function (arrayBuffer) {
  6153. var data = new Uint8Array(arrayBuffer);
  6154. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6155. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6156. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6157. if (onLoad) {
  6158. onLoad();
  6159. }
  6160. }, samplingMode);
  6161. };
  6162. if (!(fromData instanceof Array))
  6163. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6164. callback(arrayBuffer);
  6165. }, onerror, scene.database, true);
  6166. else
  6167. callback(buffer);
  6168. }
  6169. else if (isDDS) {
  6170. callback = function (data) {
  6171. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6172. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6173. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6174. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6175. if (onLoad) {
  6176. onLoad();
  6177. }
  6178. }, samplingMode);
  6179. };
  6180. if (!(fromData instanceof Array))
  6181. BABYLON.Tools.LoadFile(url, function (data) {
  6182. callback(data);
  6183. }, onerror, scene.database, true);
  6184. else
  6185. callback(buffer);
  6186. }
  6187. else {
  6188. var onload = function (img) {
  6189. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6190. var isPot = (img.width === potWidth && img.height === potHeight);
  6191. if (!isPot) {
  6192. _this._prepareWorkingCanvas();
  6193. _this._workingCanvas.width = potWidth;
  6194. _this._workingCanvas.height = potHeight;
  6195. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6196. _this._workingContext.imageSmoothingEnabled = false;
  6197. _this._workingContext.mozImageSmoothingEnabled = false;
  6198. _this._workingContext.oImageSmoothingEnabled = false;
  6199. _this._workingContext.webkitImageSmoothingEnabled = false;
  6200. _this._workingContext.msImageSmoothingEnabled = false;
  6201. }
  6202. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6203. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6204. _this._workingContext.imageSmoothingEnabled = true;
  6205. _this._workingContext.mozImageSmoothingEnabled = true;
  6206. _this._workingContext.oImageSmoothingEnabled = true;
  6207. _this._workingContext.webkitImageSmoothingEnabled = true;
  6208. _this._workingContext.msImageSmoothingEnabled = true;
  6209. }
  6210. }
  6211. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6212. if (onLoad) {
  6213. onLoad();
  6214. }
  6215. }, samplingMode);
  6216. };
  6217. if (!(fromData instanceof Array))
  6218. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6219. else
  6220. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6221. }
  6222. return texture;
  6223. };
  6224. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6225. if (compression === void 0) { compression = null; }
  6226. var internalFormat = this._gl.RGBA;
  6227. switch (format) {
  6228. case Engine.TEXTUREFORMAT_ALPHA:
  6229. internalFormat = this._gl.ALPHA;
  6230. break;
  6231. case Engine.TEXTUREFORMAT_LUMINANCE:
  6232. internalFormat = this._gl.LUMINANCE;
  6233. break;
  6234. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6235. internalFormat = this._gl.LUMINANCE_ALPHA;
  6236. break;
  6237. case Engine.TEXTUREFORMAT_RGB:
  6238. internalFormat = this._gl.RGB;
  6239. break;
  6240. case Engine.TEXTUREFORMAT_RGBA:
  6241. internalFormat = this._gl.RGBA;
  6242. break;
  6243. }
  6244. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6245. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6246. if (compression) {
  6247. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6248. }
  6249. else {
  6250. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6251. }
  6252. if (texture.generateMipMaps) {
  6253. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6254. }
  6255. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6256. this.resetTextureCache();
  6257. texture.isReady = true;
  6258. };
  6259. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6260. if (compression === void 0) { compression = null; }
  6261. var texture = this._gl.createTexture();
  6262. texture._baseWidth = width;
  6263. texture._baseHeight = height;
  6264. texture._width = width;
  6265. texture._height = height;
  6266. texture.references = 1;
  6267. this.updateRawTexture(texture, data, format, invertY, compression);
  6268. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6269. // Filters
  6270. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6273. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6274. texture.samplingMode = samplingMode;
  6275. this._loadedTexturesCache.push(texture);
  6276. return texture;
  6277. };
  6278. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6279. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6280. var texture = this._gl.createTexture();
  6281. texture._baseWidth = width;
  6282. texture._baseHeight = height;
  6283. if (forceExponantOfTwo) {
  6284. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6285. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6286. }
  6287. this.resetTextureCache();
  6288. texture._width = width;
  6289. texture._height = height;
  6290. texture.isReady = false;
  6291. texture.generateMipMaps = generateMipMaps;
  6292. texture.references = 1;
  6293. texture.samplingMode = samplingMode;
  6294. this.updateTextureSamplingMode(samplingMode, texture);
  6295. this._loadedTexturesCache.push(texture);
  6296. return texture;
  6297. };
  6298. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6299. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6300. if (texture.isCube) {
  6301. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6302. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6303. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6304. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6305. }
  6306. else {
  6307. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6310. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6311. }
  6312. };
  6313. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6314. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6315. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6316. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6317. if (texture.generateMipMaps) {
  6318. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6319. }
  6320. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6321. this.resetTextureCache();
  6322. texture.isReady = true;
  6323. };
  6324. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6325. if (texture._isDisabled) {
  6326. return;
  6327. }
  6328. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6329. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6330. try {
  6331. // Testing video texture support
  6332. if (this._videoTextureSupported === undefined) {
  6333. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6334. if (this._gl.getError() !== 0) {
  6335. this._videoTextureSupported = false;
  6336. }
  6337. else {
  6338. this._videoTextureSupported = true;
  6339. }
  6340. }
  6341. // Copy video through the current working canvas if video texture is not supported
  6342. if (!this._videoTextureSupported) {
  6343. if (!texture._workingCanvas) {
  6344. texture._workingCanvas = document.createElement("canvas");
  6345. texture._workingContext = texture._workingCanvas.getContext("2d");
  6346. texture._workingCanvas.width = texture._width;
  6347. texture._workingCanvas.height = texture._height;
  6348. }
  6349. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6350. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6351. }
  6352. else {
  6353. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6354. }
  6355. if (texture.generateMipMaps) {
  6356. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6357. }
  6358. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6359. this.resetTextureCache();
  6360. texture.isReady = true;
  6361. }
  6362. catch (ex) {
  6363. // Something unexpected
  6364. // Let's disable the texture
  6365. texture._isDisabled = true;
  6366. }
  6367. };
  6368. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6369. // old version had a "generateMipMaps" arg instead of options.
  6370. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6371. // in the same way, generateDepthBuffer is defaulted to true
  6372. var generateMipMaps = false;
  6373. var generateDepthBuffer = true;
  6374. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6375. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6376. if (options !== undefined) {
  6377. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6378. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6379. type = options.type === undefined ? type : options.type;
  6380. if (options.samplingMode !== undefined) {
  6381. samplingMode = options.samplingMode;
  6382. }
  6383. if (type === Engine.TEXTURETYPE_FLOAT) {
  6384. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6385. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6386. }
  6387. }
  6388. var gl = this._gl;
  6389. var texture = gl.createTexture();
  6390. gl.bindTexture(gl.TEXTURE_2D, texture);
  6391. var width = size.width || size;
  6392. var height = size.height || size;
  6393. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6394. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6395. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6396. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6397. }
  6398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6399. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6402. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6403. var depthBuffer;
  6404. // Create the depth buffer
  6405. if (generateDepthBuffer) {
  6406. depthBuffer = gl.createRenderbuffer();
  6407. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6408. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6409. }
  6410. // Create the framebuffer
  6411. var framebuffer = gl.createFramebuffer();
  6412. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6413. if (generateDepthBuffer) {
  6414. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6415. }
  6416. if (generateMipMaps) {
  6417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6418. }
  6419. // Unbind
  6420. gl.bindTexture(gl.TEXTURE_2D, null);
  6421. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6422. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6423. texture._framebuffer = framebuffer;
  6424. if (generateDepthBuffer) {
  6425. texture._depthBuffer = depthBuffer;
  6426. }
  6427. texture._width = width;
  6428. texture._height = height;
  6429. texture.isReady = true;
  6430. texture.generateMipMaps = generateMipMaps;
  6431. texture.references = 1;
  6432. texture.samplingMode = samplingMode;
  6433. this.resetTextureCache();
  6434. this._loadedTexturesCache.push(texture);
  6435. return texture;
  6436. };
  6437. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6438. var gl = this._gl;
  6439. var texture = gl.createTexture();
  6440. var generateMipMaps = true;
  6441. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6442. if (options !== undefined) {
  6443. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6444. if (options.samplingMode !== undefined) {
  6445. samplingMode = options.samplingMode;
  6446. }
  6447. }
  6448. texture.isCube = true;
  6449. texture.references = 1;
  6450. texture.generateMipMaps = generateMipMaps;
  6451. texture.references = 1;
  6452. texture.samplingMode = samplingMode;
  6453. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6454. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6455. for (var face = 0; face < 6; face++) {
  6456. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6457. }
  6458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6462. // Create the depth buffer
  6463. var depthBuffer = gl.createRenderbuffer();
  6464. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6465. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6466. // Create the framebuffer
  6467. var framebuffer = gl.createFramebuffer();
  6468. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6469. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6470. // mipmaps
  6471. if (texture.generateMipMaps) {
  6472. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6473. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6474. }
  6475. // Unbind
  6476. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6477. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6478. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6479. texture._framebuffer = framebuffer;
  6480. texture._depthBuffer = depthBuffer;
  6481. this.resetTextureCache();
  6482. texture._width = size;
  6483. texture._height = size;
  6484. texture.isReady = true;
  6485. return texture;
  6486. };
  6487. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6488. var _this = this;
  6489. var gl = this._gl;
  6490. var texture = gl.createTexture();
  6491. texture.isCube = true;
  6492. texture.url = rootUrl;
  6493. texture.references = 1;
  6494. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6495. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6496. if (isDDS) {
  6497. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6498. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6499. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6500. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6501. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6502. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6503. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6504. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6505. }
  6506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6510. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6511. _this.resetTextureCache();
  6512. texture._width = info.width;
  6513. texture._height = info.height;
  6514. texture.isReady = true;
  6515. }, null, null, true);
  6516. }
  6517. else {
  6518. cascadeLoad(rootUrl, scene, function (imgs) {
  6519. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6520. var height = width;
  6521. _this._prepareWorkingCanvas();
  6522. _this._workingCanvas.width = width;
  6523. _this._workingCanvas.height = height;
  6524. var faces = [
  6525. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6526. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6527. ];
  6528. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6530. for (var index = 0; index < faces.length; index++) {
  6531. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6532. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6533. }
  6534. if (!noMipmap) {
  6535. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6536. }
  6537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6541. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6542. _this.resetTextureCache();
  6543. texture._width = width;
  6544. texture._height = height;
  6545. texture.isReady = true;
  6546. }, extensions);
  6547. }
  6548. return texture;
  6549. };
  6550. Engine.prototype._releaseTexture = function (texture) {
  6551. var gl = this._gl;
  6552. if (texture._framebuffer) {
  6553. gl.deleteFramebuffer(texture._framebuffer);
  6554. }
  6555. if (texture._depthBuffer) {
  6556. gl.deleteRenderbuffer(texture._depthBuffer);
  6557. }
  6558. gl.deleteTexture(texture);
  6559. // Unbind channels
  6560. this.unbindAllTextures();
  6561. var index = this._loadedTexturesCache.indexOf(texture);
  6562. if (index !== -1) {
  6563. this._loadedTexturesCache.splice(index, 1);
  6564. }
  6565. };
  6566. Engine.prototype.bindSamplers = function (effect) {
  6567. this._gl.useProgram(effect.getProgram());
  6568. var samplers = effect.getSamplers();
  6569. for (var index = 0; index < samplers.length; index++) {
  6570. var uniform = effect.getUniform(samplers[index]);
  6571. this._gl.uniform1i(uniform, index);
  6572. }
  6573. this._currentEffect = null;
  6574. };
  6575. Engine.prototype._bindTexture = function (channel, texture) {
  6576. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6577. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6578. this._activeTexturesCache[channel] = null;
  6579. };
  6580. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6581. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6582. };
  6583. Engine.prototype.unbindAllTextures = function () {
  6584. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6585. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6586. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6587. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6588. this._activeTexturesCache[channel] = null;
  6589. }
  6590. };
  6591. Engine.prototype.setTexture = function (channel, texture) {
  6592. if (channel < 0) {
  6593. return;
  6594. }
  6595. // Not ready?
  6596. if (!texture || !texture.isReady()) {
  6597. if (this._activeTexturesCache[channel] != null) {
  6598. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6599. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6600. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6601. this._activeTexturesCache[channel] = null;
  6602. }
  6603. return;
  6604. }
  6605. // Video
  6606. var alreadyActivated = false;
  6607. if (texture instanceof BABYLON.VideoTexture) {
  6608. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6609. alreadyActivated = true;
  6610. texture.update();
  6611. }
  6612. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6613. texture.delayLoad();
  6614. return;
  6615. }
  6616. if (this._activeTexturesCache[channel] === texture) {
  6617. return;
  6618. }
  6619. this._activeTexturesCache[channel] = texture;
  6620. var internalTexture = texture.getInternalTexture();
  6621. if (!alreadyActivated) {
  6622. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6623. }
  6624. if (internalTexture.isCube) {
  6625. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6626. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6627. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6628. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6629. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6630. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6631. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6632. }
  6633. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6634. }
  6635. else {
  6636. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6637. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6638. internalTexture._cachedWrapU = texture.wrapU;
  6639. switch (texture.wrapU) {
  6640. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6641. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6642. break;
  6643. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6645. break;
  6646. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6647. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6648. break;
  6649. }
  6650. }
  6651. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6652. internalTexture._cachedWrapV = texture.wrapV;
  6653. switch (texture.wrapV) {
  6654. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6655. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6656. break;
  6657. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6658. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6659. break;
  6660. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6661. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6662. break;
  6663. }
  6664. }
  6665. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6666. }
  6667. };
  6668. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6669. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6670. var value = texture.anisotropicFilteringLevel;
  6671. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6672. value = 1;
  6673. }
  6674. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6675. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6676. texture._cachedAnisotropicFilteringLevel = value;
  6677. }
  6678. };
  6679. Engine.prototype.readPixels = function (x, y, width, height) {
  6680. var data = new Uint8Array(height * width * 4);
  6681. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6682. return data;
  6683. };
  6684. Engine.prototype.releaseInternalTexture = function (texture) {
  6685. if (!texture) {
  6686. return;
  6687. }
  6688. texture.references--;
  6689. // Final reference ?
  6690. if (texture.references === 0) {
  6691. var texturesCache = this.getLoadedTexturesCache();
  6692. var index = texturesCache.indexOf(texture);
  6693. if (index > -1) {
  6694. texturesCache.splice(index, 1);
  6695. }
  6696. this._releaseTexture(texture);
  6697. }
  6698. };
  6699. // Dispose
  6700. Engine.prototype.dispose = function () {
  6701. this.hideLoadingUI();
  6702. this.stopRenderLoop();
  6703. // Release scenes
  6704. while (this.scenes.length) {
  6705. this.scenes[0].dispose();
  6706. }
  6707. // Release audio engine
  6708. Engine.audioEngine.dispose();
  6709. // Release effects
  6710. for (var name in this._compiledEffects) {
  6711. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6712. }
  6713. // Unbind
  6714. for (var i in this._vertexAttribArrays) {
  6715. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6716. continue;
  6717. }
  6718. this._gl.disableVertexAttribArray(i);
  6719. }
  6720. this._gl = null;
  6721. // Events
  6722. window.removeEventListener("blur", this._onBlur);
  6723. window.removeEventListener("focus", this._onFocus);
  6724. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6725. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6726. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6727. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6728. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6729. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6730. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6731. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6732. };
  6733. // Loading screen
  6734. Engine.prototype.displayLoadingUI = function () {
  6735. this._loadingScreen.displayLoadingUI();
  6736. };
  6737. Engine.prototype.hideLoadingUI = function () {
  6738. this._loadingScreen.hideLoadingUI();
  6739. };
  6740. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6741. get: function () {
  6742. return this._loadingScreen;
  6743. },
  6744. set: function (loadingScreen) {
  6745. this._loadingScreen = loadingScreen;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6751. set: function (text) {
  6752. this._loadingScreen.loadingUIText = text;
  6753. },
  6754. enumerable: true,
  6755. configurable: true
  6756. });
  6757. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6758. set: function (color) {
  6759. this._loadingScreen.loadingUIBackgroundColor = color;
  6760. },
  6761. enumerable: true,
  6762. configurable: true
  6763. });
  6764. // FPS
  6765. Engine.prototype.getFps = function () {
  6766. return this.fps;
  6767. };
  6768. Engine.prototype.getDeltaTime = function () {
  6769. return this.deltaTime;
  6770. };
  6771. Engine.prototype._measureFps = function () {
  6772. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6773. var length = this.previousFramesDuration.length;
  6774. if (length >= 2) {
  6775. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6776. }
  6777. if (length >= this.fpsRange) {
  6778. if (length > this.fpsRange) {
  6779. this.previousFramesDuration.splice(0, 1);
  6780. length = this.previousFramesDuration.length;
  6781. }
  6782. var sum = 0;
  6783. for (var id = 0; id < length - 1; id++) {
  6784. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6785. }
  6786. this.fps = 1000.0 / (sum / (length - 1));
  6787. }
  6788. };
  6789. // Statics
  6790. Engine.isSupported = function () {
  6791. try {
  6792. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6793. if (navigator.isCocoonJS) {
  6794. return true;
  6795. }
  6796. var tempcanvas = document.createElement("canvas");
  6797. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6798. return gl != null && !!window.WebGLRenderingContext;
  6799. }
  6800. catch (e) {
  6801. return false;
  6802. }
  6803. };
  6804. // Const statics
  6805. Engine._ALPHA_DISABLE = 0;
  6806. Engine._ALPHA_ADD = 1;
  6807. Engine._ALPHA_COMBINE = 2;
  6808. Engine._ALPHA_SUBTRACT = 3;
  6809. Engine._ALPHA_MULTIPLY = 4;
  6810. Engine._ALPHA_MAXIMIZED = 5;
  6811. Engine._ALPHA_ONEONE = 6;
  6812. Engine._DELAYLOADSTATE_NONE = 0;
  6813. Engine._DELAYLOADSTATE_LOADED = 1;
  6814. Engine._DELAYLOADSTATE_LOADING = 2;
  6815. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6816. Engine._TEXTUREFORMAT_ALPHA = 0;
  6817. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6818. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6819. Engine._TEXTUREFORMAT_RGB = 4;
  6820. Engine._TEXTUREFORMAT_RGBA = 5;
  6821. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6822. Engine._TEXTURETYPE_FLOAT = 1;
  6823. // Updatable statics so stick with vars here
  6824. Engine.Epsilon = 0.001;
  6825. Engine.CollisionsEpsilon = 0.001;
  6826. Engine.CodeRepository = "src/";
  6827. Engine.ShadersRepository = "src/Shaders/";
  6828. return Engine;
  6829. })();
  6830. BABYLON.Engine = Engine;
  6831. })(BABYLON || (BABYLON = {}));
  6832. var BABYLON;
  6833. (function (BABYLON) {
  6834. /**
  6835. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6836. */
  6837. var Node = (function () {
  6838. /**
  6839. * @constructor
  6840. * @param {string} name - the name and id to be given to this node
  6841. * @param {BABYLON.Scene} the scene this node will be added to
  6842. */
  6843. function Node(name, scene) {
  6844. this.state = "";
  6845. this.animations = new Array();
  6846. this._childrenFlag = -1;
  6847. this._isEnabled = true;
  6848. this._isReady = true;
  6849. this._currentRenderId = -1;
  6850. this._parentRenderId = -1;
  6851. this.name = name;
  6852. this.id = name;
  6853. this._scene = scene;
  6854. this._initCache();
  6855. }
  6856. Node.prototype.getScene = function () {
  6857. return this._scene;
  6858. };
  6859. Node.prototype.getEngine = function () {
  6860. return this._scene.getEngine();
  6861. };
  6862. // override it in derived class
  6863. Node.prototype.getWorldMatrix = function () {
  6864. return BABYLON.Matrix.Identity();
  6865. };
  6866. // override it in derived class if you add new variables to the cache
  6867. // and call the parent class method
  6868. Node.prototype._initCache = function () {
  6869. this._cache = {};
  6870. this._cache.parent = undefined;
  6871. };
  6872. Node.prototype.updateCache = function (force) {
  6873. if (!force && this.isSynchronized())
  6874. return;
  6875. this._cache.parent = this.parent;
  6876. this._updateCache();
  6877. };
  6878. // override it in derived class if you add new variables to the cache
  6879. // and call the parent class method if !ignoreParentClass
  6880. Node.prototype._updateCache = function (ignoreParentClass) {
  6881. };
  6882. // override it in derived class if you add new variables to the cache
  6883. Node.prototype._isSynchronized = function () {
  6884. return true;
  6885. };
  6886. Node.prototype._markSyncedWithParent = function () {
  6887. this._parentRenderId = this.parent._currentRenderId;
  6888. };
  6889. Node.prototype.isSynchronizedWithParent = function () {
  6890. if (!this.parent) {
  6891. return true;
  6892. }
  6893. if (this._parentRenderId !== this.parent._currentRenderId) {
  6894. return false;
  6895. }
  6896. return this.parent.isSynchronized();
  6897. };
  6898. Node.prototype.isSynchronized = function (updateCache) {
  6899. var check = this.hasNewParent();
  6900. check = check || !this.isSynchronizedWithParent();
  6901. check = check || !this._isSynchronized();
  6902. if (updateCache)
  6903. this.updateCache(true);
  6904. return !check;
  6905. };
  6906. Node.prototype.hasNewParent = function (update) {
  6907. if (this._cache.parent === this.parent)
  6908. return false;
  6909. if (update)
  6910. this._cache.parent = this.parent;
  6911. return true;
  6912. };
  6913. /**
  6914. * Is this node ready to be used/rendered
  6915. * @return {boolean} is it ready
  6916. */
  6917. Node.prototype.isReady = function () {
  6918. return this._isReady;
  6919. };
  6920. /**
  6921. * Is this node enabled.
  6922. * If the node has a parent and is enabled, the parent will be inspected as well.
  6923. * @return {boolean} whether this node (and its parent) is enabled.
  6924. * @see setEnabled
  6925. */
  6926. Node.prototype.isEnabled = function () {
  6927. if (!this._isEnabled) {
  6928. return false;
  6929. }
  6930. if (this.parent) {
  6931. return this.parent.isEnabled();
  6932. }
  6933. return true;
  6934. };
  6935. /**
  6936. * Set the enabled state of this node.
  6937. * @param {boolean} value - the new enabled state
  6938. * @see isEnabled
  6939. */
  6940. Node.prototype.setEnabled = function (value) {
  6941. this._isEnabled = value;
  6942. };
  6943. /**
  6944. * Is this node a descendant of the given node.
  6945. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6946. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6947. * @see parent
  6948. */
  6949. Node.prototype.isDescendantOf = function (ancestor) {
  6950. if (this.parent) {
  6951. if (this.parent === ancestor) {
  6952. return true;
  6953. }
  6954. return this.parent.isDescendantOf(ancestor);
  6955. }
  6956. return false;
  6957. };
  6958. Node.prototype._getDescendants = function (list, results) {
  6959. for (var index = 0; index < list.length; index++) {
  6960. var item = list[index];
  6961. if (item.isDescendantOf(this)) {
  6962. results.push(item);
  6963. }
  6964. }
  6965. };
  6966. /**
  6967. * Will return all nodes that have this node as parent.
  6968. * @return {BABYLON.Node[]} all children nodes of all types.
  6969. */
  6970. Node.prototype.getDescendants = function () {
  6971. var results = [];
  6972. this._getDescendants(this._scene.meshes, results);
  6973. this._getDescendants(this._scene.lights, results);
  6974. this._getDescendants(this._scene.cameras, results);
  6975. return results;
  6976. };
  6977. Node.prototype._setReady = function (state) {
  6978. if (state === this._isReady) {
  6979. return;
  6980. }
  6981. if (!state) {
  6982. this._isReady = false;
  6983. return;
  6984. }
  6985. this._isReady = true;
  6986. if (this.onReady) {
  6987. this.onReady(this);
  6988. }
  6989. };
  6990. Node.prototype.getAnimationByName = function (name) {
  6991. for (var i = 0; i < this.animations.length; i++) {
  6992. var animation = this.animations[i];
  6993. if (animation.name === name) {
  6994. return animation;
  6995. }
  6996. }
  6997. return null;
  6998. };
  6999. return Node;
  7000. })();
  7001. BABYLON.Node = Node;
  7002. })(BABYLON || (BABYLON = {}));
  7003. var BABYLON;
  7004. (function (BABYLON) {
  7005. var FilesInput = (function () {
  7006. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7007. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7008. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7009. this._engine = p_engine;
  7010. this._canvas = p_canvas;
  7011. this._currentScene = p_scene;
  7012. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7013. this._progressCallback = p_progressCallback;
  7014. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7015. this._textureLoadingCallback = p_textureLoadingCallback;
  7016. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7017. }
  7018. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7019. var _this = this;
  7020. if (p_elementToMonitor) {
  7021. this._elementToMonitor = p_elementToMonitor;
  7022. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7023. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7024. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7025. }
  7026. };
  7027. FilesInput.prototype.renderFunction = function () {
  7028. if (this._additionnalRenderLoopLogicCallback) {
  7029. this._additionnalRenderLoopLogicCallback();
  7030. }
  7031. if (this._currentScene) {
  7032. if (this._textureLoadingCallback) {
  7033. var remaining = this._currentScene.getWaitingItemsCount();
  7034. if (remaining > 0) {
  7035. this._textureLoadingCallback(remaining);
  7036. }
  7037. }
  7038. this._currentScene.render();
  7039. }
  7040. };
  7041. FilesInput.prototype.drag = function (e) {
  7042. e.stopPropagation();
  7043. e.preventDefault();
  7044. };
  7045. FilesInput.prototype.drop = function (eventDrop) {
  7046. eventDrop.stopPropagation();
  7047. eventDrop.preventDefault();
  7048. this.loadFiles(eventDrop);
  7049. };
  7050. FilesInput.prototype.loadFiles = function (event) {
  7051. if (this._startingProcessingFilesCallback)
  7052. this._startingProcessingFilesCallback();
  7053. // Handling data transfer via drag'n'drop
  7054. if (event && event.dataTransfer && event.dataTransfer.files) {
  7055. this._filesToLoad = event.dataTransfer.files;
  7056. }
  7057. // Handling files from input files
  7058. if (event && event.target && event.target.files) {
  7059. this._filesToLoad = event.target.files;
  7060. }
  7061. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7062. for (var i = 0; i < this._filesToLoad.length; i++) {
  7063. switch (this._filesToLoad[i].type) {
  7064. case "image/jpeg":
  7065. case "image/png":
  7066. case "image/bmp":
  7067. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7068. break;
  7069. case "image/targa":
  7070. case "image/vnd.ms-dds":
  7071. case "audio/wav":
  7072. case "audio/x-wav":
  7073. case "audio/mp3":
  7074. case "audio/mpeg":
  7075. case "audio/mpeg3":
  7076. case "audio/x-mpeg-3":
  7077. case "audio/ogg":
  7078. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7079. break;
  7080. default:
  7081. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7082. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7083. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7084. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7085. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7086. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7087. this._sceneFileToLoad = this._filesToLoad[i];
  7088. }
  7089. break;
  7090. }
  7091. }
  7092. this.reload();
  7093. }
  7094. };
  7095. FilesInput.prototype.reload = function () {
  7096. var _this = this;
  7097. var that = this;
  7098. // If a ".babylon" file has been provided
  7099. if (this._sceneFileToLoad) {
  7100. if (this._currentScene) {
  7101. if (BABYLON.Tools.errorsCount > 0) {
  7102. BABYLON.Tools.ClearLogCache();
  7103. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7104. }
  7105. this._engine.stopRenderLoop();
  7106. this._currentScene.dispose();
  7107. }
  7108. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7109. that._currentScene = newScene;
  7110. // Wait for textures and shaders to be ready
  7111. that._currentScene.executeWhenReady(function () {
  7112. // Attach camera to canvas inputs
  7113. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7114. that._currentScene.createDefaultCameraOrLight();
  7115. }
  7116. that._currentScene.activeCamera.attachControl(that._canvas);
  7117. if (that._sceneLoadedCallback) {
  7118. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7119. }
  7120. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7121. });
  7122. }, function (progress) {
  7123. if (_this._progressCallback) {
  7124. _this._progressCallback(progress);
  7125. }
  7126. });
  7127. }
  7128. else {
  7129. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7130. }
  7131. };
  7132. FilesInput.FilesTextures = new Array();
  7133. FilesInput.FilesToLoad = new Array();
  7134. return FilesInput;
  7135. })();
  7136. BABYLON.FilesInput = FilesInput;
  7137. })(BABYLON || (BABYLON = {}));
  7138. var BABYLON;
  7139. (function (BABYLON) {
  7140. var IntersectionInfo = (function () {
  7141. function IntersectionInfo(bu, bv, distance) {
  7142. this.bu = bu;
  7143. this.bv = bv;
  7144. this.distance = distance;
  7145. this.faceId = 0;
  7146. this.subMeshId = 0;
  7147. }
  7148. return IntersectionInfo;
  7149. })();
  7150. BABYLON.IntersectionInfo = IntersectionInfo;
  7151. var PickingInfo = (function () {
  7152. function PickingInfo() {
  7153. this.hit = false;
  7154. this.distance = 0;
  7155. this.pickedPoint = null;
  7156. this.pickedMesh = null;
  7157. this.bu = 0;
  7158. this.bv = 0;
  7159. this.faceId = -1;
  7160. this.subMeshId = 0;
  7161. this.pickedSprite = null;
  7162. }
  7163. // Methods
  7164. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7165. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7166. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7167. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7168. return null;
  7169. }
  7170. var indices = this.pickedMesh.getIndices();
  7171. var result;
  7172. if (useVerticesNormals) {
  7173. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7174. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7175. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7176. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7177. normal0 = normal0.scale(this.bu);
  7178. normal1 = normal1.scale(this.bv);
  7179. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7180. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7181. }
  7182. else {
  7183. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7184. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7185. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7186. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7187. var p1p2 = vertex1.subtract(vertex2);
  7188. var p3p2 = vertex3.subtract(vertex2);
  7189. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7190. }
  7191. if (useWorldCoordinates) {
  7192. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7193. }
  7194. return BABYLON.Vector3.Normalize(result);
  7195. };
  7196. PickingInfo.prototype.getTextureCoordinates = function () {
  7197. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7198. return null;
  7199. }
  7200. var indices = this.pickedMesh.getIndices();
  7201. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7202. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7203. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7204. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7205. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7206. uv1 = uv1.scale(this.bu);
  7207. uv2 = uv2.scale(this.bv);
  7208. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7209. };
  7210. return PickingInfo;
  7211. })();
  7212. BABYLON.PickingInfo = PickingInfo;
  7213. })(BABYLON || (BABYLON = {}));
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. var BoundingSphere = (function () {
  7217. function BoundingSphere(minimum, maximum) {
  7218. this.minimum = minimum;
  7219. this.maximum = maximum;
  7220. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7221. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7222. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7223. this.radius = distance * 0.5;
  7224. this.centerWorld = BABYLON.Vector3.Zero();
  7225. this._update(BABYLON.Matrix.Identity());
  7226. }
  7227. // Methods
  7228. BoundingSphere.prototype._update = function (world) {
  7229. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7230. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7231. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7232. };
  7233. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7234. for (var i = 0; i < 6; i++) {
  7235. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7236. return false;
  7237. }
  7238. return true;
  7239. };
  7240. BoundingSphere.prototype.intersectsPoint = function (point) {
  7241. var x = this.centerWorld.x - point.x;
  7242. var y = this.centerWorld.y - point.y;
  7243. var z = this.centerWorld.z - point.z;
  7244. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7245. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7246. return false;
  7247. return true;
  7248. };
  7249. // Statics
  7250. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7251. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7252. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7253. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7254. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7255. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7256. return false;
  7257. return true;
  7258. };
  7259. return BoundingSphere;
  7260. })();
  7261. BABYLON.BoundingSphere = BoundingSphere;
  7262. })(BABYLON || (BABYLON = {}));
  7263. var BABYLON;
  7264. (function (BABYLON) {
  7265. var BoundingBox = (function () {
  7266. function BoundingBox(minimum, maximum) {
  7267. this.minimum = minimum;
  7268. this.maximum = maximum;
  7269. this.vectors = new Array();
  7270. this.vectorsWorld = new Array();
  7271. // Bounding vectors
  7272. this.vectors.push(this.minimum.clone());
  7273. this.vectors.push(this.maximum.clone());
  7274. this.vectors.push(this.minimum.clone());
  7275. this.vectors[2].x = this.maximum.x;
  7276. this.vectors.push(this.minimum.clone());
  7277. this.vectors[3].y = this.maximum.y;
  7278. this.vectors.push(this.minimum.clone());
  7279. this.vectors[4].z = this.maximum.z;
  7280. this.vectors.push(this.maximum.clone());
  7281. this.vectors[5].z = this.minimum.z;
  7282. this.vectors.push(this.maximum.clone());
  7283. this.vectors[6].x = this.minimum.x;
  7284. this.vectors.push(this.maximum.clone());
  7285. this.vectors[7].y = this.minimum.y;
  7286. // OBB
  7287. this.center = this.maximum.add(this.minimum).scale(0.5);
  7288. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7289. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7290. // World
  7291. for (var index = 0; index < this.vectors.length; index++) {
  7292. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7293. }
  7294. this.minimumWorld = BABYLON.Vector3.Zero();
  7295. this.maximumWorld = BABYLON.Vector3.Zero();
  7296. this._update(BABYLON.Matrix.Identity());
  7297. }
  7298. // Methods
  7299. BoundingBox.prototype.getWorldMatrix = function () {
  7300. return this._worldMatrix;
  7301. };
  7302. BoundingBox.prototype._update = function (world) {
  7303. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7304. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7305. for (var index = 0; index < this.vectors.length; index++) {
  7306. var v = this.vectorsWorld[index];
  7307. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7308. if (v.x < this.minimumWorld.x)
  7309. this.minimumWorld.x = v.x;
  7310. if (v.y < this.minimumWorld.y)
  7311. this.minimumWorld.y = v.y;
  7312. if (v.z < this.minimumWorld.z)
  7313. this.minimumWorld.z = v.z;
  7314. if (v.x > this.maximumWorld.x)
  7315. this.maximumWorld.x = v.x;
  7316. if (v.y > this.maximumWorld.y)
  7317. this.maximumWorld.y = v.y;
  7318. if (v.z > this.maximumWorld.z)
  7319. this.maximumWorld.z = v.z;
  7320. }
  7321. // OBB
  7322. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7323. this.center.scaleInPlace(0.5);
  7324. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7325. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7326. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7327. this._worldMatrix = world;
  7328. };
  7329. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7330. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7331. };
  7332. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7333. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7334. };
  7335. BoundingBox.prototype.intersectsPoint = function (point) {
  7336. var delta = -BABYLON.Engine.Epsilon;
  7337. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7338. return false;
  7339. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7340. return false;
  7341. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7342. return false;
  7343. return true;
  7344. };
  7345. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7346. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7347. };
  7348. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7349. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7350. return false;
  7351. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7352. return false;
  7353. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7354. return false;
  7355. return true;
  7356. };
  7357. // Statics
  7358. BoundingBox.Intersects = function (box0, box1) {
  7359. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7360. return false;
  7361. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7362. return false;
  7363. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7364. return false;
  7365. return true;
  7366. };
  7367. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7368. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7369. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7370. return (num <= (sphereRadius * sphereRadius));
  7371. };
  7372. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7373. for (var p = 0; p < 6; p++) {
  7374. for (var i = 0; i < 8; i++) {
  7375. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7376. return false;
  7377. }
  7378. }
  7379. }
  7380. return true;
  7381. };
  7382. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7383. for (var p = 0; p < 6; p++) {
  7384. var inCount = 8;
  7385. for (var i = 0; i < 8; i++) {
  7386. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7387. --inCount;
  7388. }
  7389. else {
  7390. break;
  7391. }
  7392. }
  7393. if (inCount === 0)
  7394. return false;
  7395. }
  7396. return true;
  7397. };
  7398. return BoundingBox;
  7399. })();
  7400. BABYLON.BoundingBox = BoundingBox;
  7401. })(BABYLON || (BABYLON = {}));
  7402. var BABYLON;
  7403. (function (BABYLON) {
  7404. var computeBoxExtents = function (axis, box) {
  7405. var p = BABYLON.Vector3.Dot(box.center, axis);
  7406. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7407. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7408. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7409. var r = r0 + r1 + r2;
  7410. return {
  7411. min: p - r,
  7412. max: p + r
  7413. };
  7414. };
  7415. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7416. var axisOverlap = function (axis, box0, box1) {
  7417. var result0 = computeBoxExtents(axis, box0);
  7418. var result1 = computeBoxExtents(axis, box1);
  7419. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7420. };
  7421. var BoundingInfo = (function () {
  7422. function BoundingInfo(minimum, maximum) {
  7423. this.minimum = minimum;
  7424. this.maximum = maximum;
  7425. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7426. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7427. }
  7428. // Methods
  7429. BoundingInfo.prototype._update = function (world) {
  7430. this.boundingBox._update(world);
  7431. this.boundingSphere._update(world);
  7432. };
  7433. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7434. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7435. return false;
  7436. return this.boundingBox.isInFrustum(frustumPlanes);
  7437. };
  7438. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7439. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7440. };
  7441. BoundingInfo.prototype._checkCollision = function (collider) {
  7442. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7443. };
  7444. BoundingInfo.prototype.intersectsPoint = function (point) {
  7445. if (!this.boundingSphere.centerWorld) {
  7446. return false;
  7447. }
  7448. if (!this.boundingSphere.intersectsPoint(point)) {
  7449. return false;
  7450. }
  7451. if (!this.boundingBox.intersectsPoint(point)) {
  7452. return false;
  7453. }
  7454. return true;
  7455. };
  7456. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7457. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7458. return false;
  7459. }
  7460. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7461. return false;
  7462. }
  7463. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7464. return false;
  7465. }
  7466. if (!precise) {
  7467. return true;
  7468. }
  7469. var box0 = this.boundingBox;
  7470. var box1 = boundingInfo.boundingBox;
  7471. if (!axisOverlap(box0.directions[0], box0, box1))
  7472. return false;
  7473. if (!axisOverlap(box0.directions[1], box0, box1))
  7474. return false;
  7475. if (!axisOverlap(box0.directions[2], box0, box1))
  7476. return false;
  7477. if (!axisOverlap(box1.directions[0], box0, box1))
  7478. return false;
  7479. if (!axisOverlap(box1.directions[1], box0, box1))
  7480. return false;
  7481. if (!axisOverlap(box1.directions[2], box0, box1))
  7482. return false;
  7483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7484. return false;
  7485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7486. return false;
  7487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7488. return false;
  7489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7490. return false;
  7491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7492. return false;
  7493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7494. return false;
  7495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7496. return false;
  7497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7498. return false;
  7499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7500. return false;
  7501. return true;
  7502. };
  7503. return BoundingInfo;
  7504. })();
  7505. BABYLON.BoundingInfo = BoundingInfo;
  7506. })(BABYLON || (BABYLON = {}));
  7507. var BABYLON;
  7508. (function (BABYLON) {
  7509. var AbstractMesh = (function (_super) {
  7510. __extends(AbstractMesh, _super);
  7511. function AbstractMesh(name, scene) {
  7512. var _this = this;
  7513. _super.call(this, name, scene);
  7514. // Properties
  7515. this.definedFacingForward = true; // orientation for POV movement & rotation
  7516. this.position = new BABYLON.Vector3(0, 0, 0);
  7517. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7518. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7519. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7520. this.visibility = 1.0;
  7521. this.alphaIndex = Number.MAX_VALUE;
  7522. this.infiniteDistance = false;
  7523. this.isVisible = true;
  7524. this.isPickable = true;
  7525. this.showBoundingBox = false;
  7526. this.showSubMeshesBoundingBox = false;
  7527. this.onDispose = null;
  7528. this.isBlocker = false;
  7529. this.renderingGroupId = 0;
  7530. this.receiveShadows = false;
  7531. this.renderOutline = false;
  7532. this.outlineColor = BABYLON.Color3.Red();
  7533. this.outlineWidth = 0.02;
  7534. this.renderOverlay = false;
  7535. this.overlayColor = BABYLON.Color3.Red();
  7536. this.overlayAlpha = 0.5;
  7537. this.hasVertexAlpha = false;
  7538. this.useVertexColors = true;
  7539. this.applyFog = true;
  7540. this.computeBonesUsingShaders = true;
  7541. this.scalingDeterminant = 1;
  7542. this.numBoneInfluencers = 4;
  7543. this.useOctreeForRenderingSelection = true;
  7544. this.useOctreeForPicking = true;
  7545. this.useOctreeForCollisions = true;
  7546. this.layerMask = 0x0FFFFFFF;
  7547. this.alwaysSelectAsActiveMesh = false;
  7548. // Physics
  7549. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7550. // Collisions
  7551. this._checkCollisions = false;
  7552. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7553. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7554. this._collider = new BABYLON.Collider();
  7555. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7556. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7557. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7558. // Edges
  7559. this.edgesWidth = 1;
  7560. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7561. // Cache
  7562. this._localScaling = BABYLON.Matrix.Zero();
  7563. this._localRotation = BABYLON.Matrix.Zero();
  7564. this._localTranslation = BABYLON.Matrix.Zero();
  7565. this._localBillboard = BABYLON.Matrix.Zero();
  7566. this._localPivotScaling = BABYLON.Matrix.Zero();
  7567. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7568. this._localWorld = BABYLON.Matrix.Zero();
  7569. this._worldMatrix = BABYLON.Matrix.Zero();
  7570. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7571. this._absolutePosition = BABYLON.Vector3.Zero();
  7572. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7573. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7574. this._isDirty = false;
  7575. this._pivotMatrix = BABYLON.Matrix.Identity();
  7576. this._isDisposed = false;
  7577. this._renderId = 0;
  7578. this._intersectionsInProgress = new Array();
  7579. this._onAfterWorldMatrixUpdate = new Array();
  7580. this._isWorldMatrixFrozen = false;
  7581. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7582. if (collidedMesh === void 0) { collidedMesh = null; }
  7583. //TODO move this to the collision coordinator!
  7584. if (_this.getScene().workerCollisions)
  7585. newPosition.multiplyInPlace(_this._collider.radius);
  7586. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7587. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7588. _this.position.addInPlace(_this._diffPositionForCollisions);
  7589. }
  7590. if (_this.onCollide && collidedMesh) {
  7591. _this.onCollide(collidedMesh);
  7592. }
  7593. if (_this.onCollisionPositionChange) {
  7594. _this.onCollisionPositionChange(_this.position);
  7595. }
  7596. };
  7597. scene.addMesh(this);
  7598. }
  7599. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7600. get: function () {
  7601. return AbstractMesh._BILLBOARDMODE_NONE;
  7602. },
  7603. enumerable: true,
  7604. configurable: true
  7605. });
  7606. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7607. get: function () {
  7608. return AbstractMesh._BILLBOARDMODE_X;
  7609. },
  7610. enumerable: true,
  7611. configurable: true
  7612. });
  7613. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7614. get: function () {
  7615. return AbstractMesh._BILLBOARDMODE_Y;
  7616. },
  7617. enumerable: true,
  7618. configurable: true
  7619. });
  7620. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7621. get: function () {
  7622. return AbstractMesh._BILLBOARDMODE_Z;
  7623. },
  7624. enumerable: true,
  7625. configurable: true
  7626. });
  7627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7628. get: function () {
  7629. return AbstractMesh._BILLBOARDMODE_ALL;
  7630. },
  7631. enumerable: true,
  7632. configurable: true
  7633. });
  7634. // Methods
  7635. AbstractMesh.prototype.disableEdgesRendering = function () {
  7636. if (this._edgesRenderer !== undefined) {
  7637. this._edgesRenderer.dispose();
  7638. this._edgesRenderer = undefined;
  7639. }
  7640. };
  7641. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7642. if (epsilon === void 0) { epsilon = 0.95; }
  7643. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7644. this.disableEdgesRendering();
  7645. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7646. };
  7647. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7648. get: function () {
  7649. return false;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. AbstractMesh.prototype.getLOD = function (camera) {
  7655. return this;
  7656. };
  7657. AbstractMesh.prototype.getTotalVertices = function () {
  7658. return 0;
  7659. };
  7660. AbstractMesh.prototype.getIndices = function () {
  7661. return null;
  7662. };
  7663. AbstractMesh.prototype.getVerticesData = function (kind) {
  7664. return null;
  7665. };
  7666. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7667. return false;
  7668. };
  7669. AbstractMesh.prototype.getBoundingInfo = function () {
  7670. if (this._masterMesh) {
  7671. return this._masterMesh.getBoundingInfo();
  7672. }
  7673. if (!this._boundingInfo) {
  7674. this._updateBoundingInfo();
  7675. }
  7676. return this._boundingInfo;
  7677. };
  7678. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7679. get: function () {
  7680. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. AbstractMesh.prototype._preActivate = function () {
  7686. };
  7687. AbstractMesh.prototype._activate = function (renderId) {
  7688. this._renderId = renderId;
  7689. };
  7690. AbstractMesh.prototype.getWorldMatrix = function () {
  7691. if (this._masterMesh) {
  7692. return this._masterMesh.getWorldMatrix();
  7693. }
  7694. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7695. this.computeWorldMatrix();
  7696. }
  7697. return this._worldMatrix;
  7698. };
  7699. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7700. get: function () {
  7701. return this._worldMatrix;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7707. get: function () {
  7708. return this._absolutePosition;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7714. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7715. this.computeWorldMatrix(true);
  7716. this._isWorldMatrixFrozen = true;
  7717. };
  7718. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7719. this._isWorldMatrixFrozen = false;
  7720. this.computeWorldMatrix(true);
  7721. };
  7722. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7723. get: function () {
  7724. return this._isWorldMatrixFrozen;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7730. axis.normalize();
  7731. if (!this.rotationQuaternion) {
  7732. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7733. this.rotation = BABYLON.Vector3.Zero();
  7734. }
  7735. var rotationQuaternion;
  7736. if (!space || space === BABYLON.Space.LOCAL) {
  7737. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7738. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7739. }
  7740. else {
  7741. if (this.parent) {
  7742. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7743. invertParentWorldMatrix.invert();
  7744. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7745. }
  7746. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7747. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7748. }
  7749. };
  7750. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7751. var displacementVector = axis.scale(distance);
  7752. if (!space || space === BABYLON.Space.LOCAL) {
  7753. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7754. this.setPositionWithLocalVector(tempV3);
  7755. }
  7756. else {
  7757. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7758. }
  7759. };
  7760. AbstractMesh.prototype.getAbsolutePosition = function () {
  7761. this.computeWorldMatrix();
  7762. return this._absolutePosition;
  7763. };
  7764. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7765. if (!absolutePosition) {
  7766. return;
  7767. }
  7768. var absolutePositionX;
  7769. var absolutePositionY;
  7770. var absolutePositionZ;
  7771. if (absolutePosition.x === undefined) {
  7772. if (arguments.length < 3) {
  7773. return;
  7774. }
  7775. absolutePositionX = arguments[0];
  7776. absolutePositionY = arguments[1];
  7777. absolutePositionZ = arguments[2];
  7778. }
  7779. else {
  7780. absolutePositionX = absolutePosition.x;
  7781. absolutePositionY = absolutePosition.y;
  7782. absolutePositionZ = absolutePosition.z;
  7783. }
  7784. if (this.parent) {
  7785. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7786. invertParentWorldMatrix.invert();
  7787. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7788. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7789. }
  7790. else {
  7791. this.position.x = absolutePositionX;
  7792. this.position.y = absolutePositionY;
  7793. this.position.z = absolutePositionZ;
  7794. }
  7795. };
  7796. // ================================== Point of View Movement =================================
  7797. /**
  7798. * Perform relative position change from the point of view of behind the front of the mesh.
  7799. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7800. * Supports definition of mesh facing forward or backward.
  7801. * @param {number} amountRight
  7802. * @param {number} amountUp
  7803. * @param {number} amountForward
  7804. */
  7805. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7806. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7807. };
  7808. /**
  7809. * Calculate 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.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7817. var rotMatrix = new BABYLON.Matrix();
  7818. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7819. rotQuaternion.toRotationMatrix(rotMatrix);
  7820. var translationDelta = BABYLON.Vector3.Zero();
  7821. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7822. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7823. return translationDelta;
  7824. };
  7825. // ================================== Point of View Rotation =================================
  7826. /**
  7827. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7828. * Supports definition of mesh facing forward or backward.
  7829. * @param {number} flipBack
  7830. * @param {number} twirlClockwise
  7831. * @param {number} tiltRight
  7832. */
  7833. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7834. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7835. };
  7836. /**
  7837. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7838. * Supports definition of mesh facing forward or backward.
  7839. * @param {number} flipBack
  7840. * @param {number} twirlClockwise
  7841. * @param {number} tiltRight
  7842. */
  7843. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7844. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7845. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7846. };
  7847. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7848. this._pivotMatrix = matrix;
  7849. this._cache.pivotMatrixUpdated = true;
  7850. };
  7851. AbstractMesh.prototype.getPivotMatrix = function () {
  7852. return this._pivotMatrix;
  7853. };
  7854. AbstractMesh.prototype._isSynchronized = function () {
  7855. if (this._isDirty) {
  7856. return false;
  7857. }
  7858. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7859. return false;
  7860. if (this._cache.pivotMatrixUpdated) {
  7861. return false;
  7862. }
  7863. if (this.infiniteDistance) {
  7864. return false;
  7865. }
  7866. if (!this._cache.position.equals(this.position))
  7867. return false;
  7868. if (this.rotationQuaternion) {
  7869. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7870. return false;
  7871. }
  7872. else {
  7873. if (!this._cache.rotation.equals(this.rotation))
  7874. return false;
  7875. }
  7876. if (!this._cache.scaling.equals(this.scaling))
  7877. return false;
  7878. return true;
  7879. };
  7880. AbstractMesh.prototype._initCache = function () {
  7881. _super.prototype._initCache.call(this);
  7882. this._cache.localMatrixUpdated = false;
  7883. this._cache.position = BABYLON.Vector3.Zero();
  7884. this._cache.scaling = BABYLON.Vector3.Zero();
  7885. this._cache.rotation = BABYLON.Vector3.Zero();
  7886. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7887. this._cache.billboardMode = -1;
  7888. };
  7889. AbstractMesh.prototype.markAsDirty = function (property) {
  7890. if (property === "rotation") {
  7891. this.rotationQuaternion = null;
  7892. }
  7893. this._currentRenderId = Number.MAX_VALUE;
  7894. this._isDirty = true;
  7895. };
  7896. AbstractMesh.prototype._updateBoundingInfo = function () {
  7897. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7898. this._boundingInfo._update(this.worldMatrixFromCache);
  7899. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7900. };
  7901. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7902. if (!this.subMeshes) {
  7903. return;
  7904. }
  7905. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7906. var subMesh = this.subMeshes[subIndex];
  7907. subMesh.updateBoundingInfo(matrix);
  7908. }
  7909. };
  7910. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7911. if (this._isWorldMatrixFrozen) {
  7912. return this._worldMatrix;
  7913. }
  7914. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7915. return this._worldMatrix;
  7916. }
  7917. this._cache.position.copyFrom(this.position);
  7918. this._cache.scaling.copyFrom(this.scaling);
  7919. this._cache.pivotMatrixUpdated = false;
  7920. this._cache.billboardMode = this.billboardMode;
  7921. this._currentRenderId = this.getScene().getRenderId();
  7922. this._isDirty = false;
  7923. // Scaling
  7924. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7925. // Rotation
  7926. if (this.rotationQuaternion) {
  7927. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7928. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7929. }
  7930. else {
  7931. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7932. this._cache.rotation.copyFrom(this.rotation);
  7933. }
  7934. // Translation
  7935. if (this.infiniteDistance && !this.parent) {
  7936. var camera = this.getScene().activeCamera;
  7937. if (camera) {
  7938. var cameraWorldMatrix = camera.getWorldMatrix();
  7939. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7940. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7941. }
  7942. }
  7943. else {
  7944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7945. }
  7946. // Composing transformations
  7947. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7948. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7949. // Billboarding
  7950. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7951. var localPosition = this.position.clone();
  7952. var zero = this.getScene().activeCamera.globalPosition.clone();
  7953. if (this.parent && this.parent.position) {
  7954. localPosition.addInPlace(this.parent.position);
  7955. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7956. }
  7957. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7958. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7959. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7960. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7961. zero.y = localPosition.y + 0.001;
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7963. zero.z = localPosition.z + 0.001;
  7964. }
  7965. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7966. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7967. this._localBillboard.invert();
  7968. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7969. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7970. }
  7971. // Local world
  7972. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7973. // Parent
  7974. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7975. this._markSyncedWithParent();
  7976. if (this._meshToBoneReferal) {
  7977. if (!this._localMeshReferalTransform) {
  7978. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7979. }
  7980. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7981. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7982. }
  7983. else {
  7984. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7985. }
  7986. }
  7987. else {
  7988. this._worldMatrix.copyFrom(this._localWorld);
  7989. }
  7990. // Bounding info
  7991. this._updateBoundingInfo();
  7992. // Absolute position
  7993. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7994. // Callbacks
  7995. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7996. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7997. }
  7998. return this._worldMatrix;
  7999. };
  8000. /**
  8001. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8002. * @param func: callback function to add
  8003. */
  8004. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8005. this._onAfterWorldMatrixUpdate.push(func);
  8006. };
  8007. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8008. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8009. if (index > -1) {
  8010. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8011. }
  8012. };
  8013. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8014. this.computeWorldMatrix();
  8015. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8016. };
  8017. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8018. this.computeWorldMatrix();
  8019. var invLocalWorldMatrix = this._localWorld.clone();
  8020. invLocalWorldMatrix.invert();
  8021. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8022. };
  8023. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8024. this.computeWorldMatrix(true);
  8025. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8026. };
  8027. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8028. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8029. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8030. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8031. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8032. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8033. /// <returns>Mesh oriented towards targetMesh</returns>
  8034. yawCor = yawCor || 0; // default to zero if undefined
  8035. pitchCor = pitchCor || 0;
  8036. rollCor = rollCor || 0;
  8037. var dv = targetPoint.subtract(this.position);
  8038. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8039. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8040. var pitch = Math.atan2(dv.y, len);
  8041. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8042. };
  8043. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8044. this._meshToBoneReferal = affectedMesh;
  8045. this.parent = bone;
  8046. if (bone.getWorldMatrix().determinant() < 0) {
  8047. this.scalingDeterminant *= -1;
  8048. }
  8049. };
  8050. AbstractMesh.prototype.detachFromBone = function () {
  8051. if (this.parent.getWorldMatrix().determinant() < 0) {
  8052. this.scalingDeterminant *= -1;
  8053. }
  8054. this._meshToBoneReferal = null;
  8055. this.parent = null;
  8056. };
  8057. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8058. return this._boundingInfo.isInFrustum(frustumPlanes);
  8059. };
  8060. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8061. if (!camera) {
  8062. camera = this.getScene().activeCamera;
  8063. }
  8064. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8065. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8066. return false;
  8067. }
  8068. return true;
  8069. };
  8070. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8071. if (!this._boundingInfo || !mesh._boundingInfo) {
  8072. return false;
  8073. }
  8074. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8075. };
  8076. AbstractMesh.prototype.intersectsPoint = function (point) {
  8077. if (!this._boundingInfo) {
  8078. return false;
  8079. }
  8080. return this._boundingInfo.intersectsPoint(point);
  8081. };
  8082. // Physics
  8083. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8084. var physicsEngine = this.getScene().getPhysicsEngine();
  8085. if (!physicsEngine) {
  8086. return null;
  8087. }
  8088. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8089. if (impostor.impostor) {
  8090. // Old API
  8091. options = impostor;
  8092. impostor = impostor.impostor;
  8093. }
  8094. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8095. physicsEngine._unregisterMesh(this);
  8096. return null;
  8097. }
  8098. if (!options) {
  8099. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8100. }
  8101. else {
  8102. if (!options.mass && options.mass !== 0)
  8103. options.mass = 0;
  8104. if (!options.friction && options.friction !== 0)
  8105. options.friction = 0.2;
  8106. if (!options.restitution && options.restitution !== 0)
  8107. options.restitution = 0.2;
  8108. }
  8109. this._physicImpostor = impostor;
  8110. this._physicsMass = options.mass;
  8111. this._physicsFriction = options.friction;
  8112. this._physicRestitution = options.restitution;
  8113. return physicsEngine._registerMesh(this, impostor, options);
  8114. };
  8115. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8116. if (!this._physicImpostor) {
  8117. return BABYLON.PhysicsEngine.NoImpostor;
  8118. }
  8119. return this._physicImpostor;
  8120. };
  8121. AbstractMesh.prototype.getPhysicsMass = function () {
  8122. if (!this._physicsMass) {
  8123. return 0;
  8124. }
  8125. return this._physicsMass;
  8126. };
  8127. AbstractMesh.prototype.getPhysicsFriction = function () {
  8128. if (!this._physicsFriction) {
  8129. return 0;
  8130. }
  8131. return this._physicsFriction;
  8132. };
  8133. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8134. if (!this._physicRestitution) {
  8135. return 0;
  8136. }
  8137. return this._physicRestitution;
  8138. };
  8139. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8140. if (!camera) {
  8141. camera = this.getScene().activeCamera;
  8142. }
  8143. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8144. };
  8145. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8146. if (!camera) {
  8147. camera = this.getScene().activeCamera;
  8148. }
  8149. return this.absolutePosition.subtract(camera.position).length();
  8150. };
  8151. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8152. if (!this._physicImpostor) {
  8153. return;
  8154. }
  8155. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8156. };
  8157. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8158. if (!this._physicImpostor) {
  8159. return;
  8160. }
  8161. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8162. };
  8163. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8164. if (!this._physicImpostor) {
  8165. return;
  8166. }
  8167. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8168. };
  8169. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8170. // Collisions
  8171. get: function () {
  8172. return this._checkCollisions;
  8173. },
  8174. set: function (collisionEnabled) {
  8175. this._checkCollisions = collisionEnabled;
  8176. if (this.getScene().workerCollisions) {
  8177. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8178. }
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8184. var globalPosition = this.getAbsolutePosition();
  8185. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8186. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8187. this._collider.radius = this.ellipsoid;
  8188. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8189. };
  8190. // Submeshes octree
  8191. /**
  8192. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8193. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8194. */
  8195. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8196. if (maxCapacity === void 0) { maxCapacity = 64; }
  8197. if (maxDepth === void 0) { maxDepth = 2; }
  8198. if (!this._submeshesOctree) {
  8199. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8200. }
  8201. this.computeWorldMatrix(true);
  8202. // Update octree
  8203. var bbox = this.getBoundingInfo().boundingBox;
  8204. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8205. return this._submeshesOctree;
  8206. };
  8207. // Collisions
  8208. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8209. this._generatePointsArray();
  8210. // Transformation
  8211. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8212. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8213. subMesh._lastColliderWorldVertices = [];
  8214. subMesh._trianglePlanes = [];
  8215. var start = subMesh.verticesStart;
  8216. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8217. for (var i = start; i < end; i++) {
  8218. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8219. }
  8220. }
  8221. // Collide
  8222. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8223. if (collider.collisionFound) {
  8224. collider.collidedMesh = this;
  8225. }
  8226. };
  8227. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8228. var subMeshes;
  8229. var len;
  8230. // Octrees
  8231. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8232. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8233. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8234. len = intersections.length;
  8235. subMeshes = intersections.data;
  8236. }
  8237. else {
  8238. subMeshes = this.subMeshes;
  8239. len = subMeshes.length;
  8240. }
  8241. for (var index = 0; index < len; index++) {
  8242. var subMesh = subMeshes[index];
  8243. // Bounding test
  8244. if (len > 1 && !subMesh._checkCollision(collider))
  8245. continue;
  8246. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8247. }
  8248. };
  8249. AbstractMesh.prototype._checkCollision = function (collider) {
  8250. // Bounding box test
  8251. if (!this._boundingInfo._checkCollision(collider))
  8252. return;
  8253. // Transformation matrix
  8254. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8255. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8256. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8257. };
  8258. // Picking
  8259. AbstractMesh.prototype._generatePointsArray = function () {
  8260. return false;
  8261. };
  8262. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8263. var pickingInfo = new BABYLON.PickingInfo();
  8264. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8265. return pickingInfo;
  8266. }
  8267. if (!this._generatePointsArray()) {
  8268. return pickingInfo;
  8269. }
  8270. var intersectInfo = null;
  8271. // Octrees
  8272. var subMeshes;
  8273. var len;
  8274. if (this._submeshesOctree && this.useOctreeForPicking) {
  8275. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8276. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8277. len = intersections.length;
  8278. subMeshes = intersections.data;
  8279. }
  8280. else {
  8281. subMeshes = this.subMeshes;
  8282. len = subMeshes.length;
  8283. }
  8284. for (var index = 0; index < len; index++) {
  8285. var subMesh = subMeshes[index];
  8286. // Bounding test
  8287. if (len > 1 && !subMesh.canIntersects(ray))
  8288. continue;
  8289. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8290. if (currentIntersectInfo) {
  8291. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8292. intersectInfo = currentIntersectInfo;
  8293. intersectInfo.subMeshId = index;
  8294. if (fastCheck) {
  8295. break;
  8296. }
  8297. }
  8298. }
  8299. }
  8300. if (intersectInfo) {
  8301. // Get picked point
  8302. var world = this.getWorldMatrix();
  8303. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8304. var direction = ray.direction.clone();
  8305. direction = direction.scale(intersectInfo.distance);
  8306. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8307. var pickedPoint = worldOrigin.add(worldDirection);
  8308. // Return result
  8309. pickingInfo.hit = true;
  8310. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8311. pickingInfo.pickedPoint = pickedPoint;
  8312. pickingInfo.pickedMesh = this;
  8313. pickingInfo.bu = intersectInfo.bu;
  8314. pickingInfo.bv = intersectInfo.bv;
  8315. pickingInfo.faceId = intersectInfo.faceId;
  8316. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8317. return pickingInfo;
  8318. }
  8319. return pickingInfo;
  8320. };
  8321. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8322. return null;
  8323. };
  8324. AbstractMesh.prototype.releaseSubMeshes = function () {
  8325. if (this.subMeshes) {
  8326. while (this.subMeshes.length) {
  8327. this.subMeshes[0].dispose();
  8328. }
  8329. }
  8330. else {
  8331. this.subMeshes = new Array();
  8332. }
  8333. };
  8334. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8335. var index;
  8336. // Animations
  8337. this.getScene().stopAnimation(this);
  8338. // Physics
  8339. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8340. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8341. }
  8342. // Intersections in progress
  8343. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8344. var other = this._intersectionsInProgress[index];
  8345. var pos = other._intersectionsInProgress.indexOf(this);
  8346. other._intersectionsInProgress.splice(pos, 1);
  8347. }
  8348. this._intersectionsInProgress = [];
  8349. // Edges
  8350. if (this._edgesRenderer) {
  8351. this._edgesRenderer.dispose();
  8352. this._edgesRenderer = null;
  8353. }
  8354. // SubMeshes
  8355. this.releaseSubMeshes();
  8356. // Remove from scene
  8357. this.getScene().removeMesh(this);
  8358. if (!doNotRecurse) {
  8359. // Particles
  8360. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8361. if (this.getScene().particleSystems[index].emitter === this) {
  8362. this.getScene().particleSystems[index].dispose();
  8363. index--;
  8364. }
  8365. }
  8366. // Children
  8367. var objects = this.getScene().meshes.slice(0);
  8368. for (index = 0; index < objects.length; index++) {
  8369. if (objects[index].parent === this) {
  8370. objects[index].dispose();
  8371. }
  8372. }
  8373. }
  8374. else {
  8375. for (index = 0; index < this.getScene().meshes.length; index++) {
  8376. var obj = this.getScene().meshes[index];
  8377. if (obj.parent === this) {
  8378. obj.parent = null;
  8379. obj.computeWorldMatrix(true);
  8380. }
  8381. }
  8382. }
  8383. this._onAfterWorldMatrixUpdate = [];
  8384. this._isDisposed = true;
  8385. // Callback
  8386. if (this.onDispose) {
  8387. this.onDispose();
  8388. }
  8389. };
  8390. // Statics
  8391. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8392. AbstractMesh._BILLBOARDMODE_X = 1;
  8393. AbstractMesh._BILLBOARDMODE_Y = 2;
  8394. AbstractMesh._BILLBOARDMODE_Z = 4;
  8395. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8396. return AbstractMesh;
  8397. })(BABYLON.Node);
  8398. BABYLON.AbstractMesh = AbstractMesh;
  8399. })(BABYLON || (BABYLON = {}));
  8400. var BABYLON;
  8401. (function (BABYLON) {
  8402. var Light = (function (_super) {
  8403. __extends(Light, _super);
  8404. function Light(name, scene) {
  8405. _super.call(this, name, scene);
  8406. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8407. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8408. this.intensity = 1.0;
  8409. this.range = Number.MAX_VALUE;
  8410. this.includeOnlyWithLayerMask = 0;
  8411. this.includedOnlyMeshes = new Array();
  8412. this.excludedMeshes = new Array();
  8413. this.excludeWithLayerMask = 0;
  8414. this._excludedMeshesIds = new Array();
  8415. this._includedOnlyMeshesIds = new Array();
  8416. scene.addLight(this);
  8417. }
  8418. Light.prototype.getShadowGenerator = function () {
  8419. return this._shadowGenerator;
  8420. };
  8421. Light.prototype.getAbsolutePosition = function () {
  8422. return BABYLON.Vector3.Zero();
  8423. };
  8424. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8425. };
  8426. Light.prototype._getWorldMatrix = function () {
  8427. return BABYLON.Matrix.Identity();
  8428. };
  8429. Light.prototype.canAffectMesh = function (mesh) {
  8430. if (!mesh) {
  8431. return true;
  8432. }
  8433. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8434. return false;
  8435. }
  8436. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8437. return false;
  8438. }
  8439. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8440. return false;
  8441. }
  8442. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8443. return false;
  8444. }
  8445. return true;
  8446. };
  8447. Light.prototype.getWorldMatrix = function () {
  8448. this._currentRenderId = this.getScene().getRenderId();
  8449. var worldMatrix = this._getWorldMatrix();
  8450. if (this.parent && this.parent.getWorldMatrix) {
  8451. if (!this._parentedWorldMatrix) {
  8452. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8453. }
  8454. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8455. this._markSyncedWithParent();
  8456. return this._parentedWorldMatrix;
  8457. }
  8458. return worldMatrix;
  8459. };
  8460. Light.prototype.dispose = function () {
  8461. if (this._shadowGenerator) {
  8462. this._shadowGenerator.dispose();
  8463. this._shadowGenerator = null;
  8464. }
  8465. // Animations
  8466. this.getScene().stopAnimation(this);
  8467. // Remove from scene
  8468. this.getScene().removeLight(this);
  8469. };
  8470. Light.prototype.serialize = function () {
  8471. var serializationObject = {};
  8472. serializationObject.name = this.name;
  8473. serializationObject.id = this.id;
  8474. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8475. if (this.intensity) {
  8476. serializationObject.intensity = this.intensity;
  8477. }
  8478. serializationObject.range = this.range;
  8479. serializationObject.diffuse = this.diffuse.asArray();
  8480. serializationObject.specular = this.specular.asArray();
  8481. return serializationObject;
  8482. };
  8483. Light.ParseLight = function (parsedLight, scene) {
  8484. var light;
  8485. switch (parsedLight.type) {
  8486. case 0:
  8487. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8488. break;
  8489. case 1:
  8490. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8491. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8492. break;
  8493. case 2:
  8494. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8495. break;
  8496. case 3:
  8497. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8498. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8499. break;
  8500. }
  8501. light.id = parsedLight.id;
  8502. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8503. if (parsedLight.intensity !== undefined) {
  8504. light.intensity = parsedLight.intensity;
  8505. }
  8506. if (parsedLight.range) {
  8507. light.range = parsedLight.range;
  8508. }
  8509. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8510. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8511. if (parsedLight.excludedMeshesIds) {
  8512. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8513. }
  8514. // Parent
  8515. if (parsedLight.parentId) {
  8516. light._waitingParentId = parsedLight.parentId;
  8517. }
  8518. if (parsedLight.includedOnlyMeshesIds) {
  8519. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8520. }
  8521. // Animations
  8522. if (parsedLight.animations) {
  8523. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8524. var parsedAnimation = parsedLight.animations[animationIndex];
  8525. light.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  8526. }
  8527. }
  8528. if (parsedLight.autoAnimate) {
  8529. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8530. }
  8531. return light;
  8532. };
  8533. return Light;
  8534. })(BABYLON.Node);
  8535. BABYLON.Light = Light;
  8536. })(BABYLON || (BABYLON = {}));
  8537. var BABYLON;
  8538. (function (BABYLON) {
  8539. var PointLight = (function (_super) {
  8540. __extends(PointLight, _super);
  8541. function PointLight(name, position, scene) {
  8542. _super.call(this, name, scene);
  8543. this.position = position;
  8544. }
  8545. PointLight.prototype.getAbsolutePosition = function () {
  8546. return this.transformedPosition ? this.transformedPosition : this.position;
  8547. };
  8548. PointLight.prototype.computeTransformedPosition = function () {
  8549. if (this.parent && this.parent.getWorldMatrix) {
  8550. if (!this.transformedPosition) {
  8551. this.transformedPosition = BABYLON.Vector3.Zero();
  8552. }
  8553. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8554. return true;
  8555. }
  8556. return false;
  8557. };
  8558. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8559. if (this.parent && this.parent.getWorldMatrix) {
  8560. this.computeTransformedPosition();
  8561. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8562. return;
  8563. }
  8564. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8565. };
  8566. PointLight.prototype.needCube = function () {
  8567. return true;
  8568. };
  8569. PointLight.prototype.supportsVSM = function () {
  8570. return false;
  8571. };
  8572. PointLight.prototype.needRefreshPerFrame = function () {
  8573. return false;
  8574. };
  8575. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8576. switch (faceIndex) {
  8577. case 0:
  8578. return new BABYLON.Vector3(1, 0, 0);
  8579. case 1:
  8580. return new BABYLON.Vector3(-1, 0, 0);
  8581. case 2:
  8582. return new BABYLON.Vector3(0, -1, 0);
  8583. case 3:
  8584. return new BABYLON.Vector3(0, 1, 0);
  8585. case 4:
  8586. return new BABYLON.Vector3(0, 0, 1);
  8587. case 5:
  8588. return new BABYLON.Vector3(0, 0, -1);
  8589. }
  8590. return BABYLON.Vector3.Zero();
  8591. };
  8592. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8593. var activeCamera = this.getScene().activeCamera;
  8594. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8595. };
  8596. PointLight.prototype._getWorldMatrix = function () {
  8597. if (!this._worldMatrix) {
  8598. this._worldMatrix = BABYLON.Matrix.Identity();
  8599. }
  8600. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8601. return this._worldMatrix;
  8602. };
  8603. PointLight.prototype.serialize = function () {
  8604. var serializationObject = _super.prototype.serialize.call(this);
  8605. serializationObject.type = 0;
  8606. serializationObject.position = this.position.asArray();
  8607. return serializationObject;
  8608. };
  8609. return PointLight;
  8610. })(BABYLON.Light);
  8611. BABYLON.PointLight = PointLight;
  8612. })(BABYLON || (BABYLON = {}));
  8613. var BABYLON;
  8614. (function (BABYLON) {
  8615. var SpotLight = (function (_super) {
  8616. __extends(SpotLight, _super);
  8617. function SpotLight(name, position, direction, angle, exponent, scene) {
  8618. _super.call(this, name, scene);
  8619. this.position = position;
  8620. this.direction = direction;
  8621. this.angle = angle;
  8622. this.exponent = exponent;
  8623. }
  8624. SpotLight.prototype.getAbsolutePosition = function () {
  8625. return this.transformedPosition ? this.transformedPosition : this.position;
  8626. };
  8627. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8628. var activeCamera = this.getScene().activeCamera;
  8629. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8630. };
  8631. SpotLight.prototype.needCube = function () {
  8632. return false;
  8633. };
  8634. SpotLight.prototype.supportsVSM = function () {
  8635. return true;
  8636. };
  8637. SpotLight.prototype.needRefreshPerFrame = function () {
  8638. return false;
  8639. };
  8640. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8641. return this.direction;
  8642. };
  8643. SpotLight.prototype.setDirectionToTarget = function (target) {
  8644. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8645. return this.direction;
  8646. };
  8647. SpotLight.prototype.computeTransformedPosition = function () {
  8648. if (this.parent && this.parent.getWorldMatrix) {
  8649. if (!this.transformedPosition) {
  8650. this.transformedPosition = BABYLON.Vector3.Zero();
  8651. }
  8652. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8653. return true;
  8654. }
  8655. return false;
  8656. };
  8657. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8658. var normalizeDirection;
  8659. if (this.parent && this.parent.getWorldMatrix) {
  8660. if (!this._transformedDirection) {
  8661. this._transformedDirection = BABYLON.Vector3.Zero();
  8662. }
  8663. this.computeTransformedPosition();
  8664. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8665. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8666. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8667. }
  8668. else {
  8669. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8670. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8671. }
  8672. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8673. };
  8674. SpotLight.prototype._getWorldMatrix = function () {
  8675. if (!this._worldMatrix) {
  8676. this._worldMatrix = BABYLON.Matrix.Identity();
  8677. }
  8678. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8679. return this._worldMatrix;
  8680. };
  8681. SpotLight.prototype.serialize = function () {
  8682. var serializationObject = _super.prototype.serialize.call(this);
  8683. serializationObject.type = 2;
  8684. serializationObject.position = this.position.asArray();
  8685. serializationObject.direction = this.position.asArray();
  8686. serializationObject.angle = this.angle;
  8687. serializationObject.exponent = this.exponent;
  8688. return serializationObject;
  8689. };
  8690. return SpotLight;
  8691. })(BABYLON.Light);
  8692. BABYLON.SpotLight = SpotLight;
  8693. })(BABYLON || (BABYLON = {}));
  8694. var BABYLON;
  8695. (function (BABYLON) {
  8696. var HemisphericLight = (function (_super) {
  8697. __extends(HemisphericLight, _super);
  8698. function HemisphericLight(name, direction, scene) {
  8699. _super.call(this, name, scene);
  8700. this.direction = direction;
  8701. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8702. }
  8703. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8704. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8705. return this.direction;
  8706. };
  8707. HemisphericLight.prototype.getShadowGenerator = function () {
  8708. return null;
  8709. };
  8710. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8711. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8712. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8713. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8714. };
  8715. HemisphericLight.prototype._getWorldMatrix = function () {
  8716. if (!this._worldMatrix) {
  8717. this._worldMatrix = BABYLON.Matrix.Identity();
  8718. }
  8719. return this._worldMatrix;
  8720. };
  8721. HemisphericLight.prototype.serialize = function () {
  8722. var serializationObject = _super.prototype.serialize.call(this);
  8723. serializationObject.type = 3;
  8724. serializationObject.direction = this.direction.asArray();
  8725. serializationObject.groundColor = this.groundColor.asArray();
  8726. return serializationObject;
  8727. };
  8728. return HemisphericLight;
  8729. })(BABYLON.Light);
  8730. BABYLON.HemisphericLight = HemisphericLight;
  8731. })(BABYLON || (BABYLON = {}));
  8732. var BABYLON;
  8733. (function (BABYLON) {
  8734. var DirectionalLight = (function (_super) {
  8735. __extends(DirectionalLight, _super);
  8736. function DirectionalLight(name, direction, scene) {
  8737. _super.call(this, name, scene);
  8738. this.direction = direction;
  8739. this.shadowOrthoScale = 0.5;
  8740. this.autoUpdateExtends = true;
  8741. // Cache
  8742. this._orthoLeft = Number.MAX_VALUE;
  8743. this._orthoRight = Number.MIN_VALUE;
  8744. this._orthoTop = Number.MIN_VALUE;
  8745. this._orthoBottom = Number.MAX_VALUE;
  8746. this.position = direction.scale(-1);
  8747. }
  8748. DirectionalLight.prototype.getAbsolutePosition = function () {
  8749. return this.transformedPosition ? this.transformedPosition : this.position;
  8750. };
  8751. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8752. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8753. return this.direction;
  8754. };
  8755. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8756. var activeCamera = this.getScene().activeCamera;
  8757. // Check extends
  8758. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8759. var tempVector3 = BABYLON.Vector3.Zero();
  8760. this._orthoLeft = Number.MAX_VALUE;
  8761. this._orthoRight = Number.MIN_VALUE;
  8762. this._orthoTop = Number.MIN_VALUE;
  8763. this._orthoBottom = Number.MAX_VALUE;
  8764. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8765. var mesh = renderList[meshIndex];
  8766. if (!mesh) {
  8767. continue;
  8768. }
  8769. var boundingInfo = mesh.getBoundingInfo();
  8770. if (!boundingInfo) {
  8771. continue;
  8772. }
  8773. var boundingBox = boundingInfo.boundingBox;
  8774. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8775. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8776. if (tempVector3.x < this._orthoLeft)
  8777. this._orthoLeft = tempVector3.x;
  8778. if (tempVector3.y < this._orthoBottom)
  8779. this._orthoBottom = tempVector3.y;
  8780. if (tempVector3.x > this._orthoRight)
  8781. this._orthoRight = tempVector3.x;
  8782. if (tempVector3.y > this._orthoTop)
  8783. this._orthoTop = tempVector3.y;
  8784. }
  8785. }
  8786. }
  8787. var xOffset = this._orthoRight - this._orthoLeft;
  8788. var yOffset = this._orthoTop - this._orthoBottom;
  8789. 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);
  8790. };
  8791. DirectionalLight.prototype.supportsVSM = function () {
  8792. return true;
  8793. };
  8794. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8795. return true;
  8796. };
  8797. DirectionalLight.prototype.needCube = function () {
  8798. return false;
  8799. };
  8800. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8801. return this.direction;
  8802. };
  8803. DirectionalLight.prototype.computeTransformedPosition = function () {
  8804. if (this.parent && this.parent.getWorldMatrix) {
  8805. if (!this.transformedPosition) {
  8806. this.transformedPosition = BABYLON.Vector3.Zero();
  8807. }
  8808. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8809. return true;
  8810. }
  8811. return false;
  8812. };
  8813. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8814. if (this.parent && this.parent.getWorldMatrix) {
  8815. if (!this._transformedDirection) {
  8816. this._transformedDirection = BABYLON.Vector3.Zero();
  8817. }
  8818. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8819. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8820. return;
  8821. }
  8822. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8823. };
  8824. DirectionalLight.prototype._getWorldMatrix = function () {
  8825. if (!this._worldMatrix) {
  8826. this._worldMatrix = BABYLON.Matrix.Identity();
  8827. }
  8828. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8829. return this._worldMatrix;
  8830. };
  8831. DirectionalLight.prototype.serialize = function () {
  8832. var serializationObject = _super.prototype.serialize.call(this);
  8833. serializationObject.type = 1;
  8834. serializationObject.position = this.position.asArray();
  8835. serializationObject.direction = this.direction.asArray();
  8836. return serializationObject;
  8837. };
  8838. return DirectionalLight;
  8839. })(BABYLON.Light);
  8840. BABYLON.DirectionalLight = DirectionalLight;
  8841. })(BABYLON || (BABYLON = {}));
  8842. var BABYLON;
  8843. (function (BABYLON) {
  8844. var ShadowGenerator = (function () {
  8845. function ShadowGenerator(mapSize, light) {
  8846. var _this = this;
  8847. // Members
  8848. this._filter = ShadowGenerator.FILTER_NONE;
  8849. this.blurScale = 2;
  8850. this._blurBoxOffset = 0;
  8851. this._bias = 0.00005;
  8852. this._lightDirection = BABYLON.Vector3.Zero();
  8853. this._darkness = 0;
  8854. this._transparencyShadow = false;
  8855. this._viewMatrix = BABYLON.Matrix.Zero();
  8856. this._projectionMatrix = BABYLON.Matrix.Zero();
  8857. this._transformMatrix = BABYLON.Matrix.Zero();
  8858. this._worldViewProjection = BABYLON.Matrix.Zero();
  8859. this._currentFaceIndex = 0;
  8860. this._currentFaceIndexCache = 0;
  8861. this._light = light;
  8862. this._scene = light.getScene();
  8863. this._mapSize = mapSize;
  8864. light._shadowGenerator = this;
  8865. // Render target
  8866. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8867. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8868. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8869. this._shadowMap.anisotropicFilteringLevel = 1;
  8870. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8871. this._shadowMap.renderParticles = false;
  8872. this._shadowMap.onBeforeRender = function (faceIndex) {
  8873. _this._currentFaceIndex = faceIndex;
  8874. };
  8875. this._shadowMap.onAfterUnbind = function () {
  8876. if (!_this.useBlurVarianceShadowMap) {
  8877. return;
  8878. }
  8879. if (!_this._shadowMap2) {
  8880. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8881. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8882. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8883. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8884. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8885. _this._downSamplePostprocess.onApply = function (effect) {
  8886. effect.setTexture("textureSampler", _this._shadowMap);
  8887. };
  8888. _this.blurBoxOffset = 1;
  8889. }
  8890. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8891. };
  8892. // Custom render function
  8893. var renderSubMesh = function (subMesh) {
  8894. var mesh = subMesh.getRenderingMesh();
  8895. var scene = _this._scene;
  8896. var engine = scene.getEngine();
  8897. // Culling
  8898. engine.setState(subMesh.getMaterial().backFaceCulling);
  8899. // Managing instances
  8900. var batch = mesh._getInstancesRenderList(subMesh._id);
  8901. if (batch.mustReturn) {
  8902. return;
  8903. }
  8904. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8905. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8906. engine.enableEffect(_this._effect);
  8907. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8908. var material = subMesh.getMaterial();
  8909. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8910. // Alpha test
  8911. if (material && material.needAlphaTesting()) {
  8912. var alphaTexture = material.getAlphaTestTexture();
  8913. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8914. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8915. }
  8916. // Bones
  8917. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8918. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8919. }
  8920. // Draw
  8921. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8922. }
  8923. else {
  8924. // Need to reset refresh rate of the shadowMap
  8925. _this._shadowMap.resetRefreshCounter();
  8926. }
  8927. };
  8928. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8929. var index;
  8930. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8931. renderSubMesh(opaqueSubMeshes.data[index]);
  8932. }
  8933. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8934. renderSubMesh(alphaTestSubMeshes.data[index]);
  8935. }
  8936. if (_this._transparencyShadow) {
  8937. for (index = 0; index < transparentSubMeshes.length; index++) {
  8938. renderSubMesh(transparentSubMeshes.data[index]);
  8939. }
  8940. }
  8941. };
  8942. this._shadowMap.onClear = function (engine) {
  8943. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8944. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8945. }
  8946. else {
  8947. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8948. }
  8949. };
  8950. }
  8951. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8952. // Static
  8953. get: function () {
  8954. return ShadowGenerator._FILTER_NONE;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8960. get: function () {
  8961. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8967. get: function () {
  8968. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8974. get: function () {
  8975. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8976. },
  8977. enumerable: true,
  8978. configurable: true
  8979. });
  8980. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8981. get: function () {
  8982. return this._bias;
  8983. },
  8984. set: function (bias) {
  8985. this._bias = bias;
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8991. get: function () {
  8992. return this._blurBoxOffset;
  8993. },
  8994. set: function (value) {
  8995. var _this = this;
  8996. if (this._blurBoxOffset === value) {
  8997. return;
  8998. }
  8999. this._blurBoxOffset = value;
  9000. if (this._boxBlurPostprocess) {
  9001. this._boxBlurPostprocess.dispose();
  9002. }
  9003. 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);
  9004. this._boxBlurPostprocess.onApply = function (effect) {
  9005. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9006. };
  9007. },
  9008. enumerable: true,
  9009. configurable: true
  9010. });
  9011. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9012. get: function () {
  9013. return this._filter;
  9014. },
  9015. set: function (value) {
  9016. if (this._filter === value) {
  9017. return;
  9018. }
  9019. this._filter = value;
  9020. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9021. this._shadowMap.anisotropicFilteringLevel = 16;
  9022. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9023. }
  9024. else {
  9025. this._shadowMap.anisotropicFilteringLevel = 1;
  9026. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9027. }
  9028. },
  9029. enumerable: true,
  9030. configurable: true
  9031. });
  9032. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9033. get: function () {
  9034. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9035. },
  9036. set: function (value) {
  9037. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9038. },
  9039. enumerable: true,
  9040. configurable: true
  9041. });
  9042. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9043. get: function () {
  9044. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9045. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9046. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9047. },
  9048. set: function (value) {
  9049. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9055. get: function () {
  9056. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9057. },
  9058. set: function (value) {
  9059. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9065. var defines = [];
  9066. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9067. defines.push("#define VSM");
  9068. }
  9069. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9070. var mesh = subMesh.getMesh();
  9071. var material = subMesh.getMaterial();
  9072. // Alpha test
  9073. if (material && material.needAlphaTesting()) {
  9074. defines.push("#define ALPHATEST");
  9075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9076. attribs.push(BABYLON.VertexBuffer.UVKind);
  9077. defines.push("#define UV1");
  9078. }
  9079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9080. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9081. defines.push("#define UV2");
  9082. }
  9083. }
  9084. // Bones
  9085. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9086. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9087. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9088. if (mesh.numBoneInfluencers > 4) {
  9089. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9090. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9091. }
  9092. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9093. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9094. }
  9095. else {
  9096. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9097. }
  9098. // Instances
  9099. if (useInstances) {
  9100. defines.push("#define INSTANCES");
  9101. attribs.push("world0");
  9102. attribs.push("world1");
  9103. attribs.push("world2");
  9104. attribs.push("world3");
  9105. }
  9106. // Get correct effect
  9107. var join = defines.join("\n");
  9108. if (this._cachedDefines !== join) {
  9109. this._cachedDefines = join;
  9110. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9111. }
  9112. return this._effect.isReady();
  9113. };
  9114. ShadowGenerator.prototype.getShadowMap = function () {
  9115. return this._shadowMap;
  9116. };
  9117. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9118. if (this._shadowMap2) {
  9119. return this._shadowMap2;
  9120. }
  9121. return this._shadowMap;
  9122. };
  9123. ShadowGenerator.prototype.getLight = function () {
  9124. return this._light;
  9125. };
  9126. // Methods
  9127. ShadowGenerator.prototype.getTransformMatrix = function () {
  9128. var scene = this._scene;
  9129. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9130. return this._transformMatrix;
  9131. }
  9132. this._currentRenderID = scene.getRenderId();
  9133. this._currentFaceIndexCache = this._currentFaceIndex;
  9134. var lightPosition = this._light.position;
  9135. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9136. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9137. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9138. }
  9139. if (this._light.computeTransformedPosition()) {
  9140. lightPosition = this._light.transformedPosition;
  9141. }
  9142. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9143. this._cachedPosition = lightPosition.clone();
  9144. this._cachedDirection = this._lightDirection.clone();
  9145. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9146. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9147. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9148. }
  9149. return this._transformMatrix;
  9150. };
  9151. ShadowGenerator.prototype.getDarkness = function () {
  9152. return this._darkness;
  9153. };
  9154. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9155. if (darkness >= 1.0)
  9156. this._darkness = 1.0;
  9157. else if (darkness <= 0.0)
  9158. this._darkness = 0.0;
  9159. else
  9160. this._darkness = darkness;
  9161. };
  9162. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9163. this._transparencyShadow = hasShadow;
  9164. };
  9165. ShadowGenerator.prototype._packHalf = function (depth) {
  9166. var scale = depth * 255.0;
  9167. var fract = scale - Math.floor(scale);
  9168. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9169. };
  9170. ShadowGenerator.prototype.dispose = function () {
  9171. this._shadowMap.dispose();
  9172. if (this._shadowMap2) {
  9173. this._shadowMap2.dispose();
  9174. }
  9175. if (this._downSamplePostprocess) {
  9176. this._downSamplePostprocess.dispose();
  9177. }
  9178. if (this._boxBlurPostprocess) {
  9179. this._boxBlurPostprocess.dispose();
  9180. }
  9181. };
  9182. ShadowGenerator.prototype.serialize = function () {
  9183. var serializationObject = {};
  9184. serializationObject.lightId = this._light.id;
  9185. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9186. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9187. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9188. serializationObject.renderList = [];
  9189. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9190. var mesh = this.getShadowMap().renderList[meshIndex];
  9191. serializationObject.renderList.push(mesh.id);
  9192. }
  9193. return serializationObject;
  9194. };
  9195. ShadowGenerator.ParseShadowGenerator = function (parsedShadowGenerator, scene) {
  9196. //casting to point light, as light is missing the position attr and typescript complains.
  9197. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9198. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9199. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9200. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9201. shadowGenerator.getShadowMap().renderList.push(mesh);
  9202. }
  9203. if (parsedShadowGenerator.usePoissonSampling) {
  9204. shadowGenerator.usePoissonSampling = true;
  9205. }
  9206. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9207. shadowGenerator.useVarianceShadowMap = true;
  9208. }
  9209. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9210. shadowGenerator.useBlurVarianceShadowMap = true;
  9211. if (parsedShadowGenerator.blurScale) {
  9212. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9213. }
  9214. if (parsedShadowGenerator.blurBoxOffset) {
  9215. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9216. }
  9217. }
  9218. if (parsedShadowGenerator.bias !== undefined) {
  9219. shadowGenerator.bias = parsedShadowGenerator.bias;
  9220. }
  9221. return shadowGenerator;
  9222. };
  9223. ShadowGenerator._FILTER_NONE = 0;
  9224. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9225. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9226. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9227. return ShadowGenerator;
  9228. })();
  9229. BABYLON.ShadowGenerator = ShadowGenerator;
  9230. })(BABYLON || (BABYLON = {}));
  9231. var BABYLON;
  9232. (function (BABYLON) {
  9233. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9234. if (boxMin.x > sphereCenter.x + sphereRadius)
  9235. return false;
  9236. if (sphereCenter.x - sphereRadius > boxMax.x)
  9237. return false;
  9238. if (boxMin.y > sphereCenter.y + sphereRadius)
  9239. return false;
  9240. if (sphereCenter.y - sphereRadius > boxMax.y)
  9241. return false;
  9242. if (boxMin.z > sphereCenter.z + sphereRadius)
  9243. return false;
  9244. if (sphereCenter.z - sphereRadius > boxMax.z)
  9245. return false;
  9246. return true;
  9247. };
  9248. var getLowestRoot = function (a, b, c, maxR) {
  9249. var determinant = b * b - 4.0 * a * c;
  9250. var result = { root: 0, found: false };
  9251. if (determinant < 0)
  9252. return result;
  9253. var sqrtD = Math.sqrt(determinant);
  9254. var r1 = (-b - sqrtD) / (2.0 * a);
  9255. var r2 = (-b + sqrtD) / (2.0 * a);
  9256. if (r1 > r2) {
  9257. var temp = r2;
  9258. r2 = r1;
  9259. r1 = temp;
  9260. }
  9261. if (r1 > 0 && r1 < maxR) {
  9262. result.root = r1;
  9263. result.found = true;
  9264. return result;
  9265. }
  9266. if (r2 > 0 && r2 < maxR) {
  9267. result.root = r2;
  9268. result.found = true;
  9269. return result;
  9270. }
  9271. return result;
  9272. };
  9273. var Collider = (function () {
  9274. function Collider() {
  9275. this.radius = new BABYLON.Vector3(1, 1, 1);
  9276. this.retry = 0;
  9277. this.basePointWorld = BABYLON.Vector3.Zero();
  9278. this.velocityWorld = BABYLON.Vector3.Zero();
  9279. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9280. this._collisionPoint = BABYLON.Vector3.Zero();
  9281. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9282. this._tempVector = BABYLON.Vector3.Zero();
  9283. this._tempVector2 = BABYLON.Vector3.Zero();
  9284. this._tempVector3 = BABYLON.Vector3.Zero();
  9285. this._tempVector4 = BABYLON.Vector3.Zero();
  9286. this._edge = BABYLON.Vector3.Zero();
  9287. this._baseToVertex = BABYLON.Vector3.Zero();
  9288. this._destinationPoint = BABYLON.Vector3.Zero();
  9289. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9290. this._displacementVector = BABYLON.Vector3.Zero();
  9291. }
  9292. // Methods
  9293. Collider.prototype._initialize = function (source, dir, e) {
  9294. this.velocity = dir;
  9295. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9296. this.basePoint = source;
  9297. source.multiplyToRef(this.radius, this.basePointWorld);
  9298. dir.multiplyToRef(this.radius, this.velocityWorld);
  9299. this.velocityWorldLength = this.velocityWorld.length();
  9300. this.epsilon = e;
  9301. this.collisionFound = false;
  9302. };
  9303. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9304. pa.subtractToRef(point, this._tempVector);
  9305. pb.subtractToRef(point, this._tempVector2);
  9306. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9307. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9308. if (d < 0)
  9309. return false;
  9310. pc.subtractToRef(point, this._tempVector3);
  9311. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9312. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9313. if (d < 0)
  9314. return false;
  9315. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9316. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9317. return d >= 0;
  9318. };
  9319. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9320. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9321. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9322. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9323. return false;
  9324. }
  9325. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9326. return false;
  9327. return true;
  9328. };
  9329. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9330. var t0;
  9331. var embeddedInPlane = false;
  9332. //defensive programming, actually not needed.
  9333. if (!trianglePlaneArray) {
  9334. trianglePlaneArray = [];
  9335. }
  9336. if (!trianglePlaneArray[faceIndex]) {
  9337. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9338. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9339. }
  9340. var trianglePlane = trianglePlaneArray[faceIndex];
  9341. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9342. return;
  9343. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9344. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9345. if (normalDotVelocity == 0) {
  9346. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9347. return;
  9348. embeddedInPlane = true;
  9349. t0 = 0;
  9350. }
  9351. else {
  9352. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9353. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9354. if (t0 > t1) {
  9355. var temp = t1;
  9356. t1 = t0;
  9357. t0 = temp;
  9358. }
  9359. if (t0 > 1.0 || t1 < 0.0)
  9360. return;
  9361. if (t0 < 0)
  9362. t0 = 0;
  9363. if (t0 > 1.0)
  9364. t0 = 1.0;
  9365. }
  9366. this._collisionPoint.copyFromFloats(0, 0, 0);
  9367. var found = false;
  9368. var t = 1.0;
  9369. if (!embeddedInPlane) {
  9370. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9371. this.velocity.scaleToRef(t0, this._tempVector);
  9372. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9373. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9374. found = true;
  9375. t = t0;
  9376. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9377. }
  9378. }
  9379. if (!found) {
  9380. var velocitySquaredLength = this.velocity.lengthSquared();
  9381. var a = velocitySquaredLength;
  9382. this.basePoint.subtractToRef(p1, this._tempVector);
  9383. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9384. var c = this._tempVector.lengthSquared() - 1.0;
  9385. var lowestRoot = getLowestRoot(a, b, c, t);
  9386. if (lowestRoot.found) {
  9387. t = lowestRoot.root;
  9388. found = true;
  9389. this._collisionPoint.copyFrom(p1);
  9390. }
  9391. this.basePoint.subtractToRef(p2, this._tempVector);
  9392. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9393. c = this._tempVector.lengthSquared() - 1.0;
  9394. lowestRoot = getLowestRoot(a, b, c, t);
  9395. if (lowestRoot.found) {
  9396. t = lowestRoot.root;
  9397. found = true;
  9398. this._collisionPoint.copyFrom(p2);
  9399. }
  9400. this.basePoint.subtractToRef(p3, this._tempVector);
  9401. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9402. c = this._tempVector.lengthSquared() - 1.0;
  9403. lowestRoot = getLowestRoot(a, b, c, t);
  9404. if (lowestRoot.found) {
  9405. t = lowestRoot.root;
  9406. found = true;
  9407. this._collisionPoint.copyFrom(p3);
  9408. }
  9409. p2.subtractToRef(p1, this._edge);
  9410. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9411. var edgeSquaredLength = this._edge.lengthSquared();
  9412. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9413. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9414. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9415. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9416. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9417. lowestRoot = getLowestRoot(a, b, c, t);
  9418. if (lowestRoot.found) {
  9419. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9420. if (f >= 0.0 && f <= 1.0) {
  9421. t = lowestRoot.root;
  9422. found = true;
  9423. this._edge.scaleInPlace(f);
  9424. p1.addToRef(this._edge, this._collisionPoint);
  9425. }
  9426. }
  9427. p3.subtractToRef(p2, this._edge);
  9428. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9429. edgeSquaredLength = this._edge.lengthSquared();
  9430. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9431. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9432. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9433. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9434. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9435. lowestRoot = getLowestRoot(a, b, c, t);
  9436. if (lowestRoot.found) {
  9437. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9438. if (f >= 0.0 && f <= 1.0) {
  9439. t = lowestRoot.root;
  9440. found = true;
  9441. this._edge.scaleInPlace(f);
  9442. p2.addToRef(this._edge, this._collisionPoint);
  9443. }
  9444. }
  9445. p1.subtractToRef(p3, this._edge);
  9446. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9447. edgeSquaredLength = this._edge.lengthSquared();
  9448. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9449. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9450. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9451. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9452. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9453. lowestRoot = getLowestRoot(a, b, c, t);
  9454. if (lowestRoot.found) {
  9455. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9456. if (f >= 0.0 && f <= 1.0) {
  9457. t = lowestRoot.root;
  9458. found = true;
  9459. this._edge.scaleInPlace(f);
  9460. p3.addToRef(this._edge, this._collisionPoint);
  9461. }
  9462. }
  9463. }
  9464. if (found) {
  9465. var distToCollision = t * this.velocity.length();
  9466. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9467. if (!this.intersectionPoint) {
  9468. this.intersectionPoint = this._collisionPoint.clone();
  9469. }
  9470. else {
  9471. this.intersectionPoint.copyFrom(this._collisionPoint);
  9472. }
  9473. this.nearestDistance = distToCollision;
  9474. this.collisionFound = true;
  9475. }
  9476. }
  9477. };
  9478. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9479. for (var i = indexStart; i < indexEnd; i += 3) {
  9480. var p1 = pts[indices[i] - decal];
  9481. var p2 = pts[indices[i + 1] - decal];
  9482. var p3 = pts[indices[i + 2] - decal];
  9483. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9484. }
  9485. };
  9486. Collider.prototype._getResponse = function (pos, vel) {
  9487. pos.addToRef(vel, this._destinationPoint);
  9488. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9489. this.basePoint.addToRef(vel, pos);
  9490. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9491. this._slidePlaneNormal.normalize();
  9492. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9493. pos.addInPlace(this._displacementVector);
  9494. this.intersectionPoint.addInPlace(this._displacementVector);
  9495. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9496. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9497. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9498. };
  9499. return Collider;
  9500. })();
  9501. BABYLON.Collider = Collider;
  9502. })(BABYLON || (BABYLON = {}));
  9503. var BABYLON;
  9504. (function (BABYLON) {
  9505. //WebWorker code will be inserted to this variable.
  9506. BABYLON.CollisionWorker = "";
  9507. (function (WorkerTaskType) {
  9508. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9509. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9510. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9511. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9512. var WorkerTaskType = BABYLON.WorkerTaskType;
  9513. (function (WorkerReplyType) {
  9514. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9515. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9516. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9517. var WorkerReplyType = BABYLON.WorkerReplyType;
  9518. var CollisionCoordinatorWorker = (function () {
  9519. function CollisionCoordinatorWorker() {
  9520. var _this = this;
  9521. this._scaledPosition = BABYLON.Vector3.Zero();
  9522. this._scaledVelocity = BABYLON.Vector3.Zero();
  9523. this.onMeshUpdated = function (mesh) {
  9524. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9525. };
  9526. this.onGeometryUpdated = function (geometry) {
  9527. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9528. };
  9529. this._afterRender = function () {
  9530. if (!_this._init)
  9531. return;
  9532. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9533. return;
  9534. }
  9535. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9536. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9537. if (_this._runningUpdated > 4) {
  9538. return;
  9539. }
  9540. ++_this._runningUpdated;
  9541. var payload = {
  9542. updatedMeshes: _this._addUpdateMeshesList,
  9543. updatedGeometries: _this._addUpdateGeometriesList,
  9544. removedGeometries: _this._toRemoveGeometryArray,
  9545. removedMeshes: _this._toRemoveMeshesArray
  9546. };
  9547. var message = {
  9548. payload: payload,
  9549. taskType: WorkerTaskType.UPDATE
  9550. };
  9551. var serializable = [];
  9552. for (var id in payload.updatedGeometries) {
  9553. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9554. //prepare transferables
  9555. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9556. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9557. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9558. }
  9559. }
  9560. _this._worker.postMessage(message, serializable);
  9561. _this._addUpdateMeshesList = {};
  9562. _this._addUpdateGeometriesList = {};
  9563. _this._toRemoveGeometryArray = [];
  9564. _this._toRemoveMeshesArray = [];
  9565. };
  9566. this._onMessageFromWorker = function (e) {
  9567. var returnData = e.data;
  9568. if (returnData.error != WorkerReplyType.SUCCESS) {
  9569. //TODO what errors can be returned from the worker?
  9570. BABYLON.Tools.Warn("error returned from worker!");
  9571. return;
  9572. }
  9573. switch (returnData.taskType) {
  9574. case WorkerTaskType.INIT:
  9575. _this._init = true;
  9576. //Update the worked with ALL of the scene's current state
  9577. _this._scene.meshes.forEach(function (mesh) {
  9578. _this.onMeshAdded(mesh);
  9579. });
  9580. _this._scene.getGeometries().forEach(function (geometry) {
  9581. _this.onGeometryAdded(geometry);
  9582. });
  9583. break;
  9584. case WorkerTaskType.UPDATE:
  9585. _this._runningUpdated--;
  9586. break;
  9587. case WorkerTaskType.COLLIDE:
  9588. _this._runningCollisionTask = false;
  9589. var returnPayload = returnData.payload;
  9590. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9591. return;
  9592. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9593. //cleanup
  9594. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9595. break;
  9596. }
  9597. };
  9598. this._collisionsCallbackArray = [];
  9599. this._init = false;
  9600. this._runningUpdated = 0;
  9601. this._runningCollisionTask = false;
  9602. this._addUpdateMeshesList = {};
  9603. this._addUpdateGeometriesList = {};
  9604. this._toRemoveGeometryArray = [];
  9605. this._toRemoveMeshesArray = [];
  9606. }
  9607. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9608. if (!this._init)
  9609. return;
  9610. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9611. return;
  9612. position.divideToRef(collider.radius, this._scaledPosition);
  9613. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9614. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9615. var payload = {
  9616. collider: {
  9617. position: this._scaledPosition.asArray(),
  9618. velocity: this._scaledVelocity.asArray(),
  9619. radius: collider.radius.asArray()
  9620. },
  9621. collisionId: collisionIndex,
  9622. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9623. maximumRetry: maximumRetry
  9624. };
  9625. var message = {
  9626. payload: payload,
  9627. taskType: WorkerTaskType.COLLIDE
  9628. };
  9629. this._worker.postMessage(message);
  9630. };
  9631. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9632. this._scene = scene;
  9633. this._scene.registerAfterRender(this._afterRender);
  9634. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9635. this._worker = new Worker(workerUrl);
  9636. this._worker.onmessage = this._onMessageFromWorker;
  9637. var message = {
  9638. payload: {},
  9639. taskType: WorkerTaskType.INIT
  9640. };
  9641. this._worker.postMessage(message);
  9642. };
  9643. CollisionCoordinatorWorker.prototype.destroy = function () {
  9644. this._scene.unregisterAfterRender(this._afterRender);
  9645. this._worker.terminate();
  9646. };
  9647. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9648. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9649. this.onMeshUpdated(mesh);
  9650. };
  9651. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9652. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9655. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9656. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9657. this.onGeometryUpdated(geometry);
  9658. };
  9659. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9660. this._toRemoveGeometryArray.push(geometry.id);
  9661. };
  9662. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9663. var submeshes = [];
  9664. if (mesh.subMeshes) {
  9665. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9666. return {
  9667. position: idx,
  9668. verticesStart: sm.verticesStart,
  9669. verticesCount: sm.verticesCount,
  9670. indexStart: sm.indexStart,
  9671. indexCount: sm.indexCount,
  9672. hasMaterial: !!sm.getMaterial(),
  9673. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9674. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9675. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9676. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9677. };
  9678. });
  9679. }
  9680. var geometryId = null;
  9681. if (mesh instanceof BABYLON.Mesh) {
  9682. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9683. }
  9684. else if (mesh instanceof BABYLON.InstancedMesh) {
  9685. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9686. }
  9687. return {
  9688. uniqueId: mesh.uniqueId,
  9689. id: mesh.id,
  9690. name: mesh.name,
  9691. geometryId: geometryId,
  9692. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9693. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9694. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9695. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9696. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9697. subMeshes: submeshes,
  9698. checkCollisions: mesh.checkCollisions
  9699. };
  9700. };
  9701. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9702. return {
  9703. id: geometry.id,
  9704. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9705. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9706. indices: new Int32Array(geometry.getIndices() || []),
  9707. };
  9708. };
  9709. return CollisionCoordinatorWorker;
  9710. })();
  9711. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9712. var CollisionCoordinatorLegacy = (function () {
  9713. function CollisionCoordinatorLegacy() {
  9714. this._scaledPosition = BABYLON.Vector3.Zero();
  9715. this._scaledVelocity = BABYLON.Vector3.Zero();
  9716. this._finalPosition = BABYLON.Vector3.Zero();
  9717. }
  9718. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9719. position.divideToRef(collider.radius, this._scaledPosition);
  9720. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9721. collider.collidedMesh = null;
  9722. collider.retry = 0;
  9723. collider.initialVelocity = this._scaledVelocity;
  9724. collider.initialPosition = this._scaledPosition;
  9725. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9726. this._finalPosition.multiplyInPlace(collider.radius);
  9727. //run the callback
  9728. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9729. };
  9730. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9731. this._scene = scene;
  9732. };
  9733. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9734. //Legacy need no destruction method.
  9735. };
  9736. //No update in legacy mode
  9737. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9738. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9739. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9740. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9741. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9742. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9743. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9744. if (excludedMesh === void 0) { excludedMesh = null; }
  9745. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9746. if (collider.retry >= maximumRetry) {
  9747. finalPosition.copyFrom(position);
  9748. return;
  9749. }
  9750. collider._initialize(position, velocity, closeDistance);
  9751. // Check all meshes
  9752. for (var index = 0; index < this._scene.meshes.length; index++) {
  9753. var mesh = this._scene.meshes[index];
  9754. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9755. mesh._checkCollision(collider);
  9756. }
  9757. }
  9758. if (!collider.collisionFound) {
  9759. position.addToRef(velocity, finalPosition);
  9760. return;
  9761. }
  9762. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9763. collider._getResponse(position, velocity);
  9764. }
  9765. if (velocity.length() <= closeDistance) {
  9766. finalPosition.copyFrom(position);
  9767. return;
  9768. }
  9769. collider.retry++;
  9770. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9771. };
  9772. return CollisionCoordinatorLegacy;
  9773. })();
  9774. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9775. })(BABYLON || (BABYLON = {}));
  9776. var BABYLON;
  9777. (function (BABYLON) {
  9778. var VRCameraMetrics = (function () {
  9779. function VRCameraMetrics() {
  9780. this.compensateDistortion = true;
  9781. }
  9782. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9783. get: function () {
  9784. return this.hResolution / (2 * this.vResolution);
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9790. get: function () {
  9791. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9792. },
  9793. enumerable: true,
  9794. configurable: true
  9795. });
  9796. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9797. get: function () {
  9798. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9799. var h = (4 * meters) / this.hScreenSize;
  9800. return BABYLON.Matrix.Translation(h, 0, 0);
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9806. get: function () {
  9807. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9808. var h = (4 * meters) / this.hScreenSize;
  9809. return BABYLON.Matrix.Translation(-h, 0, 0);
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9815. get: function () {
  9816. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9822. get: function () {
  9823. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. VRCameraMetrics.GetDefault = function () {
  9829. var result = new VRCameraMetrics();
  9830. result.hResolution = 1280;
  9831. result.vResolution = 800;
  9832. result.hScreenSize = 0.149759993;
  9833. result.vScreenSize = 0.0935999975;
  9834. result.vScreenCenter = 0.0467999987,
  9835. result.eyeToScreenDistance = 0.0410000011;
  9836. result.lensSeparationDistance = 0.0635000020;
  9837. result.interpupillaryDistance = 0.0640000030;
  9838. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9839. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9840. result.postProcessScaleFactor = 1.714605507808412;
  9841. result.lensCenterOffset = 0.151976421;
  9842. return result;
  9843. };
  9844. return VRCameraMetrics;
  9845. })();
  9846. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9847. var Camera = (function (_super) {
  9848. __extends(Camera, _super);
  9849. function Camera(name, position, scene) {
  9850. _super.call(this, name, scene);
  9851. this.position = position;
  9852. // Members
  9853. this.upVector = BABYLON.Vector3.Up();
  9854. this.orthoLeft = null;
  9855. this.orthoRight = null;
  9856. this.orthoBottom = null;
  9857. this.orthoTop = null;
  9858. this.fov = 0.8;
  9859. this.minZ = 1.0;
  9860. this.maxZ = 10000.0;
  9861. this.inertia = 0.9;
  9862. this.mode = Camera.PERSPECTIVE_CAMERA;
  9863. this.isIntermediate = false;
  9864. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9865. this.layerMask = 0x0FFFFFFF;
  9866. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9867. // Camera rig members
  9868. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9869. this._rigCameras = new Array();
  9870. // Cache
  9871. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9872. this._projectionMatrix = new BABYLON.Matrix();
  9873. this._postProcesses = new Array();
  9874. this._postProcessesTakenIndices = [];
  9875. this._activeMeshes = new BABYLON.SmartArray(256);
  9876. this._globalPosition = BABYLON.Vector3.Zero();
  9877. scene.addCamera(this);
  9878. if (!scene.activeCamera) {
  9879. scene.activeCamera = this;
  9880. }
  9881. }
  9882. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9883. get: function () {
  9884. return Camera._PERSPECTIVE_CAMERA;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9890. get: function () {
  9891. return Camera._ORTHOGRAPHIC_CAMERA;
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9897. get: function () {
  9898. return Camera._FOVMODE_VERTICAL_FIXED;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9904. get: function () {
  9905. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9911. get: function () {
  9912. return Camera._RIG_MODE_NONE;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9918. get: function () {
  9919. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9925. get: function () {
  9926. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9927. },
  9928. enumerable: true,
  9929. configurable: true
  9930. });
  9931. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9932. get: function () {
  9933. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9939. get: function () {
  9940. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9946. get: function () {
  9947. return Camera._RIG_MODE_VR;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. Object.defineProperty(Camera.prototype, "globalPosition", {
  9953. get: function () {
  9954. return this._globalPosition;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Camera.prototype.getActiveMeshes = function () {
  9960. return this._activeMeshes;
  9961. };
  9962. Camera.prototype.isActiveMesh = function (mesh) {
  9963. return (this._activeMeshes.indexOf(mesh) !== -1);
  9964. };
  9965. //Cache
  9966. Camera.prototype._initCache = function () {
  9967. _super.prototype._initCache.call(this);
  9968. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9969. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9970. this._cache.mode = undefined;
  9971. this._cache.minZ = undefined;
  9972. this._cache.maxZ = undefined;
  9973. this._cache.fov = undefined;
  9974. this._cache.aspectRatio = undefined;
  9975. this._cache.orthoLeft = undefined;
  9976. this._cache.orthoRight = undefined;
  9977. this._cache.orthoBottom = undefined;
  9978. this._cache.orthoTop = undefined;
  9979. this._cache.renderWidth = undefined;
  9980. this._cache.renderHeight = undefined;
  9981. };
  9982. Camera.prototype._updateCache = function (ignoreParentClass) {
  9983. if (!ignoreParentClass) {
  9984. _super.prototype._updateCache.call(this);
  9985. }
  9986. var engine = this.getEngine();
  9987. this._cache.position.copyFrom(this.position);
  9988. this._cache.upVector.copyFrom(this.upVector);
  9989. this._cache.mode = this.mode;
  9990. this._cache.minZ = this.minZ;
  9991. this._cache.maxZ = this.maxZ;
  9992. this._cache.fov = this.fov;
  9993. this._cache.aspectRatio = engine.getAspectRatio(this);
  9994. this._cache.orthoLeft = this.orthoLeft;
  9995. this._cache.orthoRight = this.orthoRight;
  9996. this._cache.orthoBottom = this.orthoBottom;
  9997. this._cache.orthoTop = this.orthoTop;
  9998. this._cache.renderWidth = engine.getRenderWidth();
  9999. this._cache.renderHeight = engine.getRenderHeight();
  10000. };
  10001. Camera.prototype._updateFromScene = function () {
  10002. this.updateCache();
  10003. this._update();
  10004. };
  10005. // Synchronized
  10006. Camera.prototype._isSynchronized = function () {
  10007. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10008. };
  10009. Camera.prototype._isSynchronizedViewMatrix = function () {
  10010. if (!_super.prototype._isSynchronized.call(this))
  10011. return false;
  10012. return this._cache.position.equals(this.position)
  10013. && this._cache.upVector.equals(this.upVector)
  10014. && this.isSynchronizedWithParent();
  10015. };
  10016. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10017. var check = this._cache.mode === this.mode
  10018. && this._cache.minZ === this.minZ
  10019. && this._cache.maxZ === this.maxZ;
  10020. if (!check) {
  10021. return false;
  10022. }
  10023. var engine = this.getEngine();
  10024. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10025. check = this._cache.fov === this.fov
  10026. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10027. }
  10028. else {
  10029. check = this._cache.orthoLeft === this.orthoLeft
  10030. && this._cache.orthoRight === this.orthoRight
  10031. && this._cache.orthoBottom === this.orthoBottom
  10032. && this._cache.orthoTop === this.orthoTop
  10033. && this._cache.renderWidth === engine.getRenderWidth()
  10034. && this._cache.renderHeight === engine.getRenderHeight();
  10035. }
  10036. return check;
  10037. };
  10038. // Controls
  10039. Camera.prototype.attachControl = function (element) {
  10040. };
  10041. Camera.prototype.detachControl = function (element) {
  10042. };
  10043. Camera.prototype._update = function () {
  10044. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10045. this._updateRigCameras();
  10046. }
  10047. this._checkInputs();
  10048. };
  10049. Camera.prototype._checkInputs = function () {
  10050. };
  10051. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10052. if (insertAt === void 0) { insertAt = null; }
  10053. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10054. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10055. return 0;
  10056. }
  10057. if (insertAt == null || insertAt < 0) {
  10058. this._postProcesses.push(postProcess);
  10059. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10060. return this._postProcesses.length - 1;
  10061. }
  10062. var add = 0;
  10063. var i;
  10064. var start;
  10065. if (this._postProcesses[insertAt]) {
  10066. start = this._postProcesses.length - 1;
  10067. for (i = start; i >= insertAt + 1; --i) {
  10068. this._postProcesses[i + 1] = this._postProcesses[i];
  10069. }
  10070. add = 1;
  10071. }
  10072. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10073. if (this._postProcessesTakenIndices[i] < insertAt) {
  10074. continue;
  10075. }
  10076. start = this._postProcessesTakenIndices.length - 1;
  10077. for (var j = start; j >= i; --j) {
  10078. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10079. }
  10080. this._postProcessesTakenIndices[i] = insertAt;
  10081. break;
  10082. }
  10083. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10084. this._postProcessesTakenIndices.push(insertAt);
  10085. }
  10086. var result = insertAt + add;
  10087. this._postProcesses[result] = postProcess;
  10088. return result;
  10089. };
  10090. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10091. if (atIndices === void 0) { atIndices = null; }
  10092. var result = [];
  10093. var i;
  10094. var index;
  10095. if (!atIndices) {
  10096. var length = this._postProcesses.length;
  10097. for (i = 0; i < length; i++) {
  10098. if (this._postProcesses[i] !== postProcess) {
  10099. continue;
  10100. }
  10101. delete this._postProcesses[i];
  10102. index = this._postProcessesTakenIndices.indexOf(i);
  10103. this._postProcessesTakenIndices.splice(index, 1);
  10104. }
  10105. }
  10106. else {
  10107. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10108. for (i = 0; i < atIndices.length; i++) {
  10109. var foundPostProcess = this._postProcesses[atIndices[i]];
  10110. if (foundPostProcess !== postProcess) {
  10111. result.push(i);
  10112. continue;
  10113. }
  10114. delete this._postProcesses[atIndices[i]];
  10115. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10116. this._postProcessesTakenIndices.splice(index, 1);
  10117. }
  10118. }
  10119. return result;
  10120. };
  10121. Camera.prototype.getWorldMatrix = function () {
  10122. if (!this._worldMatrix) {
  10123. this._worldMatrix = BABYLON.Matrix.Identity();
  10124. }
  10125. var viewMatrix = this.getViewMatrix();
  10126. viewMatrix.invertToRef(this._worldMatrix);
  10127. return this._worldMatrix;
  10128. };
  10129. Camera.prototype._getViewMatrix = function () {
  10130. return BABYLON.Matrix.Identity();
  10131. };
  10132. Camera.prototype.getViewMatrix = function (force) {
  10133. this._computedViewMatrix = this._computeViewMatrix(force);
  10134. if (!force && this._isSynchronizedViewMatrix()) {
  10135. return this._computedViewMatrix;
  10136. }
  10137. if (!this.parent || !this.parent.getWorldMatrix) {
  10138. this._globalPosition.copyFrom(this.position);
  10139. }
  10140. else {
  10141. if (!this._worldMatrix) {
  10142. this._worldMatrix = BABYLON.Matrix.Identity();
  10143. }
  10144. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10145. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10146. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10147. this._computedViewMatrix.invert();
  10148. this._markSyncedWithParent();
  10149. }
  10150. this._currentRenderId = this.getScene().getRenderId();
  10151. return this._computedViewMatrix;
  10152. };
  10153. Camera.prototype._computeViewMatrix = function (force) {
  10154. if (!force && this._isSynchronizedViewMatrix()) {
  10155. return this._computedViewMatrix;
  10156. }
  10157. this._computedViewMatrix = this._getViewMatrix();
  10158. this._currentRenderId = this.getScene().getRenderId();
  10159. return this._computedViewMatrix;
  10160. };
  10161. Camera.prototype.getProjectionMatrix = function (force) {
  10162. if (!force && this._isSynchronizedProjectionMatrix()) {
  10163. return this._projectionMatrix;
  10164. }
  10165. var engine = this.getEngine();
  10166. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10167. if (this.minZ <= 0) {
  10168. this.minZ = 0.1;
  10169. }
  10170. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10171. return this._projectionMatrix;
  10172. }
  10173. var halfWidth = engine.getRenderWidth() / 2.0;
  10174. var halfHeight = engine.getRenderHeight() / 2.0;
  10175. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10176. return this._projectionMatrix;
  10177. };
  10178. Camera.prototype.dispose = function () {
  10179. // Animations
  10180. this.getScene().stopAnimation(this);
  10181. // Remove from scene
  10182. this.getScene().removeCamera(this);
  10183. while (this._rigCameras.length > 0) {
  10184. this._rigCameras.pop().dispose();
  10185. }
  10186. // Postprocesses
  10187. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10188. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10189. }
  10190. };
  10191. // ---- Camera rigs section ----
  10192. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10193. while (this._rigCameras.length > 0) {
  10194. this._rigCameras.pop().dispose();
  10195. }
  10196. this.cameraRigMode = mode;
  10197. this._cameraRigParams = {};
  10198. switch (this.cameraRigMode) {
  10199. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10200. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10201. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10202. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10203. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10204. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10205. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10206. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10207. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10208. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10209. break;
  10210. }
  10211. var postProcesses = new Array();
  10212. switch (this.cameraRigMode) {
  10213. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10214. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10215. this._rigCameras[0].isIntermediate = true;
  10216. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10217. postProcesses[1].onApply = function (effect) {
  10218. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10219. };
  10220. break;
  10221. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10222. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10223. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10224. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10225. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10226. var secondCamIndex = 1 - firstCamIndex;
  10227. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10228. this._rigCameras[firstCamIndex].isIntermediate = true;
  10229. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10230. break;
  10231. case Camera.RIG_MODE_VR:
  10232. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10233. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10234. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10235. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10236. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10237. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10238. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10239. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10240. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10241. if (metrics.compensateDistortion) {
  10242. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10243. }
  10244. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10245. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10246. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10247. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10248. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10249. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10250. if (metrics.compensateDistortion) {
  10251. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10252. }
  10253. break;
  10254. }
  10255. this._update();
  10256. };
  10257. Camera.prototype._getVRProjectionMatrix = function () {
  10258. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10259. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10260. return this._projectionMatrix;
  10261. };
  10262. Camera.prototype.setCameraRigParameter = function (name, value) {
  10263. this._cameraRigParams[name] = value;
  10264. //provisionnally:
  10265. if (name === "interaxialDistance") {
  10266. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10267. }
  10268. };
  10269. /**
  10270. * May needs to be overridden by children so sub has required properties to be copied
  10271. */
  10272. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10273. return null;
  10274. };
  10275. /**
  10276. * May needs to be overridden by children
  10277. */
  10278. Camera.prototype._updateRigCameras = function () {
  10279. for (var i = 0; i < this._rigCameras.length; i++) {
  10280. this._rigCameras[i].minZ = this.minZ;
  10281. this._rigCameras[i].maxZ = this.maxZ;
  10282. this._rigCameras[i].fov = this.fov;
  10283. }
  10284. // only update viewport when ANAGLYPH
  10285. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10286. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10287. }
  10288. };
  10289. Camera.prototype.serialize = function () {
  10290. var serializationObject = {};
  10291. serializationObject.name = this.name;
  10292. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10293. serializationObject.id = this.id;
  10294. serializationObject.position = this.position.asArray();
  10295. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10296. // Parent
  10297. if (this.parent) {
  10298. serializationObject.parentId = this.parent.id;
  10299. }
  10300. serializationObject.fov = this.fov;
  10301. serializationObject.minZ = this.minZ;
  10302. serializationObject.maxZ = this.maxZ;
  10303. serializationObject.inertia = this.inertia;
  10304. // Animations
  10305. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10306. // Layer mask
  10307. serializationObject.layerMask = this.layerMask;
  10308. return serializationObject;
  10309. };
  10310. Camera.ParseCamera = function (parsedCamera, scene) {
  10311. var camera;
  10312. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10313. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10314. var interaxial_distance;
  10315. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10316. var alpha = parsedCamera.alpha;
  10317. var beta = parsedCamera.beta;
  10318. var radius = parsedCamera.radius;
  10319. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10320. interaxial_distance = parsedCamera.interaxial_distance;
  10321. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10322. }
  10323. else {
  10324. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10325. }
  10326. }
  10327. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10328. interaxial_distance = parsedCamera.interaxial_distance;
  10329. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10330. }
  10331. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10332. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10333. }
  10334. else if (parsedCamera.type === "FollowCamera") {
  10335. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10336. camera.heightOffset = parsedCamera.heightOffset;
  10337. camera.radius = parsedCamera.radius;
  10338. camera.rotationOffset = parsedCamera.rotationOffset;
  10339. if (lockedTargetMesh)
  10340. camera.target = lockedTargetMesh;
  10341. }
  10342. else if (parsedCamera.type === "GamepadCamera") {
  10343. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10344. }
  10345. else if (parsedCamera.type === "TouchCamera") {
  10346. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10347. }
  10348. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10349. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10350. }
  10351. else if (parsedCamera.type === "WebVRFreeCamera") {
  10352. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10353. }
  10354. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10355. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10356. }
  10357. else {
  10358. // Free Camera is the default value
  10359. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10360. }
  10361. // apply 3d rig, when found
  10362. if (parsedCamera.cameraRigMode) {
  10363. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10364. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10365. }
  10366. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10367. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10368. camera.lockedTarget = lockedTargetMesh;
  10369. }
  10370. camera.id = parsedCamera.id;
  10371. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10372. // Parent
  10373. if (parsedCamera.parentId) {
  10374. camera._waitingParentId = parsedCamera.parentId;
  10375. }
  10376. // Target
  10377. if (parsedCamera.target) {
  10378. if (camera.setTarget) {
  10379. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10380. }
  10381. else {
  10382. //For ArcRotate
  10383. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10384. }
  10385. }
  10386. else {
  10387. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10388. }
  10389. camera.fov = parsedCamera.fov;
  10390. camera.minZ = parsedCamera.minZ;
  10391. camera.maxZ = parsedCamera.maxZ;
  10392. camera.speed = parsedCamera.speed;
  10393. camera.inertia = parsedCamera.inertia;
  10394. camera.checkCollisions = parsedCamera.checkCollisions;
  10395. camera.applyGravity = parsedCamera.applyGravity;
  10396. if (parsedCamera.ellipsoid) {
  10397. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10398. }
  10399. // Animations
  10400. if (parsedCamera.animations) {
  10401. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10402. var parsedAnimation = parsedCamera.animations[animationIndex];
  10403. camera.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  10404. }
  10405. }
  10406. if (parsedCamera.autoAnimate) {
  10407. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10408. }
  10409. // Layer Mask
  10410. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10411. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10412. }
  10413. else {
  10414. camera.layerMask = 0x0FFFFFFF;
  10415. }
  10416. return camera;
  10417. };
  10418. // Statics
  10419. Camera._PERSPECTIVE_CAMERA = 0;
  10420. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10421. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10422. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10423. Camera._RIG_MODE_NONE = 0;
  10424. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10425. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10426. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10427. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10428. Camera._RIG_MODE_VR = 20;
  10429. return Camera;
  10430. })(BABYLON.Node);
  10431. BABYLON.Camera = Camera;
  10432. })(BABYLON || (BABYLON = {}));
  10433. var BABYLON;
  10434. (function (BABYLON) {
  10435. var TargetCamera = (function (_super) {
  10436. __extends(TargetCamera, _super);
  10437. function TargetCamera(name, position, scene) {
  10438. _super.call(this, name, position, scene);
  10439. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10440. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10441. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10442. this.speed = 2.0;
  10443. this.noRotationConstraint = false;
  10444. this.lockedTarget = null;
  10445. this._currentTarget = BABYLON.Vector3.Zero();
  10446. this._viewMatrix = BABYLON.Matrix.Zero();
  10447. this._camMatrix = BABYLON.Matrix.Zero();
  10448. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10449. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10450. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10451. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10452. this._lookAtTemp = BABYLON.Matrix.Zero();
  10453. this._tempMatrix = BABYLON.Matrix.Zero();
  10454. }
  10455. TargetCamera.prototype.getFrontPosition = function (distance) {
  10456. var direction = this.getTarget().subtract(this.position);
  10457. direction.normalize();
  10458. direction.scaleInPlace(distance);
  10459. return this.globalPosition.add(direction);
  10460. };
  10461. TargetCamera.prototype._getLockedTargetPosition = function () {
  10462. if (!this.lockedTarget) {
  10463. return null;
  10464. }
  10465. return this.lockedTarget.position || this.lockedTarget;
  10466. };
  10467. // Cache
  10468. TargetCamera.prototype._initCache = function () {
  10469. _super.prototype._initCache.call(this);
  10470. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10471. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10472. };
  10473. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10474. if (!ignoreParentClass) {
  10475. _super.prototype._updateCache.call(this);
  10476. }
  10477. var lockedTargetPosition = this._getLockedTargetPosition();
  10478. if (!lockedTargetPosition) {
  10479. this._cache.lockedTarget = null;
  10480. }
  10481. else {
  10482. if (!this._cache.lockedTarget) {
  10483. this._cache.lockedTarget = lockedTargetPosition.clone();
  10484. }
  10485. else {
  10486. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10487. }
  10488. }
  10489. this._cache.rotation.copyFrom(this.rotation);
  10490. };
  10491. // Synchronized
  10492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10494. return false;
  10495. }
  10496. var lockedTargetPosition = this._getLockedTargetPosition();
  10497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10498. && this._cache.rotation.equals(this.rotation);
  10499. };
  10500. // Methods
  10501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10502. var engine = this.getEngine();
  10503. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10504. };
  10505. // Target
  10506. TargetCamera.prototype.setTarget = function (target) {
  10507. this.upVector.normalize();
  10508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10509. this._camMatrix.invert();
  10510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10511. var vDir = target.subtract(this.position);
  10512. if (vDir.x >= 0.0) {
  10513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10514. }
  10515. else {
  10516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10517. }
  10518. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10519. if (isNaN(this.rotation.x)) {
  10520. this.rotation.x = 0;
  10521. }
  10522. if (isNaN(this.rotation.y)) {
  10523. this.rotation.y = 0;
  10524. }
  10525. if (isNaN(this.rotation.z)) {
  10526. this.rotation.z = 0;
  10527. }
  10528. };
  10529. TargetCamera.prototype.getTarget = function () {
  10530. return this._currentTarget;
  10531. };
  10532. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10533. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10534. };
  10535. TargetCamera.prototype._updatePosition = function () {
  10536. this.position.addInPlace(this.cameraDirection);
  10537. };
  10538. TargetCamera.prototype._checkInputs = function () {
  10539. var needToMove = this._decideIfNeedsToMove();
  10540. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10541. // Move
  10542. if (needToMove) {
  10543. this._updatePosition();
  10544. }
  10545. // Rotate
  10546. if (needToRotate) {
  10547. this.rotation.x += this.cameraRotation.x;
  10548. this.rotation.y += this.cameraRotation.y;
  10549. if (!this.noRotationConstraint) {
  10550. var limit = (Math.PI / 2) * 0.95;
  10551. if (this.rotation.x > limit)
  10552. this.rotation.x = limit;
  10553. if (this.rotation.x < -limit)
  10554. this.rotation.x = -limit;
  10555. }
  10556. }
  10557. // Inertia
  10558. if (needToMove) {
  10559. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10560. this.cameraDirection.x = 0;
  10561. }
  10562. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10563. this.cameraDirection.y = 0;
  10564. }
  10565. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10566. this.cameraDirection.z = 0;
  10567. }
  10568. this.cameraDirection.scaleInPlace(this.inertia);
  10569. }
  10570. if (needToRotate) {
  10571. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10572. this.cameraRotation.x = 0;
  10573. }
  10574. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10575. this.cameraRotation.y = 0;
  10576. }
  10577. this.cameraRotation.scaleInPlace(this.inertia);
  10578. }
  10579. _super.prototype._checkInputs.call(this);
  10580. };
  10581. TargetCamera.prototype._getViewMatrix = function () {
  10582. if (!this.lockedTarget) {
  10583. // Compute
  10584. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10585. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10586. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10587. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10588. this._lookAtTemp.invert();
  10589. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10590. }
  10591. else {
  10592. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10593. }
  10594. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10595. // Computing target and final matrix
  10596. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10597. }
  10598. else {
  10599. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10600. }
  10601. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10602. return this._viewMatrix;
  10603. };
  10604. TargetCamera.prototype._getVRViewMatrix = function () {
  10605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10606. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10607. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10608. // Computing target and final matrix
  10609. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10610. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10611. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10612. return this._viewMatrix;
  10613. };
  10614. /**
  10615. * @override
  10616. * Override Camera.createRigCamera
  10617. */
  10618. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10619. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10620. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10621. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10622. rigCamera._cameraRigParams = {};
  10623. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10624. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10625. }
  10626. return rigCamera;
  10627. }
  10628. return null;
  10629. };
  10630. /**
  10631. * @override
  10632. * Override Camera._updateRigCameras
  10633. */
  10634. TargetCamera.prototype._updateRigCameras = function () {
  10635. switch (this.cameraRigMode) {
  10636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10640. case BABYLON.Camera.RIG_MODE_VR:
  10641. var camLeft = this._rigCameras[0];
  10642. var camRight = this._rigCameras[1];
  10643. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10644. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10645. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10646. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10647. camLeft.position.copyFrom(this.position);
  10648. camRight.position.copyFrom(this.position);
  10649. }
  10650. else {
  10651. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10652. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10653. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10654. camLeft.setTarget(this.getTarget());
  10655. camRight.setTarget(this.getTarget());
  10656. }
  10657. break;
  10658. }
  10659. _super.prototype._updateRigCameras.call(this);
  10660. };
  10661. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10662. if (!this._rigCamTransformMatrix) {
  10663. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10664. }
  10665. var target = this.getTarget();
  10666. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10667. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10668. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10669. };
  10670. TargetCamera.prototype.serialize = function () {
  10671. var serializationObject = _super.prototype.serialize.call(this);
  10672. serializationObject.speed = this.speed;
  10673. if (this.rotation) {
  10674. serializationObject.rotation = this.rotation.asArray();
  10675. }
  10676. if (this.lockedTarget && this.lockedTarget.id) {
  10677. serializationObject.lockedTargetId = this.lockedTarget.id;
  10678. }
  10679. return serializationObject;
  10680. };
  10681. return TargetCamera;
  10682. })(BABYLON.Camera);
  10683. BABYLON.TargetCamera = TargetCamera;
  10684. })(BABYLON || (BABYLON = {}));
  10685. var BABYLON;
  10686. (function (BABYLON) {
  10687. var FreeCamera = (function (_super) {
  10688. __extends(FreeCamera, _super);
  10689. function FreeCamera(name, position, scene) {
  10690. var _this = this;
  10691. _super.call(this, name, position, scene);
  10692. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10693. this.keysUp = [38];
  10694. this.keysDown = [40];
  10695. this.keysLeft = [37];
  10696. this.keysRight = [39];
  10697. this.checkCollisions = false;
  10698. this.applyGravity = false;
  10699. this.angularSensibility = 2000.0;
  10700. this._keys = [];
  10701. this._collider = new BABYLON.Collider();
  10702. this._needMoveForGravity = false;
  10703. this._oldPosition = BABYLON.Vector3.Zero();
  10704. this._diffPosition = BABYLON.Vector3.Zero();
  10705. this._newPosition = BABYLON.Vector3.Zero();
  10706. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10707. if (collidedMesh === void 0) { collidedMesh = null; }
  10708. //TODO move this to the collision coordinator!
  10709. if (_this.getScene().workerCollisions)
  10710. newPosition.multiplyInPlace(_this._collider.radius);
  10711. var updatePosition = function (newPos) {
  10712. _this._newPosition.copyFrom(newPos);
  10713. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10714. var oldPosition = _this.position.clone();
  10715. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10716. _this.position.addInPlace(_this._diffPosition);
  10717. if (_this.onCollide && collidedMesh) {
  10718. _this.onCollide(collidedMesh);
  10719. }
  10720. }
  10721. };
  10722. updatePosition(newPosition);
  10723. };
  10724. }
  10725. // Controls
  10726. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10727. var _this = this;
  10728. var previousPosition;
  10729. var engine = this.getEngine();
  10730. if (this._attachedElement) {
  10731. return;
  10732. }
  10733. this._attachedElement = element;
  10734. if (this._onMouseDown === undefined) {
  10735. this._onMouseDown = function (evt) {
  10736. previousPosition = {
  10737. x: evt.clientX,
  10738. y: evt.clientY
  10739. };
  10740. if (!noPreventDefault) {
  10741. evt.preventDefault();
  10742. }
  10743. };
  10744. this._onMouseUp = function (evt) {
  10745. previousPosition = null;
  10746. if (!noPreventDefault) {
  10747. evt.preventDefault();
  10748. }
  10749. };
  10750. this._onMouseOut = function (evt) {
  10751. previousPosition = null;
  10752. _this._keys = [];
  10753. if (!noPreventDefault) {
  10754. evt.preventDefault();
  10755. }
  10756. };
  10757. this._onMouseMove = function (evt) {
  10758. if (!previousPosition && !engine.isPointerLock) {
  10759. return;
  10760. }
  10761. var offsetX;
  10762. var offsetY;
  10763. if (!engine.isPointerLock) {
  10764. offsetX = evt.clientX - previousPosition.x;
  10765. offsetY = evt.clientY - previousPosition.y;
  10766. }
  10767. else {
  10768. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10769. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10770. }
  10771. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10772. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10773. previousPosition = {
  10774. x: evt.clientX,
  10775. y: evt.clientY
  10776. };
  10777. if (!noPreventDefault) {
  10778. evt.preventDefault();
  10779. }
  10780. };
  10781. this._onKeyDown = function (evt) {
  10782. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10783. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10784. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10785. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10786. var index = _this._keys.indexOf(evt.keyCode);
  10787. if (index === -1) {
  10788. _this._keys.push(evt.keyCode);
  10789. }
  10790. if (!noPreventDefault) {
  10791. evt.preventDefault();
  10792. }
  10793. }
  10794. };
  10795. this._onKeyUp = function (evt) {
  10796. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10797. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10798. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10799. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10800. var index = _this._keys.indexOf(evt.keyCode);
  10801. if (index >= 0) {
  10802. _this._keys.splice(index, 1);
  10803. }
  10804. if (!noPreventDefault) {
  10805. evt.preventDefault();
  10806. }
  10807. }
  10808. };
  10809. this._onLostFocus = function () {
  10810. _this._keys = [];
  10811. };
  10812. this._reset = function () {
  10813. _this._keys = [];
  10814. previousPosition = null;
  10815. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10816. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10817. };
  10818. }
  10819. element.addEventListener("mousedown", this._onMouseDown, false);
  10820. element.addEventListener("mouseup", this._onMouseUp, false);
  10821. element.addEventListener("mouseout", this._onMouseOut, false);
  10822. element.addEventListener("mousemove", this._onMouseMove, false);
  10823. BABYLON.Tools.RegisterTopRootEvents([
  10824. { name: "keydown", handler: this._onKeyDown },
  10825. { name: "keyup", handler: this._onKeyUp },
  10826. { name: "blur", handler: this._onLostFocus }
  10827. ]);
  10828. };
  10829. FreeCamera.prototype.detachControl = function (element) {
  10830. if (this._attachedElement != element) {
  10831. return;
  10832. }
  10833. element.removeEventListener("mousedown", this._onMouseDown);
  10834. element.removeEventListener("mouseup", this._onMouseUp);
  10835. element.removeEventListener("mouseout", this._onMouseOut);
  10836. element.removeEventListener("mousemove", this._onMouseMove);
  10837. BABYLON.Tools.UnregisterTopRootEvents([
  10838. { name: "keydown", handler: this._onKeyDown },
  10839. { name: "keyup", handler: this._onKeyUp },
  10840. { name: "blur", handler: this._onLostFocus }
  10841. ]);
  10842. this._attachedElement = null;
  10843. if (this._reset) {
  10844. this._reset();
  10845. }
  10846. };
  10847. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10848. var globalPosition;
  10849. if (this.parent) {
  10850. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10851. }
  10852. else {
  10853. globalPosition = this.position;
  10854. }
  10855. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10856. this._collider.radius = this.ellipsoid;
  10857. //no need for clone, as long as gravity is not on.
  10858. var actualVelocity = velocity;
  10859. //add gravity to the velocity to prevent the dual-collision checking
  10860. if (this.applyGravity) {
  10861. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10862. actualVelocity = velocity.add(this.getScene().gravity);
  10863. }
  10864. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10865. };
  10866. FreeCamera.prototype._checkInputs = function () {
  10867. if (!this._localDirection) {
  10868. this._localDirection = BABYLON.Vector3.Zero();
  10869. this._transformedDirection = BABYLON.Vector3.Zero();
  10870. }
  10871. // Keyboard
  10872. for (var index = 0; index < this._keys.length; index++) {
  10873. var keyCode = this._keys[index];
  10874. var speed = this._computeLocalCameraSpeed();
  10875. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10876. this._localDirection.copyFromFloats(-speed, 0, 0);
  10877. }
  10878. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10879. this._localDirection.copyFromFloats(0, 0, speed);
  10880. }
  10881. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10882. this._localDirection.copyFromFloats(speed, 0, 0);
  10883. }
  10884. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10885. this._localDirection.copyFromFloats(0, 0, -speed);
  10886. }
  10887. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10888. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10889. this.cameraDirection.addInPlace(this._transformedDirection);
  10890. }
  10891. _super.prototype._checkInputs.call(this);
  10892. };
  10893. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10894. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10895. };
  10896. FreeCamera.prototype._updatePosition = function () {
  10897. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10898. this._collideWithWorld(this.cameraDirection);
  10899. }
  10900. else {
  10901. this.position.addInPlace(this.cameraDirection);
  10902. }
  10903. };
  10904. FreeCamera.prototype.serialize = function () {
  10905. var serializationObject = _super.prototype.serialize.call(this);
  10906. serializationObject.checkCollisions = this.checkCollisions;
  10907. serializationObject.applyGravity = this.applyGravity;
  10908. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10909. return serializationObject;
  10910. };
  10911. return FreeCamera;
  10912. })(BABYLON.TargetCamera);
  10913. BABYLON.FreeCamera = FreeCamera;
  10914. })(BABYLON || (BABYLON = {}));
  10915. var BABYLON;
  10916. (function (BABYLON) {
  10917. var FollowCamera = (function (_super) {
  10918. __extends(FollowCamera, _super);
  10919. function FollowCamera(name, position, scene) {
  10920. _super.call(this, name, position, scene);
  10921. this.radius = 12;
  10922. this.rotationOffset = 0;
  10923. this.heightOffset = 4;
  10924. this.cameraAcceleration = 0.05;
  10925. this.maxCameraSpeed = 20;
  10926. }
  10927. FollowCamera.prototype.getRadians = function (degrees) {
  10928. return degrees * Math.PI / 180;
  10929. };
  10930. FollowCamera.prototype.follow = function (cameraTarget) {
  10931. if (!cameraTarget)
  10932. return;
  10933. var yRotation;
  10934. if (cameraTarget.rotationQuaternion) {
  10935. var rotMatrix = new BABYLON.Matrix();
  10936. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10937. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10938. }
  10939. else {
  10940. yRotation = cameraTarget.rotation.y;
  10941. }
  10942. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10943. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10944. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10945. var dx = targetX - this.position.x;
  10946. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10947. var dz = (targetZ) - this.position.z;
  10948. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10949. var vy = dy * this.cameraAcceleration;
  10950. var vz = dz * this.cameraAcceleration * 2;
  10951. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10952. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10953. }
  10954. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10955. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10956. }
  10957. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10958. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10959. }
  10960. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10961. this.setTarget(cameraTarget.position);
  10962. };
  10963. FollowCamera.prototype._checkInputs = function () {
  10964. _super.prototype._checkInputs.call(this);
  10965. this.follow(this.target);
  10966. };
  10967. FollowCamera.prototype.serialize = function () {
  10968. var serializationObject = _super.prototype.serialize.call(this);
  10969. serializationObject.radius = this.radius;
  10970. serializationObject.heightOffset = this.heightOffset;
  10971. serializationObject.rotationOffset = this.rotationOffset;
  10972. return serializationObject;
  10973. };
  10974. return FollowCamera;
  10975. })(BABYLON.TargetCamera);
  10976. BABYLON.FollowCamera = FollowCamera;
  10977. var ArcFollowCamera = (function (_super) {
  10978. __extends(ArcFollowCamera, _super);
  10979. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10980. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10981. this.alpha = alpha;
  10982. this.beta = beta;
  10983. this.radius = radius;
  10984. this.target = target;
  10985. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10986. this.follow();
  10987. }
  10988. ArcFollowCamera.prototype.follow = function () {
  10989. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10990. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10991. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10992. this.position = this.target.position.add(this._cartesianCoordinates);
  10993. this.setTarget(this.target.position);
  10994. };
  10995. ArcFollowCamera.prototype._checkInputs = function () {
  10996. _super.prototype._checkInputs.call(this);
  10997. this.follow();
  10998. };
  10999. ArcFollowCamera.prototype.serialize = function () {
  11000. var serializationObject = _super.prototype.serialize.call(this);
  11001. serializationObject.radius = this.radius;
  11002. return serializationObject;
  11003. };
  11004. return ArcFollowCamera;
  11005. })(BABYLON.TargetCamera);
  11006. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11007. })(BABYLON || (BABYLON = {}));
  11008. var BABYLON;
  11009. (function (BABYLON) {
  11010. // We're mainly based on the logic defined into the FreeCamera code
  11011. var TouchCamera = (function (_super) {
  11012. __extends(TouchCamera, _super);
  11013. function TouchCamera(name, position, scene) {
  11014. _super.call(this, name, position, scene);
  11015. this._offsetX = null;
  11016. this._offsetY = null;
  11017. this._pointerCount = 0;
  11018. this._pointerPressed = [];
  11019. this.angularSensibility = 200000.0;
  11020. this.moveSensibility = 500.0;
  11021. }
  11022. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11023. var _this = this;
  11024. var previousPosition;
  11025. if (this._attachedCanvas) {
  11026. return;
  11027. }
  11028. this._attachedCanvas = canvas;
  11029. if (this._onPointerDown === undefined) {
  11030. this._onPointerDown = function (evt) {
  11031. if (!noPreventDefault) {
  11032. evt.preventDefault();
  11033. }
  11034. _this._pointerPressed.push(evt.pointerId);
  11035. if (_this._pointerPressed.length !== 1) {
  11036. return;
  11037. }
  11038. previousPosition = {
  11039. x: evt.clientX,
  11040. y: evt.clientY
  11041. };
  11042. };
  11043. this._onPointerUp = function (evt) {
  11044. if (!noPreventDefault) {
  11045. evt.preventDefault();
  11046. }
  11047. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11048. if (index === -1) {
  11049. return;
  11050. }
  11051. _this._pointerPressed.splice(index, 1);
  11052. if (index != 0) {
  11053. return;
  11054. }
  11055. previousPosition = null;
  11056. _this._offsetX = null;
  11057. _this._offsetY = null;
  11058. };
  11059. this._onPointerMove = function (evt) {
  11060. if (!noPreventDefault) {
  11061. evt.preventDefault();
  11062. }
  11063. if (!previousPosition) {
  11064. return;
  11065. }
  11066. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11067. if (index != 0) {
  11068. return;
  11069. }
  11070. _this._offsetX = evt.clientX - previousPosition.x;
  11071. _this._offsetY = -(evt.clientY - previousPosition.y);
  11072. };
  11073. this._onLostFocus = function () {
  11074. _this._offsetX = null;
  11075. _this._offsetY = null;
  11076. };
  11077. }
  11078. canvas.addEventListener("pointerdown", this._onPointerDown);
  11079. canvas.addEventListener("pointerup", this._onPointerUp);
  11080. canvas.addEventListener("pointerout", this._onPointerUp);
  11081. canvas.addEventListener("pointermove", this._onPointerMove);
  11082. BABYLON.Tools.RegisterTopRootEvents([
  11083. { name: "blur", handler: this._onLostFocus }
  11084. ]);
  11085. };
  11086. TouchCamera.prototype.detachControl = function (canvas) {
  11087. if (this._attachedCanvas != canvas) {
  11088. return;
  11089. }
  11090. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11091. canvas.removeEventListener("pointerup", this._onPointerUp);
  11092. canvas.removeEventListener("pointerout", this._onPointerUp);
  11093. canvas.removeEventListener("pointermove", this._onPointerMove);
  11094. BABYLON.Tools.UnregisterTopRootEvents([
  11095. { name: "blur", handler: this._onLostFocus }
  11096. ]);
  11097. this._attachedCanvas = null;
  11098. };
  11099. TouchCamera.prototype._checkInputs = function () {
  11100. if (this._offsetX) {
  11101. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11102. if (this._pointerPressed.length > 1) {
  11103. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11104. }
  11105. else {
  11106. var speed = this._computeLocalCameraSpeed();
  11107. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11108. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11109. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11110. }
  11111. }
  11112. _super.prototype._checkInputs.call(this);
  11113. };
  11114. return TouchCamera;
  11115. })(BABYLON.FreeCamera);
  11116. BABYLON.TouchCamera = TouchCamera;
  11117. })(BABYLON || (BABYLON = {}));
  11118. var BABYLON;
  11119. (function (BABYLON) {
  11120. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11121. var ArcRotateCamera = (function (_super) {
  11122. __extends(ArcRotateCamera, _super);
  11123. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11124. var _this = this;
  11125. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11126. this.alpha = alpha;
  11127. this.beta = beta;
  11128. this.radius = radius;
  11129. this.target = target;
  11130. this.inertialAlphaOffset = 0;
  11131. this.inertialBetaOffset = 0;
  11132. this.inertialRadiusOffset = 0;
  11133. this.lowerAlphaLimit = null;
  11134. this.upperAlphaLimit = null;
  11135. this.lowerBetaLimit = 0.01;
  11136. this.upperBetaLimit = Math.PI;
  11137. this.lowerRadiusLimit = null;
  11138. this.upperRadiusLimit = null;
  11139. this.angularSensibilityX = 1000.0;
  11140. this.angularSensibilityY = 1000.0;
  11141. this.wheelPrecision = 3.0;
  11142. this.pinchPrecision = 2.0;
  11143. this.panningSensibility = 50.0;
  11144. this.inertialPanningX = 0;
  11145. this.inertialPanningY = 0;
  11146. this.keysUp = [38];
  11147. this.keysDown = [40];
  11148. this.keysLeft = [37];
  11149. this.keysRight = [39];
  11150. this.zoomOnFactor = 1;
  11151. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11152. this.pinchInwards = true;
  11153. this.allowUpsideDown = true;
  11154. this._keys = [];
  11155. this._viewMatrix = new BABYLON.Matrix();
  11156. this._isRightClick = false;
  11157. this._isCtrlPushed = false;
  11158. this.checkCollisions = false;
  11159. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11160. this._collider = new BABYLON.Collider();
  11161. this._previousPosition = BABYLON.Vector3.Zero();
  11162. this._collisionVelocity = BABYLON.Vector3.Zero();
  11163. this._newPosition = BABYLON.Vector3.Zero();
  11164. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11165. if (collidedMesh === void 0) { collidedMesh = null; }
  11166. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11167. newPosition.multiplyInPlace(_this._collider.radius);
  11168. }
  11169. if (!collidedMesh) {
  11170. _this._previousPosition.copyFrom(_this.position);
  11171. }
  11172. else {
  11173. _this.setPosition(_this.position);
  11174. if (_this.onCollide) {
  11175. _this.onCollide(collidedMesh);
  11176. }
  11177. }
  11178. // Recompute because of constraints
  11179. var cosa = Math.cos(_this.alpha);
  11180. var sina = Math.sin(_this.alpha);
  11181. var cosb = Math.cos(_this.beta);
  11182. var sinb = Math.sin(_this.beta);
  11183. var target = _this._getTargetPosition();
  11184. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11185. _this.position.copyFrom(_this._newPosition);
  11186. var up = _this.upVector;
  11187. if (_this.allowUpsideDown && _this.beta < 0) {
  11188. up = up.clone();
  11189. up = up.negate();
  11190. }
  11191. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11192. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11193. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11194. _this._collisionTriggered = false;
  11195. };
  11196. if (!this.target) {
  11197. this.target = BABYLON.Vector3.Zero();
  11198. }
  11199. this.getViewMatrix();
  11200. }
  11201. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11202. //deprecated angularSensibility support
  11203. get: function () {
  11204. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11205. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11206. },
  11207. //deprecated angularSensibility support
  11208. set: function (value) {
  11209. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11210. this.angularSensibilityX = value;
  11211. this.angularSensibilityY = value;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. ArcRotateCamera.prototype._getTargetPosition = function () {
  11217. return this.target.position || this.target;
  11218. };
  11219. // Cache
  11220. ArcRotateCamera.prototype._initCache = function () {
  11221. _super.prototype._initCache.call(this);
  11222. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11223. this._cache.alpha = undefined;
  11224. this._cache.beta = undefined;
  11225. this._cache.radius = undefined;
  11226. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11227. };
  11228. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11229. if (!ignoreParentClass) {
  11230. _super.prototype._updateCache.call(this);
  11231. }
  11232. this._cache.target.copyFrom(this._getTargetPosition());
  11233. this._cache.alpha = this.alpha;
  11234. this._cache.beta = this.beta;
  11235. this._cache.radius = this.radius;
  11236. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11237. };
  11238. // Synchronized
  11239. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11240. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11241. return false;
  11242. return this._cache.target.equals(this._getTargetPosition())
  11243. && this._cache.alpha === this.alpha
  11244. && this._cache.beta === this.beta
  11245. && this._cache.radius === this.radius
  11246. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11247. };
  11248. // Methods
  11249. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11250. var _this = this;
  11251. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11252. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11253. var previousPinchDistance = 0;
  11254. var pointers = new BABYLON.SmartCollection();
  11255. if (this._attachedElement) {
  11256. return;
  11257. }
  11258. this._attachedElement = element;
  11259. var engine = this.getEngine();
  11260. if (this._onPointerDown === undefined) {
  11261. this._onPointerDown = function (evt) {
  11262. // Manage panning with right click
  11263. _this._isRightClick = evt.button === 2;
  11264. // manage pointers
  11265. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11266. cacheSoloPointer = pointers.item(evt.pointerId);
  11267. if (!noPreventDefault) {
  11268. evt.preventDefault();
  11269. }
  11270. };
  11271. this._onPointerUp = function (evt) {
  11272. cacheSoloPointer = null;
  11273. previousPinchDistance = 0;
  11274. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11275. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11276. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11277. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11278. pointers.empty();
  11279. if (!noPreventDefault) {
  11280. evt.preventDefault();
  11281. }
  11282. };
  11283. this._onContextMenu = function (evt) {
  11284. evt.preventDefault();
  11285. };
  11286. this._onPointerMove = function (evt) {
  11287. if (!noPreventDefault) {
  11288. evt.preventDefault();
  11289. }
  11290. switch (pointers.count) {
  11291. case 1:
  11292. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11293. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11294. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11295. }
  11296. else {
  11297. var offsetX = evt.clientX - cacheSoloPointer.x;
  11298. var offsetY = evt.clientY - cacheSoloPointer.y;
  11299. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11300. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11301. }
  11302. cacheSoloPointer.x = evt.clientX;
  11303. cacheSoloPointer.y = evt.clientY;
  11304. break;
  11305. case 2:
  11306. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11307. pointers.item(evt.pointerId).x = evt.clientX;
  11308. pointers.item(evt.pointerId).y = evt.clientY;
  11309. var direction = _this.pinchInwards ? 1 : -1;
  11310. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11311. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11312. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11313. if (previousPinchDistance === 0) {
  11314. previousPinchDistance = pinchSquaredDistance;
  11315. return;
  11316. }
  11317. if (pinchSquaredDistance !== previousPinchDistance) {
  11318. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11319. previousPinchDistance = pinchSquaredDistance;
  11320. }
  11321. break;
  11322. default:
  11323. if (pointers.item(evt.pointerId)) {
  11324. pointers.item(evt.pointerId).x = evt.clientX;
  11325. pointers.item(evt.pointerId).y = evt.clientY;
  11326. }
  11327. }
  11328. };
  11329. this._onMouseMove = function (evt) {
  11330. if (!engine.isPointerLock) {
  11331. return;
  11332. }
  11333. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11334. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11335. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11336. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11337. if (!noPreventDefault) {
  11338. evt.preventDefault();
  11339. }
  11340. };
  11341. this._wheel = function (event) {
  11342. var delta = 0;
  11343. if (event.wheelDelta) {
  11344. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11345. }
  11346. else if (event.detail) {
  11347. delta = -event.detail / _this.wheelPrecision;
  11348. }
  11349. if (delta)
  11350. _this.inertialRadiusOffset += delta;
  11351. if (event.preventDefault) {
  11352. if (!noPreventDefault) {
  11353. event.preventDefault();
  11354. }
  11355. }
  11356. };
  11357. this._onKeyDown = function (evt) {
  11358. _this._isCtrlPushed = evt.ctrlKey;
  11359. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11360. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11361. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11362. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11363. var index = _this._keys.indexOf(evt.keyCode);
  11364. if (index === -1) {
  11365. _this._keys.push(evt.keyCode);
  11366. }
  11367. if (evt.preventDefault) {
  11368. if (!noPreventDefault) {
  11369. evt.preventDefault();
  11370. }
  11371. }
  11372. }
  11373. };
  11374. this._onKeyUp = function (evt) {
  11375. _this._isCtrlPushed = evt.ctrlKey;
  11376. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11377. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11378. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11379. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11380. var index = _this._keys.indexOf(evt.keyCode);
  11381. if (index >= 0) {
  11382. _this._keys.splice(index, 1);
  11383. }
  11384. if (evt.preventDefault) {
  11385. if (!noPreventDefault) {
  11386. evt.preventDefault();
  11387. }
  11388. }
  11389. }
  11390. };
  11391. this._onLostFocus = function () {
  11392. _this._keys = [];
  11393. pointers.empty();
  11394. previousPinchDistance = 0;
  11395. cacheSoloPointer = null;
  11396. };
  11397. this._onGestureStart = function (e) {
  11398. if (window.MSGesture === undefined) {
  11399. return;
  11400. }
  11401. if (!_this._MSGestureHandler) {
  11402. _this._MSGestureHandler = new MSGesture();
  11403. _this._MSGestureHandler.target = element;
  11404. }
  11405. _this._MSGestureHandler.addPointer(e.pointerId);
  11406. };
  11407. this._onGesture = function (e) {
  11408. _this.radius *= e.scale;
  11409. if (e.preventDefault) {
  11410. if (!noPreventDefault) {
  11411. e.stopPropagation();
  11412. e.preventDefault();
  11413. }
  11414. }
  11415. };
  11416. this._reset = function () {
  11417. _this._keys = [];
  11418. _this.inertialAlphaOffset = 0;
  11419. _this.inertialBetaOffset = 0;
  11420. _this.inertialRadiusOffset = 0;
  11421. pointers.empty();
  11422. previousPinchDistance = 0;
  11423. cacheSoloPointer = null;
  11424. };
  11425. }
  11426. if (!useCtrlForPanning) {
  11427. element.addEventListener("contextmenu", this._onContextMenu, false);
  11428. }
  11429. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11430. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11431. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11432. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11433. element.addEventListener("mousemove", this._onMouseMove, false);
  11434. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11435. element.addEventListener("MSGestureChange", this._onGesture, false);
  11436. element.addEventListener('mousewheel', this._wheel, false);
  11437. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11438. BABYLON.Tools.RegisterTopRootEvents([
  11439. { name: "keydown", handler: this._onKeyDown },
  11440. { name: "keyup", handler: this._onKeyUp },
  11441. { name: "blur", handler: this._onLostFocus }
  11442. ]);
  11443. };
  11444. ArcRotateCamera.prototype.detachControl = function (element) {
  11445. if (this._attachedElement !== element) {
  11446. return;
  11447. }
  11448. element.removeEventListener("contextmenu", this._onContextMenu);
  11449. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11450. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11451. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11452. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11453. element.removeEventListener("mousemove", this._onMouseMove);
  11454. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11455. element.removeEventListener("MSGestureChange", this._onGesture);
  11456. element.removeEventListener('mousewheel', this._wheel);
  11457. element.removeEventListener('DOMMouseScroll', this._wheel);
  11458. BABYLON.Tools.UnregisterTopRootEvents([
  11459. { name: "keydown", handler: this._onKeyDown },
  11460. { name: "keyup", handler: this._onKeyUp },
  11461. { name: "blur", handler: this._onLostFocus }
  11462. ]);
  11463. this._MSGestureHandler = null;
  11464. this._attachedElement = null;
  11465. if (this._reset) {
  11466. this._reset();
  11467. }
  11468. };
  11469. ArcRotateCamera.prototype._checkInputs = function () {
  11470. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11471. if (this._collisionTriggered) {
  11472. return;
  11473. }
  11474. // Keyboard
  11475. for (var index = 0; index < this._keys.length; index++) {
  11476. var keyCode = this._keys[index];
  11477. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11478. this.inertialAlphaOffset -= 0.01;
  11479. }
  11480. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11481. this.inertialBetaOffset -= 0.01;
  11482. }
  11483. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11484. this.inertialAlphaOffset += 0.01;
  11485. }
  11486. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11487. this.inertialBetaOffset += 0.01;
  11488. }
  11489. }
  11490. // Inertia
  11491. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11492. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11493. this.beta += this.inertialBetaOffset;
  11494. this.radius -= this.inertialRadiusOffset;
  11495. this.inertialAlphaOffset *= this.inertia;
  11496. this.inertialBetaOffset *= this.inertia;
  11497. this.inertialRadiusOffset *= this.inertia;
  11498. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11499. this.inertialAlphaOffset = 0;
  11500. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11501. this.inertialBetaOffset = 0;
  11502. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11503. this.inertialRadiusOffset = 0;
  11504. }
  11505. // Panning inertia
  11506. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11507. if (!this._localDirection) {
  11508. this._localDirection = BABYLON.Vector3.Zero();
  11509. this._transformedDirection = BABYLON.Vector3.Zero();
  11510. }
  11511. this.inertialPanningX *= this.inertia;
  11512. this.inertialPanningY *= this.inertia;
  11513. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11514. this.inertialPanningX = 0;
  11515. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11516. this.inertialPanningY = 0;
  11517. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11518. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11519. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11520. this.target.addInPlace(this._transformedDirection);
  11521. }
  11522. // Limits
  11523. this._checkLimits();
  11524. _super.prototype._checkInputs.call(this);
  11525. };
  11526. ArcRotateCamera.prototype._checkLimits = function () {
  11527. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11528. if (this.allowUpsideDown && this.beta > Math.PI) {
  11529. this.beta = this.beta - (2 * Math.PI);
  11530. }
  11531. }
  11532. else {
  11533. if (this.beta < this.lowerBetaLimit) {
  11534. this.beta = this.lowerBetaLimit;
  11535. }
  11536. }
  11537. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11538. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11539. this.beta = this.beta + (2 * Math.PI);
  11540. }
  11541. }
  11542. else {
  11543. if (this.beta > this.upperBetaLimit) {
  11544. this.beta = this.upperBetaLimit;
  11545. }
  11546. }
  11547. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11548. this.alpha = this.lowerAlphaLimit;
  11549. }
  11550. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11551. this.alpha = this.upperAlphaLimit;
  11552. }
  11553. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11554. this.radius = this.lowerRadiusLimit;
  11555. }
  11556. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11557. this.radius = this.upperRadiusLimit;
  11558. }
  11559. };
  11560. ArcRotateCamera.prototype.setPosition = function (position) {
  11561. if (this.position.equals(position)) {
  11562. return;
  11563. }
  11564. var radiusv3 = position.subtract(this._getTargetPosition());
  11565. this.radius = radiusv3.length();
  11566. // Alpha
  11567. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11568. if (radiusv3.z < 0) {
  11569. this.alpha = 2 * Math.PI - this.alpha;
  11570. }
  11571. // Beta
  11572. this.beta = Math.acos(radiusv3.y / this.radius);
  11573. this._checkLimits();
  11574. };
  11575. ArcRotateCamera.prototype.setTarget = function (target) {
  11576. this.target = target;
  11577. };
  11578. ArcRotateCamera.prototype._getViewMatrix = function () {
  11579. // Compute
  11580. var cosa = Math.cos(this.alpha);
  11581. var sina = Math.sin(this.alpha);
  11582. var cosb = Math.cos(this.beta);
  11583. var sinb = Math.sin(this.beta);
  11584. var target = this._getTargetPosition();
  11585. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11586. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11587. this._collider.radius = this.collisionRadius;
  11588. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11589. this._collisionTriggered = true;
  11590. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11591. }
  11592. else {
  11593. this.position.copyFrom(this._newPosition);
  11594. var up = this.upVector;
  11595. if (this.allowUpsideDown && this.beta < 0) {
  11596. up = up.clone();
  11597. up = up.negate();
  11598. }
  11599. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11600. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11601. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11602. }
  11603. return this._viewMatrix;
  11604. };
  11605. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11606. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11607. meshes = meshes || this.getScene().meshes;
  11608. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11609. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11610. this.radius = distance * this.zoomOnFactor;
  11611. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11612. };
  11613. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11614. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11615. var meshesOrMinMaxVector;
  11616. var distance;
  11617. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11618. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11619. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11620. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11621. }
  11622. else {
  11623. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11624. distance = meshesOrMinMaxVectorAndDistance.distance;
  11625. }
  11626. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11627. if (!doNotUpdateMaxZ) {
  11628. this.maxZ = distance * 2;
  11629. }
  11630. };
  11631. /**
  11632. * @override
  11633. * Override Camera.createRigCamera
  11634. */
  11635. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11636. switch (this.cameraRigMode) {
  11637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11640. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11641. case BABYLON.Camera.RIG_MODE_VR:
  11642. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11643. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11644. }
  11645. return null;
  11646. };
  11647. /**
  11648. * @override
  11649. * Override Camera._updateRigCameras
  11650. */
  11651. ArcRotateCamera.prototype._updateRigCameras = function () {
  11652. switch (this.cameraRigMode) {
  11653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11657. case BABYLON.Camera.RIG_MODE_VR:
  11658. var camLeft = this._rigCameras[0];
  11659. var camRight = this._rigCameras[1];
  11660. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11661. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11662. camLeft.beta = camRight.beta = this.beta;
  11663. camLeft.radius = camRight.radius = this.radius;
  11664. break;
  11665. }
  11666. _super.prototype._updateRigCameras.call(this);
  11667. };
  11668. ArcRotateCamera.prototype.serialize = function () {
  11669. var serializationObject = _super.prototype.serialize.call(this);
  11670. if (this.target instanceof BABYLON.Vector3) {
  11671. serializationObject.target = this.target.asArray();
  11672. }
  11673. if (this.target && this.target.id) {
  11674. serializationObject.lockedTargetId = this.target.id;
  11675. }
  11676. serializationObject.checkCollisions = this.checkCollisions;
  11677. serializationObject.alpha = this.alpha;
  11678. serializationObject.beta = this.beta;
  11679. serializationObject.radius = this.radius;
  11680. return serializationObject;
  11681. };
  11682. return ArcRotateCamera;
  11683. })(BABYLON.TargetCamera);
  11684. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11685. })(BABYLON || (BABYLON = {}));
  11686. var BABYLON;
  11687. (function (BABYLON) {
  11688. var RenderingManager = (function () {
  11689. function RenderingManager(scene) {
  11690. this._renderingGroups = new Array();
  11691. this._scene = scene;
  11692. }
  11693. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11694. if (this._scene._activeParticleSystems.length === 0) {
  11695. return;
  11696. }
  11697. // Particles
  11698. var activeCamera = this._scene.activeCamera;
  11699. var beforeParticlesDate = BABYLON.Tools.Now;
  11700. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11701. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11702. if (particleSystem.renderingGroupId !== index) {
  11703. continue;
  11704. }
  11705. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11706. continue;
  11707. }
  11708. this._clearDepthBuffer();
  11709. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11710. this._scene._activeParticles += particleSystem.render();
  11711. }
  11712. }
  11713. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11714. };
  11715. RenderingManager.prototype._renderSprites = function (index) {
  11716. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11717. return;
  11718. }
  11719. // Sprites
  11720. var activeCamera = this._scene.activeCamera;
  11721. var beforeSpritessDate = BABYLON.Tools.Now;
  11722. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11723. var spriteManager = this._scene.spriteManagers[id];
  11724. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11725. this._clearDepthBuffer();
  11726. spriteManager.render();
  11727. }
  11728. }
  11729. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11730. };
  11731. RenderingManager.prototype._clearDepthBuffer = function () {
  11732. if (this._depthBufferAlreadyCleaned) {
  11733. return;
  11734. }
  11735. this._scene.getEngine().clear(0, false, true);
  11736. this._depthBufferAlreadyCleaned = true;
  11737. };
  11738. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11739. if (this._currentRenderSprites) {
  11740. this._renderSprites(this._currentIndex);
  11741. }
  11742. if (this._currentRenderParticles) {
  11743. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11744. }
  11745. };
  11746. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11747. this._currentActiveMeshes = activeMeshes;
  11748. this._currentRenderParticles = renderParticles;
  11749. this._currentRenderSprites = renderSprites;
  11750. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11751. this._depthBufferAlreadyCleaned = false;
  11752. var renderingGroup = this._renderingGroups[index];
  11753. var needToStepBack = false;
  11754. this._currentIndex = index;
  11755. if (renderingGroup) {
  11756. this._clearDepthBuffer();
  11757. if (!renderingGroup.onBeforeTransparentRendering) {
  11758. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11759. }
  11760. if (!renderingGroup.render(customRenderFunction)) {
  11761. this._renderingGroups.splice(index, 1);
  11762. needToStepBack = true;
  11763. this._renderSpritesAndParticles();
  11764. }
  11765. }
  11766. else {
  11767. this._renderSpritesAndParticles();
  11768. }
  11769. if (needToStepBack) {
  11770. index--;
  11771. }
  11772. }
  11773. };
  11774. RenderingManager.prototype.reset = function () {
  11775. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11776. if (renderingGroup) {
  11777. renderingGroup.prepare();
  11778. }
  11779. });
  11780. };
  11781. RenderingManager.prototype.dispatch = function (subMesh) {
  11782. var mesh = subMesh.getMesh();
  11783. var renderingGroupId = mesh.renderingGroupId || 0;
  11784. if (!this._renderingGroups[renderingGroupId]) {
  11785. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11786. }
  11787. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11788. };
  11789. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11790. return RenderingManager;
  11791. })();
  11792. BABYLON.RenderingManager = RenderingManager;
  11793. })(BABYLON || (BABYLON = {}));
  11794. var BABYLON;
  11795. (function (BABYLON) {
  11796. var RenderingGroup = (function () {
  11797. function RenderingGroup(index, scene) {
  11798. this.index = index;
  11799. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11800. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11801. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11802. this._scene = scene;
  11803. }
  11804. RenderingGroup.prototype.render = function (customRenderFunction) {
  11805. if (customRenderFunction) {
  11806. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11807. return true;
  11808. }
  11809. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11810. if (this.onBeforeTransparentRendering) {
  11811. this.onBeforeTransparentRendering();
  11812. }
  11813. return false;
  11814. }
  11815. var engine = this._scene.getEngine();
  11816. // Opaque
  11817. var subIndex;
  11818. var submesh;
  11819. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11820. submesh = this._opaqueSubMeshes.data[subIndex];
  11821. submesh.render(false);
  11822. }
  11823. // Alpha test
  11824. engine.setAlphaTesting(true);
  11825. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11826. submesh = this._alphaTestSubMeshes.data[subIndex];
  11827. submesh.render(false);
  11828. }
  11829. engine.setAlphaTesting(false);
  11830. if (this.onBeforeTransparentRendering) {
  11831. this.onBeforeTransparentRendering();
  11832. }
  11833. // Transparent
  11834. if (this._transparentSubMeshes.length) {
  11835. // Sorting
  11836. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11837. submesh = this._transparentSubMeshes.data[subIndex];
  11838. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11839. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11840. }
  11841. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11842. sortedArray.sort(function (a, b) {
  11843. // Alpha index first
  11844. if (a._alphaIndex > b._alphaIndex) {
  11845. return 1;
  11846. }
  11847. if (a._alphaIndex < b._alphaIndex) {
  11848. return -1;
  11849. }
  11850. // Then distance to camera
  11851. if (a._distanceToCamera < b._distanceToCamera) {
  11852. return 1;
  11853. }
  11854. if (a._distanceToCamera > b._distanceToCamera) {
  11855. return -1;
  11856. }
  11857. return 0;
  11858. });
  11859. // Rendering
  11860. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11861. submesh = sortedArray[subIndex];
  11862. submesh.render(true);
  11863. }
  11864. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11865. }
  11866. return true;
  11867. };
  11868. RenderingGroup.prototype.prepare = function () {
  11869. this._opaqueSubMeshes.reset();
  11870. this._transparentSubMeshes.reset();
  11871. this._alphaTestSubMeshes.reset();
  11872. };
  11873. RenderingGroup.prototype.dispatch = function (subMesh) {
  11874. var material = subMesh.getMaterial();
  11875. var mesh = subMesh.getMesh();
  11876. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11877. this._transparentSubMeshes.push(subMesh);
  11878. }
  11879. else if (material.needAlphaTesting()) {
  11880. this._alphaTestSubMeshes.push(subMesh);
  11881. }
  11882. else {
  11883. this._opaqueSubMeshes.push(subMesh); // Opaque
  11884. }
  11885. };
  11886. return RenderingGroup;
  11887. })();
  11888. BABYLON.RenderingGroup = RenderingGroup;
  11889. })(BABYLON || (BABYLON = {}));
  11890. var BABYLON;
  11891. (function (BABYLON) {
  11892. /**
  11893. * Represents a scene to be rendered by the engine.
  11894. * @see http://doc.babylonjs.com/page.php?p=21911
  11895. */
  11896. var Scene = (function () {
  11897. /**
  11898. * @constructor
  11899. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11900. */
  11901. function Scene(engine) {
  11902. // Members
  11903. this.autoClear = true;
  11904. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11905. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11906. this.forceWireframe = false;
  11907. this.forcePointsCloud = false;
  11908. this.forceShowBoundingBoxes = false;
  11909. this.animationsEnabled = true;
  11910. this.constantlyUpdateMeshUnderPointer = false;
  11911. 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
  11912. // Fog
  11913. /**
  11914. * is fog enabled on this scene.
  11915. * @type {boolean}
  11916. */
  11917. this.fogEnabled = true;
  11918. this.fogMode = Scene.FOGMODE_NONE;
  11919. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11920. this.fogDensity = 0.1;
  11921. this.fogStart = 0;
  11922. this.fogEnd = 1000.0;
  11923. // Lights
  11924. /**
  11925. * is shadow enabled on this scene.
  11926. * @type {boolean}
  11927. */
  11928. this.shadowsEnabled = true;
  11929. /**
  11930. * is light enabled on this scene.
  11931. * @type {boolean}
  11932. */
  11933. this.lightsEnabled = true;
  11934. /**
  11935. * All of the lights added to this scene.
  11936. * @see BABYLON.Light
  11937. * @type {BABYLON.Light[]}
  11938. */
  11939. this.lights = new Array();
  11940. // Cameras
  11941. /**
  11942. * All of the cameras added to this scene.
  11943. * @see BABYLON.Camera
  11944. * @type {BABYLON.Camera[]}
  11945. */
  11946. this.cameras = new Array();
  11947. this.activeCameras = new Array();
  11948. // Meshes
  11949. /**
  11950. * All of the (abstract) meshes added to this scene.
  11951. * @see BABYLON.AbstractMesh
  11952. * @type {BABYLON.AbstractMesh[]}
  11953. */
  11954. this.meshes = new Array();
  11955. // Geometries
  11956. this._geometries = new Array();
  11957. this.materials = new Array();
  11958. this.multiMaterials = new Array();
  11959. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11960. // Textures
  11961. this.texturesEnabled = true;
  11962. this.textures = new Array();
  11963. // Particles
  11964. this.particlesEnabled = true;
  11965. this.particleSystems = new Array();
  11966. // Sprites
  11967. this.spritesEnabled = true;
  11968. this.spriteManagers = new Array();
  11969. // Layers
  11970. this.layers = new Array();
  11971. // Skeletons
  11972. this.skeletonsEnabled = true;
  11973. this.skeletons = new Array();
  11974. // Lens flares
  11975. this.lensFlaresEnabled = true;
  11976. this.lensFlareSystems = new Array();
  11977. // Collisions
  11978. this.collisionsEnabled = true;
  11979. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11980. // Postprocesses
  11981. this.postProcessesEnabled = true;
  11982. // Customs render targets
  11983. this.renderTargetsEnabled = true;
  11984. this.dumpNextRenderTargets = false;
  11985. this.customRenderTargets = new Array();
  11986. // Imported meshes
  11987. this.importedMeshesFiles = new Array();
  11988. // Probes
  11989. this.probesEnabled = true;
  11990. this.reflectionProbes = new Array();
  11991. this._actionManagers = new Array();
  11992. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11993. // Procedural textures
  11994. this.proceduralTexturesEnabled = true;
  11995. this._proceduralTextures = new Array();
  11996. this.soundTracks = new Array();
  11997. this._audioEnabled = true;
  11998. this._headphone = false;
  11999. this._totalVertices = 0;
  12000. this._activeIndices = 0;
  12001. this._activeParticles = 0;
  12002. this._lastFrameDuration = 0;
  12003. this._evaluateActiveMeshesDuration = 0;
  12004. this._renderTargetsDuration = 0;
  12005. this._particlesDuration = 0;
  12006. this._renderDuration = 0;
  12007. this._spritesDuration = 0;
  12008. this._animationRatio = 0;
  12009. this._renderId = 0;
  12010. this._executeWhenReadyTimeoutId = -1;
  12011. this._toBeDisposed = new BABYLON.SmartArray(256);
  12012. this._onReadyCallbacks = new Array();
  12013. this._pendingData = []; //ANY
  12014. this._onBeforeRenderCallbacks = new Array();
  12015. this._onAfterRenderCallbacks = new Array();
  12016. this._activeMeshes = new BABYLON.SmartArray(256);
  12017. this._processedMaterials = new BABYLON.SmartArray(256);
  12018. this._renderTargets = new BABYLON.SmartArray(256);
  12019. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12020. this._activeSkeletons = new BABYLON.SmartArray(32);
  12021. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12022. this._activeBones = 0;
  12023. this._activeAnimatables = new Array();
  12024. this._transformMatrix = BABYLON.Matrix.Zero();
  12025. this._edgesRenderers = new BABYLON.SmartArray(16);
  12026. this._uniqueIdCounter = 0;
  12027. this._engine = engine;
  12028. engine.scenes.push(this);
  12029. this._renderingManager = new BABYLON.RenderingManager(this);
  12030. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12031. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12032. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12033. if (BABYLON.OutlineRenderer) {
  12034. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12035. }
  12036. this.attachControl();
  12037. this._debugLayer = new BABYLON.DebugLayer(this);
  12038. if (BABYLON.SoundTrack) {
  12039. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12040. }
  12041. //simplification queue
  12042. if (BABYLON.SimplificationQueue) {
  12043. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12044. }
  12045. //collision coordinator initialization. For now legacy per default.
  12046. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12047. }
  12048. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12049. get: function () {
  12050. return Scene._FOGMODE_NONE;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12056. get: function () {
  12057. return Scene._FOGMODE_EXP;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12063. get: function () {
  12064. return Scene._FOGMODE_EXP2;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12070. get: function () {
  12071. return Scene._FOGMODE_LINEAR;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Scene.prototype, "debugLayer", {
  12077. // Properties
  12078. get: function () {
  12079. return this._debugLayer;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12085. get: function () {
  12086. return this._workerCollisions;
  12087. },
  12088. set: function (enabled) {
  12089. enabled = (enabled && !!Worker);
  12090. this._workerCollisions = enabled;
  12091. if (this.collisionCoordinator) {
  12092. this.collisionCoordinator.destroy();
  12093. }
  12094. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12095. this.collisionCoordinator.init(this);
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12101. get: function () {
  12102. return this._selectionOctree;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12108. /**
  12109. * The mesh that is currently under the pointer.
  12110. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12111. */
  12112. get: function () {
  12113. return this._meshUnderPointer;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene.prototype, "pointerX", {
  12119. /**
  12120. * Current on-screen X position of the pointer
  12121. * @return {number} X position of the pointer
  12122. */
  12123. get: function () {
  12124. return this._pointerX;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. Object.defineProperty(Scene.prototype, "pointerY", {
  12130. /**
  12131. * Current on-screen Y position of the pointer
  12132. * @return {number} Y position of the pointer
  12133. */
  12134. get: function () {
  12135. return this._pointerY;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Scene.prototype.getCachedMaterial = function () {
  12141. return this._cachedMaterial;
  12142. };
  12143. Scene.prototype.getBoundingBoxRenderer = function () {
  12144. return this._boundingBoxRenderer;
  12145. };
  12146. Scene.prototype.getOutlineRenderer = function () {
  12147. return this._outlineRenderer;
  12148. };
  12149. Scene.prototype.getEngine = function () {
  12150. return this._engine;
  12151. };
  12152. Scene.prototype.getTotalVertices = function () {
  12153. return this._totalVertices;
  12154. };
  12155. Scene.prototype.getActiveIndices = function () {
  12156. return this._activeIndices;
  12157. };
  12158. Scene.prototype.getActiveParticles = function () {
  12159. return this._activeParticles;
  12160. };
  12161. Scene.prototype.getActiveBones = function () {
  12162. return this._activeBones;
  12163. };
  12164. // Stats
  12165. Scene.prototype.getLastFrameDuration = function () {
  12166. return this._lastFrameDuration;
  12167. };
  12168. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12169. return this._evaluateActiveMeshesDuration;
  12170. };
  12171. Scene.prototype.getActiveMeshes = function () {
  12172. return this._activeMeshes;
  12173. };
  12174. Scene.prototype.getRenderTargetsDuration = function () {
  12175. return this._renderTargetsDuration;
  12176. };
  12177. Scene.prototype.getRenderDuration = function () {
  12178. return this._renderDuration;
  12179. };
  12180. Scene.prototype.getParticlesDuration = function () {
  12181. return this._particlesDuration;
  12182. };
  12183. Scene.prototype.getSpritesDuration = function () {
  12184. return this._spritesDuration;
  12185. };
  12186. Scene.prototype.getAnimationRatio = function () {
  12187. return this._animationRatio;
  12188. };
  12189. Scene.prototype.getRenderId = function () {
  12190. return this._renderId;
  12191. };
  12192. Scene.prototype.incrementRenderId = function () {
  12193. this._renderId++;
  12194. };
  12195. Scene.prototype._updatePointerPosition = function (evt) {
  12196. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12197. this._pointerX = evt.clientX - canvasRect.left;
  12198. this._pointerY = evt.clientY - canvasRect.top;
  12199. if (this.cameraToUseForPointers) {
  12200. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12201. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12202. }
  12203. };
  12204. // Pointers handling
  12205. Scene.prototype.attachControl = function () {
  12206. var _this = this;
  12207. var spritePredicate = function (sprite) {
  12208. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12209. };
  12210. this._onPointerMove = function (evt) {
  12211. var canvas = _this._engine.getRenderingCanvas();
  12212. _this._updatePointerPosition(evt);
  12213. // Meshes
  12214. 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);
  12215. if (pickResult.hit && pickResult.pickedMesh) {
  12216. _this._meshUnderPointer = pickResult.pickedMesh;
  12217. _this.setPointerOverMesh(pickResult.pickedMesh);
  12218. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12219. canvas.style.cursor = "pointer";
  12220. }
  12221. else {
  12222. canvas.style.cursor = "";
  12223. }
  12224. }
  12225. else {
  12226. // Sprites
  12227. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12228. if (pickResult.hit && pickResult.pickedSprite) {
  12229. canvas.style.cursor = "pointer";
  12230. }
  12231. else {
  12232. // Restore pointer
  12233. _this.setPointerOverMesh(null);
  12234. canvas.style.cursor = "";
  12235. _this._meshUnderPointer = null;
  12236. }
  12237. }
  12238. if (_this.onPointerMove) {
  12239. _this.onPointerMove(evt, pickResult);
  12240. }
  12241. };
  12242. this._onPointerDown = function (evt) {
  12243. _this._updatePointerPosition(evt);
  12244. var predicate = null;
  12245. // Meshes
  12246. if (!_this.onPointerDown) {
  12247. predicate = function (mesh) {
  12248. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12249. };
  12250. }
  12251. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12252. if (pickResult.hit && pickResult.pickedMesh) {
  12253. if (pickResult.pickedMesh.actionManager) {
  12254. switch (evt.button) {
  12255. case 0:
  12256. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12257. break;
  12258. case 1:
  12259. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12260. break;
  12261. case 2:
  12262. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12263. break;
  12264. }
  12265. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12266. }
  12267. }
  12268. if (_this.onPointerDown) {
  12269. _this.onPointerDown(evt, pickResult);
  12270. }
  12271. // Sprites
  12272. if (_this.spriteManagers.length > 0) {
  12273. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12274. if (pickResult.hit && pickResult.pickedSprite) {
  12275. if (pickResult.pickedSprite.actionManager) {
  12276. switch (evt.button) {
  12277. case 0:
  12278. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12279. break;
  12280. case 1:
  12281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12282. break;
  12283. case 2:
  12284. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12285. break;
  12286. }
  12287. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12288. }
  12289. }
  12290. }
  12291. };
  12292. this._onPointerUp = function (evt) {
  12293. var predicate = null;
  12294. _this._updatePointerPosition(evt);
  12295. if (!_this.onPointerUp) {
  12296. predicate = function (mesh) {
  12297. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12298. };
  12299. }
  12300. // Meshes
  12301. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12302. if (pickResult.hit && pickResult.pickedMesh) {
  12303. if (pickResult.pickedMesh.actionManager) {
  12304. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12305. }
  12306. }
  12307. if (_this.onPointerUp) {
  12308. _this.onPointerUp(evt, pickResult);
  12309. }
  12310. // Sprites
  12311. if (_this.spriteManagers.length > 0) {
  12312. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12313. if (pickResult.hit && pickResult.pickedSprite) {
  12314. if (pickResult.pickedSprite.actionManager) {
  12315. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12316. }
  12317. }
  12318. }
  12319. };
  12320. this._onKeyDown = function (evt) {
  12321. if (_this.actionManager) {
  12322. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12323. }
  12324. };
  12325. this._onKeyUp = function (evt) {
  12326. if (_this.actionManager) {
  12327. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12328. }
  12329. };
  12330. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12331. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12332. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12333. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12334. // Wheel
  12335. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12336. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12337. BABYLON.Tools.RegisterTopRootEvents([
  12338. { name: "keydown", handler: this._onKeyDown },
  12339. { name: "keyup", handler: this._onKeyUp }
  12340. ]);
  12341. };
  12342. Scene.prototype.detachControl = function () {
  12343. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12344. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12345. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12346. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12347. // Wheel
  12348. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12349. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12350. BABYLON.Tools.UnregisterTopRootEvents([
  12351. { name: "keydown", handler: this._onKeyDown },
  12352. { name: "keyup", handler: this._onKeyUp }
  12353. ]);
  12354. };
  12355. // Ready
  12356. Scene.prototype.isReady = function () {
  12357. if (this._pendingData.length > 0) {
  12358. return false;
  12359. }
  12360. var index;
  12361. for (index = 0; index < this._geometries.length; index++) {
  12362. var geometry = this._geometries[index];
  12363. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12364. return false;
  12365. }
  12366. }
  12367. for (index = 0; index < this.meshes.length; index++) {
  12368. var mesh = this.meshes[index];
  12369. if (!mesh.isReady()) {
  12370. return false;
  12371. }
  12372. var mat = mesh.material;
  12373. if (mat) {
  12374. if (!mat.isReady(mesh)) {
  12375. return false;
  12376. }
  12377. }
  12378. }
  12379. return true;
  12380. };
  12381. Scene.prototype.resetCachedMaterial = function () {
  12382. this._cachedMaterial = null;
  12383. };
  12384. Scene.prototype.registerBeforeRender = function (func) {
  12385. this._onBeforeRenderCallbacks.push(func);
  12386. };
  12387. Scene.prototype.unregisterBeforeRender = function (func) {
  12388. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12389. if (index > -1) {
  12390. this._onBeforeRenderCallbacks.splice(index, 1);
  12391. }
  12392. };
  12393. Scene.prototype.registerAfterRender = function (func) {
  12394. this._onAfterRenderCallbacks.push(func);
  12395. };
  12396. Scene.prototype.unregisterAfterRender = function (func) {
  12397. var index = this._onAfterRenderCallbacks.indexOf(func);
  12398. if (index > -1) {
  12399. this._onAfterRenderCallbacks.splice(index, 1);
  12400. }
  12401. };
  12402. Scene.prototype._addPendingData = function (data) {
  12403. this._pendingData.push(data);
  12404. };
  12405. Scene.prototype._removePendingData = function (data) {
  12406. var index = this._pendingData.indexOf(data);
  12407. if (index !== -1) {
  12408. this._pendingData.splice(index, 1);
  12409. }
  12410. };
  12411. Scene.prototype.getWaitingItemsCount = function () {
  12412. return this._pendingData.length;
  12413. };
  12414. /**
  12415. * Registers a function to be executed when the scene is ready.
  12416. * @param {Function} func - the function to be executed.
  12417. */
  12418. Scene.prototype.executeWhenReady = function (func) {
  12419. var _this = this;
  12420. this._onReadyCallbacks.push(func);
  12421. if (this._executeWhenReadyTimeoutId !== -1) {
  12422. return;
  12423. }
  12424. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12425. _this._checkIsReady();
  12426. }, 150);
  12427. };
  12428. Scene.prototype._checkIsReady = function () {
  12429. var _this = this;
  12430. if (this.isReady()) {
  12431. this._onReadyCallbacks.forEach(function (func) {
  12432. func();
  12433. });
  12434. this._onReadyCallbacks = [];
  12435. this._executeWhenReadyTimeoutId = -1;
  12436. return;
  12437. }
  12438. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12439. _this._checkIsReady();
  12440. }, 150);
  12441. };
  12442. // Animations
  12443. /**
  12444. * Will start the animation sequence of a given target
  12445. * @param target - the target
  12446. * @param {number} from - from which frame should animation start
  12447. * @param {number} to - till which frame should animation run.
  12448. * @param {boolean} [loop] - should the animation loop
  12449. * @param {number} [speedRatio] - the speed in which to run the animation
  12450. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12451. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12452. * @return {BABYLON.Animatable} the animatable object created for this animation
  12453. * @see BABYLON.Animatable
  12454. * @see http://doc.babylonjs.com/page.php?p=22081
  12455. */
  12456. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12457. if (speedRatio === void 0) { speedRatio = 1.0; }
  12458. this.stopAnimation(target);
  12459. if (!animatable) {
  12460. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12461. }
  12462. // Local animations
  12463. if (target.animations) {
  12464. animatable.appendAnimations(target, target.animations);
  12465. }
  12466. // Children animations
  12467. if (target.getAnimatables) {
  12468. var animatables = target.getAnimatables();
  12469. for (var index = 0; index < animatables.length; index++) {
  12470. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12471. }
  12472. }
  12473. return animatable;
  12474. };
  12475. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12476. if (speedRatio === undefined) {
  12477. speedRatio = 1.0;
  12478. }
  12479. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12480. return animatable;
  12481. };
  12482. Scene.prototype.getAnimatableByTarget = function (target) {
  12483. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12484. if (this._activeAnimatables[index].target === target) {
  12485. return this._activeAnimatables[index];
  12486. }
  12487. }
  12488. return null;
  12489. };
  12490. /**
  12491. * Will stop the animation of the given target
  12492. * @param target - the target
  12493. * @see beginAnimation
  12494. */
  12495. Scene.prototype.stopAnimation = function (target) {
  12496. var animatable = this.getAnimatableByTarget(target);
  12497. if (animatable) {
  12498. animatable.stop();
  12499. }
  12500. };
  12501. Scene.prototype._animate = function () {
  12502. if (!this.animationsEnabled) {
  12503. return;
  12504. }
  12505. if (!this._animationStartDate) {
  12506. this._animationStartDate = BABYLON.Tools.Now;
  12507. }
  12508. // Getting time
  12509. var now = BABYLON.Tools.Now;
  12510. var delay = now - this._animationStartDate;
  12511. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12512. this._activeAnimatables[index]._animate(delay);
  12513. }
  12514. };
  12515. // Matrix
  12516. Scene.prototype.getViewMatrix = function () {
  12517. return this._viewMatrix;
  12518. };
  12519. Scene.prototype.getProjectionMatrix = function () {
  12520. return this._projectionMatrix;
  12521. };
  12522. Scene.prototype.getTransformMatrix = function () {
  12523. return this._transformMatrix;
  12524. };
  12525. Scene.prototype.setTransformMatrix = function (view, projection) {
  12526. this._viewMatrix = view;
  12527. this._projectionMatrix = projection;
  12528. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12529. };
  12530. // Methods
  12531. Scene.prototype.addMesh = function (newMesh) {
  12532. newMesh.uniqueId = this._uniqueIdCounter++;
  12533. var position = this.meshes.push(newMesh);
  12534. //notify the collision coordinator
  12535. this.collisionCoordinator.onMeshAdded(newMesh);
  12536. if (this.onNewMeshAdded) {
  12537. this.onNewMeshAdded(newMesh, position, this);
  12538. }
  12539. };
  12540. Scene.prototype.removeMesh = function (toRemove) {
  12541. var index = this.meshes.indexOf(toRemove);
  12542. if (index !== -1) {
  12543. // Remove from the scene if mesh found
  12544. this.meshes.splice(index, 1);
  12545. }
  12546. //notify the collision coordinator
  12547. this.collisionCoordinator.onMeshRemoved(toRemove);
  12548. if (this.onMeshRemoved) {
  12549. this.onMeshRemoved(toRemove);
  12550. }
  12551. return index;
  12552. };
  12553. Scene.prototype.removeSkeleton = function (toRemove) {
  12554. var index = this.skeletons.indexOf(toRemove);
  12555. if (index !== -1) {
  12556. // Remove from the scene if mesh found
  12557. this.skeletons.splice(index, 1);
  12558. }
  12559. return index;
  12560. };
  12561. Scene.prototype.removeLight = function (toRemove) {
  12562. var index = this.lights.indexOf(toRemove);
  12563. if (index !== -1) {
  12564. // Remove from the scene if mesh found
  12565. this.lights.splice(index, 1);
  12566. }
  12567. if (this.onLightRemoved) {
  12568. this.onLightRemoved(toRemove);
  12569. }
  12570. return index;
  12571. };
  12572. Scene.prototype.removeCamera = function (toRemove) {
  12573. var index = this.cameras.indexOf(toRemove);
  12574. if (index !== -1) {
  12575. // Remove from the scene if mesh found
  12576. this.cameras.splice(index, 1);
  12577. }
  12578. // Remove from activeCameras
  12579. var index2 = this.activeCameras.indexOf(toRemove);
  12580. if (index2 !== -1) {
  12581. // Remove from the scene if mesh found
  12582. this.activeCameras.splice(index2, 1);
  12583. }
  12584. // Reset the activeCamera
  12585. if (this.activeCamera === toRemove) {
  12586. if (this.cameras.length > 0) {
  12587. this.activeCamera = this.cameras[0];
  12588. }
  12589. else {
  12590. this.activeCamera = null;
  12591. }
  12592. }
  12593. if (this.onCameraRemoved) {
  12594. this.onCameraRemoved(toRemove);
  12595. }
  12596. return index;
  12597. };
  12598. Scene.prototype.addLight = function (newLight) {
  12599. newLight.uniqueId = this._uniqueIdCounter++;
  12600. var position = this.lights.push(newLight);
  12601. if (this.onNewLightAdded) {
  12602. this.onNewLightAdded(newLight, position, this);
  12603. }
  12604. };
  12605. Scene.prototype.addCamera = function (newCamera) {
  12606. newCamera.uniqueId = this._uniqueIdCounter++;
  12607. var position = this.cameras.push(newCamera);
  12608. if (this.onNewCameraAdded) {
  12609. this.onNewCameraAdded(newCamera, position, this);
  12610. }
  12611. };
  12612. /**
  12613. * sets the active camera of the scene using its ID
  12614. * @param {string} id - the camera's ID
  12615. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12616. * @see activeCamera
  12617. */
  12618. Scene.prototype.setActiveCameraByID = function (id) {
  12619. var camera = this.getCameraByID(id);
  12620. if (camera) {
  12621. this.activeCamera = camera;
  12622. return camera;
  12623. }
  12624. return null;
  12625. };
  12626. /**
  12627. * sets the active camera of the scene using its name
  12628. * @param {string} name - the camera's name
  12629. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12630. * @see activeCamera
  12631. */
  12632. Scene.prototype.setActiveCameraByName = function (name) {
  12633. var camera = this.getCameraByName(name);
  12634. if (camera) {
  12635. this.activeCamera = camera;
  12636. return camera;
  12637. }
  12638. return null;
  12639. };
  12640. /**
  12641. * get a material using its id
  12642. * @param {string} the material's ID
  12643. * @return {BABYLON.Material|null} the material or null if none found.
  12644. */
  12645. Scene.prototype.getMaterialByID = function (id) {
  12646. for (var index = 0; index < this.materials.length; index++) {
  12647. if (this.materials[index].id === id) {
  12648. return this.materials[index];
  12649. }
  12650. }
  12651. return null;
  12652. };
  12653. /**
  12654. * get a material using its name
  12655. * @param {string} the material's name
  12656. * @return {BABYLON.Material|null} the material or null if none found.
  12657. */
  12658. Scene.prototype.getMaterialByName = function (name) {
  12659. for (var index = 0; index < this.materials.length; index++) {
  12660. if (this.materials[index].name === name) {
  12661. return this.materials[index];
  12662. }
  12663. }
  12664. return null;
  12665. };
  12666. Scene.prototype.getLensFlareSystemByName = function (name) {
  12667. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12668. if (this.lensFlareSystems[index].name === name) {
  12669. return this.lensFlareSystems[index];
  12670. }
  12671. }
  12672. return null;
  12673. };
  12674. Scene.prototype.getCameraByID = function (id) {
  12675. for (var index = 0; index < this.cameras.length; index++) {
  12676. if (this.cameras[index].id === id) {
  12677. return this.cameras[index];
  12678. }
  12679. }
  12680. return null;
  12681. };
  12682. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12683. for (var index = 0; index < this.cameras.length; index++) {
  12684. if (this.cameras[index].uniqueId === uniqueId) {
  12685. return this.cameras[index];
  12686. }
  12687. }
  12688. return null;
  12689. };
  12690. /**
  12691. * get a camera using its name
  12692. * @param {string} the camera's name
  12693. * @return {BABYLON.Camera|null} the camera or null if none found.
  12694. */
  12695. Scene.prototype.getCameraByName = function (name) {
  12696. for (var index = 0; index < this.cameras.length; index++) {
  12697. if (this.cameras[index].name === name) {
  12698. return this.cameras[index];
  12699. }
  12700. }
  12701. return null;
  12702. };
  12703. /**
  12704. * get a light node using its name
  12705. * @param {string} the light's name
  12706. * @return {BABYLON.Light|null} the light or null if none found.
  12707. */
  12708. Scene.prototype.getLightByName = function (name) {
  12709. for (var index = 0; index < this.lights.length; index++) {
  12710. if (this.lights[index].name === name) {
  12711. return this.lights[index];
  12712. }
  12713. }
  12714. return null;
  12715. };
  12716. /**
  12717. * get a light node using its ID
  12718. * @param {string} the light's id
  12719. * @return {BABYLON.Light|null} the light or null if none found.
  12720. */
  12721. Scene.prototype.getLightByID = function (id) {
  12722. for (var index = 0; index < this.lights.length; index++) {
  12723. if (this.lights[index].id === id) {
  12724. return this.lights[index];
  12725. }
  12726. }
  12727. return null;
  12728. };
  12729. /**
  12730. * get a light node using its scene-generated unique ID
  12731. * @param {number} the light's unique id
  12732. * @return {BABYLON.Light|null} the light or null if none found.
  12733. */
  12734. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12735. for (var index = 0; index < this.lights.length; index++) {
  12736. if (this.lights[index].uniqueId === uniqueId) {
  12737. return this.lights[index];
  12738. }
  12739. }
  12740. return null;
  12741. };
  12742. /**
  12743. * get a geometry using its ID
  12744. * @param {string} the geometry's id
  12745. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12746. */
  12747. Scene.prototype.getGeometryByID = function (id) {
  12748. for (var index = 0; index < this._geometries.length; index++) {
  12749. if (this._geometries[index].id === id) {
  12750. return this._geometries[index];
  12751. }
  12752. }
  12753. return null;
  12754. };
  12755. /**
  12756. * add a new geometry to this scene.
  12757. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12758. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12759. * @return {boolean} was the geometry added or not
  12760. */
  12761. Scene.prototype.pushGeometry = function (geometry, force) {
  12762. if (!force && this.getGeometryByID(geometry.id)) {
  12763. return false;
  12764. }
  12765. this._geometries.push(geometry);
  12766. //notify the collision coordinator
  12767. this.collisionCoordinator.onGeometryAdded(geometry);
  12768. if (this.onGeometryAdded) {
  12769. this.onGeometryAdded(geometry);
  12770. }
  12771. return true;
  12772. };
  12773. /**
  12774. * Removes an existing geometry
  12775. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12776. * @return {boolean} was the geometry removed or not
  12777. */
  12778. Scene.prototype.removeGeometry = function (geometry) {
  12779. var index = this._geometries.indexOf(geometry);
  12780. if (index > -1) {
  12781. this._geometries.splice(index, 1);
  12782. //notify the collision coordinator
  12783. this.collisionCoordinator.onGeometryDeleted(geometry);
  12784. if (this.onGeometryRemoved) {
  12785. this.onGeometryRemoved(geometry);
  12786. }
  12787. return true;
  12788. }
  12789. return false;
  12790. };
  12791. Scene.prototype.getGeometries = function () {
  12792. return this._geometries;
  12793. };
  12794. /**
  12795. * Get the first added mesh found of a given ID
  12796. * @param {string} id - the id to search for
  12797. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12798. */
  12799. Scene.prototype.getMeshByID = function (id) {
  12800. for (var index = 0; index < this.meshes.length; index++) {
  12801. if (this.meshes[index].id === id) {
  12802. return this.meshes[index];
  12803. }
  12804. }
  12805. return null;
  12806. };
  12807. /**
  12808. * Get a mesh with its auto-generated unique id
  12809. * @param {number} uniqueId - the unique id to search for
  12810. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12811. */
  12812. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12813. for (var index = 0; index < this.meshes.length; index++) {
  12814. if (this.meshes[index].uniqueId === uniqueId) {
  12815. return this.meshes[index];
  12816. }
  12817. }
  12818. return null;
  12819. };
  12820. /**
  12821. * Get a the last added mesh found of a given ID
  12822. * @param {string} id - the id to search for
  12823. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12824. */
  12825. Scene.prototype.getLastMeshByID = function (id) {
  12826. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12827. if (this.meshes[index].id === id) {
  12828. return this.meshes[index];
  12829. }
  12830. }
  12831. return null;
  12832. };
  12833. /**
  12834. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12835. * @param {string} id - the id to search for
  12836. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12837. */
  12838. Scene.prototype.getLastEntryByID = function (id) {
  12839. var index;
  12840. for (index = this.meshes.length - 1; index >= 0; index--) {
  12841. if (this.meshes[index].id === id) {
  12842. return this.meshes[index];
  12843. }
  12844. }
  12845. for (index = this.cameras.length - 1; index >= 0; index--) {
  12846. if (this.cameras[index].id === id) {
  12847. return this.cameras[index];
  12848. }
  12849. }
  12850. for (index = this.lights.length - 1; index >= 0; index--) {
  12851. if (this.lights[index].id === id) {
  12852. return this.lights[index];
  12853. }
  12854. }
  12855. return null;
  12856. };
  12857. Scene.prototype.getNodeByID = function (id) {
  12858. var mesh = this.getMeshByID(id);
  12859. if (mesh) {
  12860. return mesh;
  12861. }
  12862. var light = this.getLightByID(id);
  12863. if (light) {
  12864. return light;
  12865. }
  12866. return this.getCameraByID(id);
  12867. };
  12868. Scene.prototype.getNodeByName = function (name) {
  12869. var mesh = this.getMeshByName(name);
  12870. if (mesh) {
  12871. return mesh;
  12872. }
  12873. var light = this.getLightByName(name);
  12874. if (light) {
  12875. return light;
  12876. }
  12877. return this.getCameraByName(name);
  12878. };
  12879. Scene.prototype.getMeshByName = function (name) {
  12880. for (var index = 0; index < this.meshes.length; index++) {
  12881. if (this.meshes[index].name === name) {
  12882. return this.meshes[index];
  12883. }
  12884. }
  12885. return null;
  12886. };
  12887. Scene.prototype.getSoundByName = function (name) {
  12888. var index;
  12889. if (BABYLON.AudioEngine) {
  12890. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12891. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12892. return this.mainSoundTrack.soundCollection[index];
  12893. }
  12894. }
  12895. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12896. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12897. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12898. return this.soundTracks[sdIndex].soundCollection[index];
  12899. }
  12900. }
  12901. }
  12902. }
  12903. return null;
  12904. };
  12905. Scene.prototype.getLastSkeletonByID = function (id) {
  12906. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12907. if (this.skeletons[index].id === id) {
  12908. return this.skeletons[index];
  12909. }
  12910. }
  12911. return null;
  12912. };
  12913. Scene.prototype.getSkeletonById = function (id) {
  12914. for (var index = 0; index < this.skeletons.length; index++) {
  12915. if (this.skeletons[index].id === id) {
  12916. return this.skeletons[index];
  12917. }
  12918. }
  12919. return null;
  12920. };
  12921. Scene.prototype.getSkeletonByName = function (name) {
  12922. for (var index = 0; index < this.skeletons.length; index++) {
  12923. if (this.skeletons[index].name === name) {
  12924. return this.skeletons[index];
  12925. }
  12926. }
  12927. return null;
  12928. };
  12929. Scene.prototype.isActiveMesh = function (mesh) {
  12930. return (this._activeMeshes.indexOf(mesh) !== -1);
  12931. };
  12932. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12933. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12934. var material = subMesh.getMaterial();
  12935. if (mesh.showSubMeshesBoundingBox) {
  12936. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12937. }
  12938. if (material) {
  12939. // Render targets
  12940. if (material.getRenderTargetTextures) {
  12941. if (this._processedMaterials.indexOf(material) === -1) {
  12942. this._processedMaterials.push(material);
  12943. this._renderTargets.concat(material.getRenderTargetTextures());
  12944. }
  12945. }
  12946. // Dispatch
  12947. this._activeIndices += subMesh.indexCount;
  12948. this._renderingManager.dispatch(subMesh);
  12949. }
  12950. }
  12951. };
  12952. Scene.prototype._evaluateActiveMeshes = function () {
  12953. this.activeCamera._activeMeshes.reset();
  12954. this._activeMeshes.reset();
  12955. this._renderingManager.reset();
  12956. this._processedMaterials.reset();
  12957. this._activeParticleSystems.reset();
  12958. this._activeSkeletons.reset();
  12959. this._softwareSkinnedMeshes.reset();
  12960. this._boundingBoxRenderer.reset();
  12961. this._edgesRenderers.reset();
  12962. if (!this._frustumPlanes) {
  12963. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12964. }
  12965. else {
  12966. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12967. }
  12968. // Meshes
  12969. var meshes;
  12970. var len;
  12971. if (this._selectionOctree) {
  12972. var selection = this._selectionOctree.select(this._frustumPlanes);
  12973. meshes = selection.data;
  12974. len = selection.length;
  12975. }
  12976. else {
  12977. len = this.meshes.length;
  12978. meshes = this.meshes;
  12979. }
  12980. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12981. var mesh = meshes[meshIndex];
  12982. if (mesh.isBlocked) {
  12983. continue;
  12984. }
  12985. this._totalVertices += mesh.getTotalVertices();
  12986. if (!mesh.isReady() || !mesh.isEnabled()) {
  12987. continue;
  12988. }
  12989. mesh.computeWorldMatrix();
  12990. // Intersections
  12991. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12992. this._meshesForIntersections.pushNoDuplicate(mesh);
  12993. }
  12994. // Switch to current LOD
  12995. var meshLOD = mesh.getLOD(this.activeCamera);
  12996. if (!meshLOD) {
  12997. continue;
  12998. }
  12999. mesh._preActivate();
  13000. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13001. this._activeMeshes.push(mesh);
  13002. this.activeCamera._activeMeshes.push(mesh);
  13003. mesh._activate(this._renderId);
  13004. this._activeMesh(meshLOD);
  13005. }
  13006. }
  13007. // Particle systems
  13008. var beforeParticlesDate = BABYLON.Tools.Now;
  13009. if (this.particlesEnabled) {
  13010. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13011. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13012. var particleSystem = this.particleSystems[particleIndex];
  13013. if (!particleSystem.isStarted()) {
  13014. continue;
  13015. }
  13016. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13017. this._activeParticleSystems.push(particleSystem);
  13018. particleSystem.animate();
  13019. }
  13020. }
  13021. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13022. }
  13023. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13024. };
  13025. Scene.prototype._activeMesh = function (mesh) {
  13026. if (mesh.skeleton && this.skeletonsEnabled) {
  13027. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13028. if (!mesh.computeBonesUsingShaders) {
  13029. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13030. }
  13031. }
  13032. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13033. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13034. }
  13035. if (mesh._edgesRenderer) {
  13036. this._edgesRenderers.push(mesh._edgesRenderer);
  13037. }
  13038. if (mesh && mesh.subMeshes) {
  13039. // Submeshes Octrees
  13040. var len;
  13041. var subMeshes;
  13042. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13043. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13044. len = intersections.length;
  13045. subMeshes = intersections.data;
  13046. }
  13047. else {
  13048. subMeshes = mesh.subMeshes;
  13049. len = subMeshes.length;
  13050. }
  13051. for (var subIndex = 0; subIndex < len; subIndex++) {
  13052. var subMesh = subMeshes[subIndex];
  13053. this._evaluateSubMesh(subMesh, mesh);
  13054. }
  13055. }
  13056. };
  13057. Scene.prototype.updateTransformMatrix = function (force) {
  13058. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13059. };
  13060. Scene.prototype._renderForCamera = function (camera) {
  13061. var engine = this._engine;
  13062. this.activeCamera = camera;
  13063. if (!this.activeCamera)
  13064. throw new Error("Active camera not set");
  13065. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13066. // Viewport
  13067. engine.setViewport(this.activeCamera.viewport);
  13068. // Camera
  13069. this.resetCachedMaterial();
  13070. this._renderId++;
  13071. this.updateTransformMatrix();
  13072. if (this.beforeCameraRender) {
  13073. this.beforeCameraRender(this.activeCamera);
  13074. }
  13075. // Meshes
  13076. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13077. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13078. this._evaluateActiveMeshes();
  13079. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13080. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13081. // Skeletons
  13082. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13083. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13084. skeleton.prepare();
  13085. }
  13086. // Software skinning
  13087. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13088. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13089. mesh.applySkeleton(mesh.skeleton);
  13090. }
  13091. // Render targets
  13092. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13093. if (this.renderTargetsEnabled) {
  13094. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13095. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13096. var renderTarget = this._renderTargets.data[renderIndex];
  13097. if (renderTarget._shouldRender()) {
  13098. this._renderId++;
  13099. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13100. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13101. }
  13102. }
  13103. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13104. this._renderId++;
  13105. }
  13106. if (this._renderTargets.length > 0) {
  13107. engine.restoreDefaultFramebuffer();
  13108. }
  13109. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13110. // Prepare Frame
  13111. this.postProcessManager._prepareFrame();
  13112. var beforeRenderDate = BABYLON.Tools.Now;
  13113. // Backgrounds
  13114. var layerIndex;
  13115. var layer;
  13116. if (this.layers.length) {
  13117. engine.setDepthBuffer(false);
  13118. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13119. layer = this.layers[layerIndex];
  13120. if (layer.isBackground) {
  13121. layer.render();
  13122. }
  13123. }
  13124. engine.setDepthBuffer(true);
  13125. }
  13126. // Render
  13127. BABYLON.Tools.StartPerformanceCounter("Main render");
  13128. this._renderingManager.render(null, null, true, true);
  13129. BABYLON.Tools.EndPerformanceCounter("Main render");
  13130. // Bounding boxes
  13131. this._boundingBoxRenderer.render();
  13132. // Edges
  13133. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13134. this._edgesRenderers.data[edgesRendererIndex].render();
  13135. }
  13136. // Lens flares
  13137. if (this.lensFlaresEnabled) {
  13138. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13139. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13140. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13141. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13142. lensFlareSystem.render();
  13143. }
  13144. }
  13145. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13146. }
  13147. // Foregrounds
  13148. if (this.layers.length) {
  13149. engine.setDepthBuffer(false);
  13150. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13151. layer = this.layers[layerIndex];
  13152. if (!layer.isBackground) {
  13153. layer.render();
  13154. }
  13155. }
  13156. engine.setDepthBuffer(true);
  13157. }
  13158. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13159. // Finalize frame
  13160. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13161. // Update camera
  13162. this.activeCamera._updateFromScene();
  13163. // Reset some special arrays
  13164. this._renderTargets.reset();
  13165. if (this.afterCameraRender) {
  13166. this.afterCameraRender(this.activeCamera);
  13167. }
  13168. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13169. };
  13170. Scene.prototype._processSubCameras = function (camera) {
  13171. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13172. this._renderForCamera(camera);
  13173. return;
  13174. }
  13175. // rig cameras
  13176. for (var index = 0; index < camera._rigCameras.length; index++) {
  13177. this._renderForCamera(camera._rigCameras[index]);
  13178. }
  13179. this.activeCamera = camera;
  13180. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13181. // Update camera
  13182. this.activeCamera._updateFromScene();
  13183. };
  13184. Scene.prototype._checkIntersections = function () {
  13185. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13186. var sourceMesh = this._meshesForIntersections.data[index];
  13187. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13188. var action = sourceMesh.actionManager.actions[actionIndex];
  13189. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13190. var parameters = action.getTriggerParameter();
  13191. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13192. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13193. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13194. if (areIntersecting && currentIntersectionInProgress === -1) {
  13195. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13196. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13197. sourceMesh._intersectionsInProgress.push(otherMesh);
  13198. }
  13199. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13200. sourceMesh._intersectionsInProgress.push(otherMesh);
  13201. }
  13202. }
  13203. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13204. //They intersected, and now they don't.
  13205. //is this trigger an exit trigger? execute an event.
  13206. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13207. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13208. }
  13209. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13210. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13211. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13212. }
  13213. }
  13214. }
  13215. }
  13216. }
  13217. };
  13218. Scene.prototype.render = function () {
  13219. var startDate = BABYLON.Tools.Now;
  13220. this._particlesDuration = 0;
  13221. this._spritesDuration = 0;
  13222. this._activeParticles = 0;
  13223. this._renderDuration = 0;
  13224. this._renderTargetsDuration = 0;
  13225. this._evaluateActiveMeshesDuration = 0;
  13226. this._totalVertices = 0;
  13227. this._activeIndices = 0;
  13228. this._activeBones = 0;
  13229. this.getEngine().resetDrawCalls();
  13230. this._meshesForIntersections.reset();
  13231. this.resetCachedMaterial();
  13232. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13233. // Actions
  13234. if (this.actionManager) {
  13235. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13236. }
  13237. //Simplification Queue
  13238. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13239. this.simplificationQueue.executeNext();
  13240. }
  13241. // Animations
  13242. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13243. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13244. this._animate();
  13245. // Physics
  13246. if (this._physicsEngine) {
  13247. BABYLON.Tools.StartPerformanceCounter("Physics");
  13248. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13249. BABYLON.Tools.EndPerformanceCounter("Physics");
  13250. }
  13251. // Before render
  13252. if (this.beforeRender) {
  13253. this.beforeRender();
  13254. }
  13255. var callbackIndex;
  13256. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13257. this._onBeforeRenderCallbacks[callbackIndex]();
  13258. }
  13259. // Customs render targets
  13260. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13261. var engine = this.getEngine();
  13262. var currentActiveCamera = this.activeCamera;
  13263. if (this.renderTargetsEnabled) {
  13264. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13265. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13266. var renderTarget = this.customRenderTargets[customIndex];
  13267. if (renderTarget._shouldRender()) {
  13268. this._renderId++;
  13269. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13270. if (!this.activeCamera)
  13271. throw new Error("Active camera not set");
  13272. // Viewport
  13273. engine.setViewport(this.activeCamera.viewport);
  13274. // Camera
  13275. this.updateTransformMatrix();
  13276. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13277. }
  13278. }
  13279. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13280. this._renderId++;
  13281. }
  13282. if (this.customRenderTargets.length > 0) {
  13283. engine.restoreDefaultFramebuffer();
  13284. }
  13285. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13286. this.activeCamera = currentActiveCamera;
  13287. // Procedural textures
  13288. if (this.proceduralTexturesEnabled) {
  13289. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13290. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13291. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13292. if (proceduralTexture._shouldRender()) {
  13293. proceduralTexture.render();
  13294. }
  13295. }
  13296. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13297. }
  13298. // Clear
  13299. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13300. // Shadows
  13301. if (this.shadowsEnabled) {
  13302. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13303. var light = this.lights[lightIndex];
  13304. var shadowGenerator = light.getShadowGenerator();
  13305. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13306. this._renderTargets.push(shadowGenerator.getShadowMap());
  13307. }
  13308. }
  13309. }
  13310. // Depth renderer
  13311. if (this._depthRenderer) {
  13312. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13313. }
  13314. // RenderPipeline
  13315. this.postProcessRenderPipelineManager.update();
  13316. // Multi-cameras?
  13317. if (this.activeCameras.length > 0) {
  13318. var currentRenderId = this._renderId;
  13319. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13320. this._renderId = currentRenderId;
  13321. this._processSubCameras(this.activeCameras[cameraIndex]);
  13322. }
  13323. }
  13324. else {
  13325. if (!this.activeCamera) {
  13326. throw new Error("No camera defined");
  13327. }
  13328. this._processSubCameras(this.activeCamera);
  13329. }
  13330. // Intersection checks
  13331. this._checkIntersections();
  13332. // Update the audio listener attached to the camera
  13333. if (BABYLON.AudioEngine) {
  13334. this._updateAudioParameters();
  13335. }
  13336. // After render
  13337. if (this.afterRender) {
  13338. this.afterRender();
  13339. }
  13340. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13341. this._onAfterRenderCallbacks[callbackIndex]();
  13342. }
  13343. // Cleaning
  13344. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13345. this._toBeDisposed.data[index].dispose();
  13346. this._toBeDisposed[index] = null;
  13347. }
  13348. this._toBeDisposed.reset();
  13349. if (this.dumpNextRenderTargets) {
  13350. this.dumpNextRenderTargets = false;
  13351. }
  13352. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13353. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13354. };
  13355. Scene.prototype._updateAudioParameters = function () {
  13356. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13357. return;
  13358. }
  13359. var listeningCamera;
  13360. var audioEngine = BABYLON.Engine.audioEngine;
  13361. if (this.activeCameras.length > 0) {
  13362. listeningCamera = this.activeCameras[0];
  13363. }
  13364. else {
  13365. listeningCamera = this.activeCamera;
  13366. }
  13367. if (listeningCamera && audioEngine.canUseWebAudio) {
  13368. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13369. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13370. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13371. cameraDirection.normalize();
  13372. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13373. var i;
  13374. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13375. var sound = this.mainSoundTrack.soundCollection[i];
  13376. if (sound.useCustomAttenuation) {
  13377. sound.updateDistanceFromListener();
  13378. }
  13379. }
  13380. for (i = 0; i < this.soundTracks.length; i++) {
  13381. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13382. sound = this.soundTracks[i].soundCollection[j];
  13383. if (sound.useCustomAttenuation) {
  13384. sound.updateDistanceFromListener();
  13385. }
  13386. }
  13387. }
  13388. }
  13389. };
  13390. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13391. // Audio
  13392. get: function () {
  13393. return this._audioEnabled;
  13394. },
  13395. set: function (value) {
  13396. this._audioEnabled = value;
  13397. if (BABYLON.AudioEngine) {
  13398. if (this._audioEnabled) {
  13399. this._enableAudio();
  13400. }
  13401. else {
  13402. this._disableAudio();
  13403. }
  13404. }
  13405. },
  13406. enumerable: true,
  13407. configurable: true
  13408. });
  13409. Scene.prototype._disableAudio = function () {
  13410. var i;
  13411. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13412. this.mainSoundTrack.soundCollection[i].pause();
  13413. }
  13414. for (i = 0; i < this.soundTracks.length; i++) {
  13415. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13416. this.soundTracks[i].soundCollection[j].pause();
  13417. }
  13418. }
  13419. };
  13420. Scene.prototype._enableAudio = function () {
  13421. var i;
  13422. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13423. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13424. this.mainSoundTrack.soundCollection[i].play();
  13425. }
  13426. }
  13427. for (i = 0; i < this.soundTracks.length; i++) {
  13428. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13429. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13430. this.soundTracks[i].soundCollection[j].play();
  13431. }
  13432. }
  13433. }
  13434. };
  13435. Object.defineProperty(Scene.prototype, "headphone", {
  13436. get: function () {
  13437. return this._headphone;
  13438. },
  13439. set: function (value) {
  13440. this._headphone = value;
  13441. if (BABYLON.AudioEngine) {
  13442. if (this._headphone) {
  13443. this._switchAudioModeForHeadphones();
  13444. }
  13445. else {
  13446. this._switchAudioModeForNormalSpeakers();
  13447. }
  13448. }
  13449. },
  13450. enumerable: true,
  13451. configurable: true
  13452. });
  13453. Scene.prototype._switchAudioModeForHeadphones = function () {
  13454. this.mainSoundTrack.switchPanningModelToHRTF();
  13455. for (var i = 0; i < this.soundTracks.length; i++) {
  13456. this.soundTracks[i].switchPanningModelToHRTF();
  13457. }
  13458. };
  13459. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13460. this.mainSoundTrack.switchPanningModelToEqualPower();
  13461. for (var i = 0; i < this.soundTracks.length; i++) {
  13462. this.soundTracks[i].switchPanningModelToEqualPower();
  13463. }
  13464. };
  13465. Scene.prototype.enableDepthRenderer = function () {
  13466. if (this._depthRenderer) {
  13467. return this._depthRenderer;
  13468. }
  13469. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13470. return this._depthRenderer;
  13471. };
  13472. Scene.prototype.disableDepthRenderer = function () {
  13473. if (!this._depthRenderer) {
  13474. return;
  13475. }
  13476. this._depthRenderer.dispose();
  13477. this._depthRenderer = null;
  13478. };
  13479. Scene.prototype.dispose = function () {
  13480. this.beforeRender = null;
  13481. this.afterRender = null;
  13482. this.skeletons = [];
  13483. this._boundingBoxRenderer.dispose();
  13484. if (this._depthRenderer) {
  13485. this._depthRenderer.dispose();
  13486. }
  13487. // Debug layer
  13488. this.debugLayer.hide();
  13489. // Events
  13490. if (this.onDispose) {
  13491. this.onDispose();
  13492. }
  13493. this._onBeforeRenderCallbacks = [];
  13494. this._onAfterRenderCallbacks = [];
  13495. this.detachControl();
  13496. // Release sounds & sounds tracks
  13497. if (BABYLON.AudioEngine) {
  13498. this.disposeSounds();
  13499. }
  13500. // Detach cameras
  13501. var canvas = this._engine.getRenderingCanvas();
  13502. var index;
  13503. for (index = 0; index < this.cameras.length; index++) {
  13504. this.cameras[index].detachControl(canvas);
  13505. }
  13506. // Release lights
  13507. while (this.lights.length) {
  13508. this.lights[0].dispose();
  13509. }
  13510. // Release meshes
  13511. while (this.meshes.length) {
  13512. this.meshes[0].dispose(true);
  13513. }
  13514. // Release cameras
  13515. while (this.cameras.length) {
  13516. this.cameras[0].dispose();
  13517. }
  13518. // Release materials
  13519. while (this.materials.length) {
  13520. this.materials[0].dispose();
  13521. }
  13522. // Release particles
  13523. while (this.particleSystems.length) {
  13524. this.particleSystems[0].dispose();
  13525. }
  13526. // Release sprites
  13527. while (this.spriteManagers.length) {
  13528. this.spriteManagers[0].dispose();
  13529. }
  13530. // Release layers
  13531. while (this.layers.length) {
  13532. this.layers[0].dispose();
  13533. }
  13534. // Release textures
  13535. while (this.textures.length) {
  13536. this.textures[0].dispose();
  13537. }
  13538. // Post-processes
  13539. this.postProcessManager.dispose();
  13540. // Physics
  13541. if (this._physicsEngine) {
  13542. this.disablePhysicsEngine();
  13543. }
  13544. // Remove from engine
  13545. index = this._engine.scenes.indexOf(this);
  13546. if (index > -1) {
  13547. this._engine.scenes.splice(index, 1);
  13548. }
  13549. this._engine.wipeCaches();
  13550. };
  13551. // Release sounds & sounds tracks
  13552. Scene.prototype.disposeSounds = function () {
  13553. this.mainSoundTrack.dispose();
  13554. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13555. this.soundTracks[scIndex].dispose();
  13556. }
  13557. };
  13558. // Octrees
  13559. Scene.prototype.getWorldExtends = function () {
  13560. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13561. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13562. for (var index = 0; index < this.meshes.length; index++) {
  13563. var mesh = this.meshes[index];
  13564. mesh.computeWorldMatrix(true);
  13565. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13566. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13567. BABYLON.Tools.CheckExtends(minBox, min, max);
  13568. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13569. }
  13570. return {
  13571. min: min,
  13572. max: max
  13573. };
  13574. };
  13575. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13576. if (maxCapacity === void 0) { maxCapacity = 64; }
  13577. if (maxDepth === void 0) { maxDepth = 2; }
  13578. if (!this._selectionOctree) {
  13579. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13580. }
  13581. var worldExtends = this.getWorldExtends();
  13582. // Update octree
  13583. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13584. return this._selectionOctree;
  13585. };
  13586. // Picking
  13587. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13588. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13589. var engine = this._engine;
  13590. if (!camera) {
  13591. if (!this.activeCamera)
  13592. throw new Error("Active camera not set");
  13593. camera = this.activeCamera;
  13594. }
  13595. var cameraViewport = camera.viewport;
  13596. var viewport = cameraViewport.toGlobal(engine);
  13597. // Moving coordinates to local viewport world
  13598. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13599. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13600. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13601. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13602. };
  13603. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13604. var engine = this._engine;
  13605. if (!camera) {
  13606. if (!this.activeCamera)
  13607. throw new Error("Active camera not set");
  13608. camera = this.activeCamera;
  13609. }
  13610. var cameraViewport = camera.viewport;
  13611. var viewport = cameraViewport.toGlobal(engine);
  13612. var identity = BABYLON.Matrix.Identity();
  13613. // Moving coordinates to local viewport world
  13614. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13615. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13616. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13617. };
  13618. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13619. var pickingInfo = null;
  13620. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13621. var mesh = this.meshes[meshIndex];
  13622. if (predicate) {
  13623. if (!predicate(mesh)) {
  13624. continue;
  13625. }
  13626. }
  13627. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13628. continue;
  13629. }
  13630. var world = mesh.getWorldMatrix();
  13631. var ray = rayFunction(world);
  13632. var result = mesh.intersects(ray, fastCheck);
  13633. if (!result || !result.hit)
  13634. continue;
  13635. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13636. continue;
  13637. pickingInfo = result;
  13638. if (fastCheck) {
  13639. break;
  13640. }
  13641. }
  13642. return pickingInfo || new BABYLON.PickingInfo();
  13643. };
  13644. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13645. var pickingInfo = null;
  13646. camera = camera || this.activeCamera;
  13647. if (this.spriteManagers.length > 0) {
  13648. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13649. var spriteManager = this.spriteManagers[spriteIndex];
  13650. if (!spriteManager.isPickable) {
  13651. continue;
  13652. }
  13653. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13654. if (!result || !result.hit)
  13655. continue;
  13656. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13657. continue;
  13658. pickingInfo = result;
  13659. if (fastCheck) {
  13660. break;
  13661. }
  13662. }
  13663. }
  13664. return pickingInfo || new BABYLON.PickingInfo();
  13665. };
  13666. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13667. var _this = this;
  13668. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13669. /// <param name="x">X position on screen</param>
  13670. /// <param name="y">Y position on screen</param>
  13671. /// <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>
  13672. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13673. /// <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>
  13674. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13675. };
  13676. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13677. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13678. /// <param name="x">X position on screen</param>
  13679. /// <param name="y">Y position on screen</param>
  13680. /// <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>
  13681. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13682. /// <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>
  13683. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13684. };
  13685. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13686. var _this = this;
  13687. return this._internalPick(function (world) {
  13688. if (!_this._pickWithRayInverseMatrix) {
  13689. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13690. }
  13691. world.invertToRef(_this._pickWithRayInverseMatrix);
  13692. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13693. }, predicate, fastCheck);
  13694. };
  13695. Scene.prototype.setPointerOverMesh = function (mesh) {
  13696. if (this._pointerOverMesh === mesh) {
  13697. return;
  13698. }
  13699. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13700. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13701. }
  13702. this._pointerOverMesh = mesh;
  13703. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13704. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13705. }
  13706. };
  13707. Scene.prototype.getPointerOverMesh = function () {
  13708. return this._pointerOverMesh;
  13709. };
  13710. // Physics
  13711. Scene.prototype.getPhysicsEngine = function () {
  13712. return this._physicsEngine;
  13713. };
  13714. /**
  13715. * Enables physics to the current scene
  13716. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13717. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13718. * @return {boolean} was the physics engine initialized
  13719. */
  13720. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13721. if (this._physicsEngine) {
  13722. return true;
  13723. }
  13724. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13725. if (!this._physicsEngine.isSupported()) {
  13726. this._physicsEngine = null;
  13727. return false;
  13728. }
  13729. this._physicsEngine._initialize(gravity);
  13730. return true;
  13731. };
  13732. Scene.prototype.disablePhysicsEngine = function () {
  13733. if (!this._physicsEngine) {
  13734. return;
  13735. }
  13736. this._physicsEngine.dispose();
  13737. this._physicsEngine = undefined;
  13738. };
  13739. Scene.prototype.isPhysicsEnabled = function () {
  13740. return this._physicsEngine !== undefined;
  13741. };
  13742. /**
  13743. * Sets the gravity of the physics engine (and NOT of the scene)
  13744. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13745. */
  13746. Scene.prototype.setGravity = function (gravity) {
  13747. if (!this._physicsEngine) {
  13748. return;
  13749. }
  13750. this._physicsEngine._setGravity(gravity);
  13751. };
  13752. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13753. if (parts.parts) {
  13754. options = parts;
  13755. parts = parts.parts;
  13756. }
  13757. if (!this._physicsEngine) {
  13758. return null;
  13759. }
  13760. for (var index = 0; index < parts.length; index++) {
  13761. var mesh = parts[index].mesh;
  13762. mesh._physicImpostor = parts[index].impostor;
  13763. mesh._physicsMass = options.mass / parts.length;
  13764. mesh._physicsFriction = options.friction;
  13765. mesh._physicRestitution = options.restitution;
  13766. }
  13767. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13768. };
  13769. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13770. for (var index = 0; index < compound.parts.length; index++) {
  13771. var mesh = compound.parts[index].mesh;
  13772. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13773. this._physicsEngine._unregisterMesh(mesh);
  13774. }
  13775. };
  13776. // Misc.
  13777. Scene.prototype.createDefaultCameraOrLight = function () {
  13778. // Light
  13779. if (this.lights.length === 0) {
  13780. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13781. }
  13782. // Camera
  13783. if (!this.activeCamera) {
  13784. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13785. // Compute position
  13786. var worldExtends = this.getWorldExtends();
  13787. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13788. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13789. camera.setTarget(worldCenter);
  13790. this.activeCamera = camera;
  13791. }
  13792. };
  13793. // Tags
  13794. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13795. if (tagsQuery === undefined) {
  13796. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13797. return list;
  13798. }
  13799. var listByTags = [];
  13800. forEach = forEach || (function (item) { return; });
  13801. for (var i in list) {
  13802. var item = list[i];
  13803. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13804. listByTags.push(item);
  13805. forEach(item);
  13806. }
  13807. }
  13808. return listByTags;
  13809. };
  13810. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13811. return this._getByTags(this.meshes, tagsQuery, forEach);
  13812. };
  13813. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13814. return this._getByTags(this.cameras, tagsQuery, forEach);
  13815. };
  13816. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13817. return this._getByTags(this.lights, tagsQuery, forEach);
  13818. };
  13819. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13820. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13821. };
  13822. // Statics
  13823. Scene._FOGMODE_NONE = 0;
  13824. Scene._FOGMODE_EXP = 1;
  13825. Scene._FOGMODE_EXP2 = 2;
  13826. Scene._FOGMODE_LINEAR = 3;
  13827. Scene.MinDeltaTime = 1.0;
  13828. Scene.MaxDeltaTime = 1000.0;
  13829. return Scene;
  13830. })();
  13831. BABYLON.Scene = Scene;
  13832. })(BABYLON || (BABYLON = {}));
  13833. var BABYLON;
  13834. (function (BABYLON) {
  13835. var VertexBuffer = (function () {
  13836. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13837. if (engine instanceof BABYLON.Mesh) {
  13838. this._engine = engine.getScene().getEngine();
  13839. }
  13840. else {
  13841. this._engine = engine;
  13842. }
  13843. this._updatable = updatable;
  13844. this._data = data;
  13845. if (!postponeInternalCreation) {
  13846. this.create();
  13847. }
  13848. this._kind = kind;
  13849. if (stride) {
  13850. this._strideSize = stride;
  13851. return;
  13852. }
  13853. // Deduce stride from kind
  13854. switch (kind) {
  13855. case VertexBuffer.PositionKind:
  13856. this._strideSize = 3;
  13857. break;
  13858. case VertexBuffer.NormalKind:
  13859. this._strideSize = 3;
  13860. break;
  13861. case VertexBuffer.UVKind:
  13862. case VertexBuffer.UV2Kind:
  13863. case VertexBuffer.UV3Kind:
  13864. case VertexBuffer.UV4Kind:
  13865. case VertexBuffer.UV5Kind:
  13866. case VertexBuffer.UV6Kind:
  13867. this._strideSize = 2;
  13868. break;
  13869. case VertexBuffer.ColorKind:
  13870. this._strideSize = 4;
  13871. break;
  13872. case VertexBuffer.MatricesIndicesKind:
  13873. case VertexBuffer.MatricesIndicesExtraKind:
  13874. this._strideSize = 4;
  13875. break;
  13876. case VertexBuffer.MatricesWeightsKind:
  13877. case VertexBuffer.MatricesWeightsExtraKind:
  13878. this._strideSize = 4;
  13879. break;
  13880. }
  13881. }
  13882. // Properties
  13883. VertexBuffer.prototype.isUpdatable = function () {
  13884. return this._updatable;
  13885. };
  13886. VertexBuffer.prototype.getData = function () {
  13887. return this._data;
  13888. };
  13889. VertexBuffer.prototype.getBuffer = function () {
  13890. return this._buffer;
  13891. };
  13892. VertexBuffer.prototype.getStrideSize = function () {
  13893. return this._strideSize;
  13894. };
  13895. // Methods
  13896. VertexBuffer.prototype.create = function (data) {
  13897. if (!data && this._buffer) {
  13898. return; // nothing to do
  13899. }
  13900. data = data || this._data;
  13901. if (!this._buffer) {
  13902. if (this._updatable) {
  13903. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13904. }
  13905. else {
  13906. this._buffer = this._engine.createVertexBuffer(data);
  13907. }
  13908. }
  13909. if (this._updatable) {
  13910. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13911. this._data = data;
  13912. }
  13913. };
  13914. VertexBuffer.prototype.update = function (data) {
  13915. this.create(data);
  13916. };
  13917. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13918. if (!this._buffer) {
  13919. return;
  13920. }
  13921. if (this._updatable) {
  13922. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13923. this._data = null;
  13924. }
  13925. };
  13926. VertexBuffer.prototype.dispose = function () {
  13927. if (!this._buffer) {
  13928. return;
  13929. }
  13930. if (this._engine._releaseBuffer(this._buffer)) {
  13931. this._buffer = null;
  13932. }
  13933. };
  13934. Object.defineProperty(VertexBuffer, "PositionKind", {
  13935. get: function () {
  13936. return VertexBuffer._PositionKind;
  13937. },
  13938. enumerable: true,
  13939. configurable: true
  13940. });
  13941. Object.defineProperty(VertexBuffer, "NormalKind", {
  13942. get: function () {
  13943. return VertexBuffer._NormalKind;
  13944. },
  13945. enumerable: true,
  13946. configurable: true
  13947. });
  13948. Object.defineProperty(VertexBuffer, "UVKind", {
  13949. get: function () {
  13950. return VertexBuffer._UVKind;
  13951. },
  13952. enumerable: true,
  13953. configurable: true
  13954. });
  13955. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13956. get: function () {
  13957. return VertexBuffer._UV2Kind;
  13958. },
  13959. enumerable: true,
  13960. configurable: true
  13961. });
  13962. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13963. get: function () {
  13964. return VertexBuffer._UV3Kind;
  13965. },
  13966. enumerable: true,
  13967. configurable: true
  13968. });
  13969. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13970. get: function () {
  13971. return VertexBuffer._UV4Kind;
  13972. },
  13973. enumerable: true,
  13974. configurable: true
  13975. });
  13976. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13977. get: function () {
  13978. return VertexBuffer._UV5Kind;
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13984. get: function () {
  13985. return VertexBuffer._UV6Kind;
  13986. },
  13987. enumerable: true,
  13988. configurable: true
  13989. });
  13990. Object.defineProperty(VertexBuffer, "ColorKind", {
  13991. get: function () {
  13992. return VertexBuffer._ColorKind;
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13998. get: function () {
  13999. return VertexBuffer._MatricesIndicesKind;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14005. get: function () {
  14006. return VertexBuffer._MatricesWeightsKind;
  14007. },
  14008. enumerable: true,
  14009. configurable: true
  14010. });
  14011. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14012. get: function () {
  14013. return VertexBuffer._MatricesIndicesExtraKind;
  14014. },
  14015. enumerable: true,
  14016. configurable: true
  14017. });
  14018. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14019. get: function () {
  14020. return VertexBuffer._MatricesWeightsExtraKind;
  14021. },
  14022. enumerable: true,
  14023. configurable: true
  14024. });
  14025. // Enums
  14026. VertexBuffer._PositionKind = "position";
  14027. VertexBuffer._NormalKind = "normal";
  14028. VertexBuffer._UVKind = "uv";
  14029. VertexBuffer._UV2Kind = "uv2";
  14030. VertexBuffer._UV3Kind = "uv3";
  14031. VertexBuffer._UV4Kind = "uv4";
  14032. VertexBuffer._UV5Kind = "uv5";
  14033. VertexBuffer._UV6Kind = "uv6";
  14034. VertexBuffer._ColorKind = "color";
  14035. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14036. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14037. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14038. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14039. return VertexBuffer;
  14040. })();
  14041. BABYLON.VertexBuffer = VertexBuffer;
  14042. })(BABYLON || (BABYLON = {}));
  14043. var BABYLON;
  14044. (function (BABYLON) {
  14045. /**
  14046. * Creates an instance based on a source mesh.
  14047. */
  14048. var InstancedMesh = (function (_super) {
  14049. __extends(InstancedMesh, _super);
  14050. function InstancedMesh(name, source) {
  14051. _super.call(this, name, source.getScene());
  14052. source.instances.push(this);
  14053. this._sourceMesh = source;
  14054. this.position.copyFrom(source.position);
  14055. this.rotation.copyFrom(source.rotation);
  14056. this.scaling.copyFrom(source.scaling);
  14057. if (source.rotationQuaternion) {
  14058. this.rotationQuaternion = source.rotationQuaternion.clone();
  14059. }
  14060. this.infiniteDistance = source.infiniteDistance;
  14061. this.setPivotMatrix(source.getPivotMatrix());
  14062. this.refreshBoundingInfo();
  14063. this._syncSubMeshes();
  14064. }
  14065. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14066. // Methods
  14067. get: function () {
  14068. return this._sourceMesh.receiveShadows;
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Object.defineProperty(InstancedMesh.prototype, "material", {
  14074. get: function () {
  14075. return this._sourceMesh.material;
  14076. },
  14077. enumerable: true,
  14078. configurable: true
  14079. });
  14080. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14081. get: function () {
  14082. return this._sourceMesh.visibility;
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14088. get: function () {
  14089. return this._sourceMesh.skeleton;
  14090. },
  14091. enumerable: true,
  14092. configurable: true
  14093. });
  14094. InstancedMesh.prototype.getTotalVertices = function () {
  14095. return this._sourceMesh.getTotalVertices();
  14096. };
  14097. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14098. get: function () {
  14099. return this._sourceMesh;
  14100. },
  14101. enumerable: true,
  14102. configurable: true
  14103. });
  14104. InstancedMesh.prototype.getVerticesData = function (kind) {
  14105. return this._sourceMesh.getVerticesData(kind);
  14106. };
  14107. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14108. return this._sourceMesh.isVerticesDataPresent(kind);
  14109. };
  14110. InstancedMesh.prototype.getIndices = function () {
  14111. return this._sourceMesh.getIndices();
  14112. };
  14113. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14114. get: function () {
  14115. return this._sourceMesh._positions;
  14116. },
  14117. enumerable: true,
  14118. configurable: true
  14119. });
  14120. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14121. var meshBB = this._sourceMesh.getBoundingInfo();
  14122. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14123. this._updateBoundingInfo();
  14124. };
  14125. InstancedMesh.prototype._preActivate = function () {
  14126. if (this._currentLOD) {
  14127. this._currentLOD._preActivate();
  14128. }
  14129. };
  14130. InstancedMesh.prototype._activate = function (renderId) {
  14131. if (this._currentLOD) {
  14132. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14133. }
  14134. };
  14135. InstancedMesh.prototype.getLOD = function (camera) {
  14136. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14137. if (this._currentLOD === this.sourceMesh) {
  14138. return this;
  14139. }
  14140. return this._currentLOD;
  14141. };
  14142. InstancedMesh.prototype._syncSubMeshes = function () {
  14143. this.releaseSubMeshes();
  14144. if (this._sourceMesh.subMeshes) {
  14145. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14146. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14147. }
  14148. }
  14149. };
  14150. InstancedMesh.prototype._generatePointsArray = function () {
  14151. return this._sourceMesh._generatePointsArray();
  14152. };
  14153. // Clone
  14154. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14155. var result = this._sourceMesh.createInstance(name);
  14156. // Deep copy
  14157. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14158. // Bounding info
  14159. this.refreshBoundingInfo();
  14160. // Parent
  14161. if (newParent) {
  14162. result.parent = newParent;
  14163. }
  14164. if (!doNotCloneChildren) {
  14165. // Children
  14166. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14167. var mesh = this.getScene().meshes[index];
  14168. if (mesh.parent === this) {
  14169. mesh.clone(mesh.name, result);
  14170. }
  14171. }
  14172. }
  14173. result.computeWorldMatrix(true);
  14174. return result;
  14175. };
  14176. // Dispoe
  14177. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14178. // Remove from mesh
  14179. var index = this._sourceMesh.instances.indexOf(this);
  14180. this._sourceMesh.instances.splice(index, 1);
  14181. _super.prototype.dispose.call(this, doNotRecurse);
  14182. };
  14183. return InstancedMesh;
  14184. })(BABYLON.AbstractMesh);
  14185. BABYLON.InstancedMesh = InstancedMesh;
  14186. })(BABYLON || (BABYLON = {}));
  14187. var BABYLON;
  14188. (function (BABYLON) {
  14189. var _InstancesBatch = (function () {
  14190. function _InstancesBatch() {
  14191. this.mustReturn = false;
  14192. this.visibleInstances = new Array();
  14193. this.renderSelf = new Array();
  14194. }
  14195. return _InstancesBatch;
  14196. })();
  14197. BABYLON._InstancesBatch = _InstancesBatch;
  14198. var Mesh = (function (_super) {
  14199. __extends(Mesh, _super);
  14200. /**
  14201. * @constructor
  14202. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14203. * @param {Scene} scene - The scene to add this mesh to.
  14204. * @param {Node} parent - The parent of this mesh, if it has one
  14205. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14206. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14207. * When false, achieved by calling a clone(), also passing False.
  14208. * This will make creation of children, recursive.
  14209. */
  14210. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14211. if (parent === void 0) { parent = null; }
  14212. _super.call(this, name, scene);
  14213. // Members
  14214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14215. this.instances = new Array();
  14216. this._LODLevels = new Array();
  14217. this._onBeforeRenderCallbacks = new Array();
  14218. this._onAfterRenderCallbacks = new Array();
  14219. this._visibleInstances = {};
  14220. this._renderIdForInstances = new Array();
  14221. this._batchCache = new _InstancesBatch();
  14222. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14223. this._sideOrientation = Mesh._DEFAULTSIDE;
  14224. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14225. if (source) {
  14226. // Geometry
  14227. if (source._geometry) {
  14228. source._geometry.applyToMesh(this);
  14229. }
  14230. // Deep copy
  14231. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14232. this.id = name + "." + source.id;
  14233. // Material
  14234. this.material = source.material;
  14235. var index;
  14236. if (!doNotCloneChildren) {
  14237. // Children
  14238. for (index = 0; index < scene.meshes.length; index++) {
  14239. var mesh = scene.meshes[index];
  14240. if (mesh.parent === source) {
  14241. // doNotCloneChildren is always going to be False
  14242. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14243. }
  14244. }
  14245. }
  14246. // Particles
  14247. for (index = 0; index < scene.particleSystems.length; index++) {
  14248. var system = scene.particleSystems[index];
  14249. if (system.emitter === source) {
  14250. system.clone(system.name, this);
  14251. }
  14252. }
  14253. this.computeWorldMatrix(true);
  14254. }
  14255. // Parent
  14256. if (parent !== null) {
  14257. this.parent = parent;
  14258. }
  14259. }
  14260. Object.defineProperty(Mesh, "FRONTSIDE", {
  14261. get: function () {
  14262. return Mesh._FRONTSIDE;
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. Object.defineProperty(Mesh, "BACKSIDE", {
  14268. get: function () {
  14269. return Mesh._BACKSIDE;
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14275. get: function () {
  14276. return Mesh._DOUBLESIDE;
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14282. get: function () {
  14283. return Mesh._DEFAULTSIDE;
  14284. },
  14285. enumerable: true,
  14286. configurable: true
  14287. });
  14288. Object.defineProperty(Mesh, "NO_CAP", {
  14289. get: function () {
  14290. return Mesh._NO_CAP;
  14291. },
  14292. enumerable: true,
  14293. configurable: true
  14294. });
  14295. Object.defineProperty(Mesh, "CAP_START", {
  14296. get: function () {
  14297. return Mesh._CAP_START;
  14298. },
  14299. enumerable: true,
  14300. configurable: true
  14301. });
  14302. Object.defineProperty(Mesh, "CAP_END", {
  14303. get: function () {
  14304. return Mesh._CAP_END;
  14305. },
  14306. enumerable: true,
  14307. configurable: true
  14308. });
  14309. Object.defineProperty(Mesh, "CAP_ALL", {
  14310. get: function () {
  14311. return Mesh._CAP_ALL;
  14312. },
  14313. enumerable: true,
  14314. configurable: true
  14315. });
  14316. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14317. // Methods
  14318. get: function () {
  14319. return this._LODLevels.length > 0;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Mesh.prototype._sortLODLevels = function () {
  14325. this._LODLevels.sort(function (a, b) {
  14326. if (a.distance < b.distance) {
  14327. return 1;
  14328. }
  14329. if (a.distance > b.distance) {
  14330. return -1;
  14331. }
  14332. return 0;
  14333. });
  14334. };
  14335. /**
  14336. * Add a mesh as LOD level triggered at the given distance.
  14337. * @param {number} distance - the distance from the center of the object to show this level
  14338. * @param {Mesh} mesh - the mesh to be added as LOD level
  14339. * @return {Mesh} this mesh (for chaining)
  14340. */
  14341. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14342. if (mesh && mesh._masterMesh) {
  14343. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14344. return this;
  14345. }
  14346. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14347. this._LODLevels.push(level);
  14348. if (mesh) {
  14349. mesh._masterMesh = this;
  14350. }
  14351. this._sortLODLevels();
  14352. return this;
  14353. };
  14354. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14355. for (var index = 0; index < this._LODLevels.length; index++) {
  14356. var level = this._LODLevels[index];
  14357. if (level.distance === distance) {
  14358. return level.mesh;
  14359. }
  14360. }
  14361. return null;
  14362. };
  14363. /**
  14364. * Remove a mesh from the LOD array
  14365. * @param {Mesh} mesh - the mesh to be removed.
  14366. * @return {Mesh} this mesh (for chaining)
  14367. */
  14368. Mesh.prototype.removeLODLevel = function (mesh) {
  14369. for (var index = 0; index < this._LODLevels.length; index++) {
  14370. if (this._LODLevels[index].mesh === mesh) {
  14371. this._LODLevels.splice(index, 1);
  14372. if (mesh) {
  14373. mesh._masterMesh = null;
  14374. }
  14375. }
  14376. }
  14377. this._sortLODLevels();
  14378. return this;
  14379. };
  14380. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14381. if (!this._LODLevels || this._LODLevels.length === 0) {
  14382. return this;
  14383. }
  14384. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14385. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14386. if (this.onLODLevelSelection) {
  14387. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14388. }
  14389. return this;
  14390. }
  14391. for (var index = 0; index < this._LODLevels.length; index++) {
  14392. var level = this._LODLevels[index];
  14393. if (level.distance < distanceToCamera) {
  14394. if (level.mesh) {
  14395. level.mesh._preActivate();
  14396. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14397. }
  14398. if (this.onLODLevelSelection) {
  14399. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14400. }
  14401. return level.mesh;
  14402. }
  14403. }
  14404. if (this.onLODLevelSelection) {
  14405. this.onLODLevelSelection(distanceToCamera, this, this);
  14406. }
  14407. return this;
  14408. };
  14409. Object.defineProperty(Mesh.prototype, "geometry", {
  14410. get: function () {
  14411. return this._geometry;
  14412. },
  14413. enumerable: true,
  14414. configurable: true
  14415. });
  14416. Mesh.prototype.getTotalVertices = function () {
  14417. if (!this._geometry) {
  14418. return 0;
  14419. }
  14420. return this._geometry.getTotalVertices();
  14421. };
  14422. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14423. if (!this._geometry) {
  14424. return null;
  14425. }
  14426. return this._geometry.getVerticesData(kind, copyWhenShared);
  14427. };
  14428. Mesh.prototype.getVertexBuffer = function (kind) {
  14429. if (!this._geometry) {
  14430. return undefined;
  14431. }
  14432. return this._geometry.getVertexBuffer(kind);
  14433. };
  14434. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14435. if (!this._geometry) {
  14436. if (this._delayInfo) {
  14437. return this._delayInfo.indexOf(kind) !== -1;
  14438. }
  14439. return false;
  14440. }
  14441. return this._geometry.isVerticesDataPresent(kind);
  14442. };
  14443. Mesh.prototype.getVerticesDataKinds = function () {
  14444. if (!this._geometry) {
  14445. var result = [];
  14446. if (this._delayInfo) {
  14447. for (var kind in this._delayInfo) {
  14448. result.push(kind);
  14449. }
  14450. }
  14451. return result;
  14452. }
  14453. return this._geometry.getVerticesDataKinds();
  14454. };
  14455. Mesh.prototype.getTotalIndices = function () {
  14456. if (!this._geometry) {
  14457. return 0;
  14458. }
  14459. return this._geometry.getTotalIndices();
  14460. };
  14461. Mesh.prototype.getIndices = function (copyWhenShared) {
  14462. if (!this._geometry) {
  14463. return [];
  14464. }
  14465. return this._geometry.getIndices(copyWhenShared);
  14466. };
  14467. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14468. get: function () {
  14469. return this._masterMesh !== null && this._masterMesh !== undefined;
  14470. },
  14471. enumerable: true,
  14472. configurable: true
  14473. });
  14474. Mesh.prototype.isReady = function () {
  14475. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14476. return false;
  14477. }
  14478. return _super.prototype.isReady.call(this);
  14479. };
  14480. Mesh.prototype.isDisposed = function () {
  14481. return this._isDisposed;
  14482. };
  14483. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14484. get: function () {
  14485. return this._sideOrientation;
  14486. },
  14487. set: function (sideO) {
  14488. this._sideOrientation = sideO;
  14489. },
  14490. enumerable: true,
  14491. configurable: true
  14492. });
  14493. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14494. get: function () {
  14495. return this._areNormalsFrozen;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14501. Mesh.prototype.freezeNormals = function () {
  14502. this._areNormalsFrozen = true;
  14503. };
  14504. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14505. Mesh.prototype.unfreezeNormals = function () {
  14506. this._areNormalsFrozen = false;
  14507. };
  14508. // Methods
  14509. Mesh.prototype._preActivate = function () {
  14510. var sceneRenderId = this.getScene().getRenderId();
  14511. if (this._preActivateId === sceneRenderId) {
  14512. return;
  14513. }
  14514. this._preActivateId = sceneRenderId;
  14515. this._visibleInstances = null;
  14516. };
  14517. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14518. if (!this._visibleInstances) {
  14519. this._visibleInstances = {};
  14520. this._visibleInstances.defaultRenderId = renderId;
  14521. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14522. }
  14523. if (!this._visibleInstances[renderId]) {
  14524. this._visibleInstances[renderId] = new Array();
  14525. }
  14526. this._visibleInstances[renderId].push(instance);
  14527. };
  14528. Mesh.prototype.refreshBoundingInfo = function () {
  14529. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14530. if (data) {
  14531. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14532. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14533. }
  14534. if (this.subMeshes) {
  14535. for (var index = 0; index < this.subMeshes.length; index++) {
  14536. this.subMeshes[index].refreshBoundingInfo();
  14537. }
  14538. }
  14539. this._updateBoundingInfo();
  14540. };
  14541. Mesh.prototype._createGlobalSubMesh = function () {
  14542. var totalVertices = this.getTotalVertices();
  14543. if (!totalVertices || !this.getIndices()) {
  14544. return null;
  14545. }
  14546. this.releaseSubMeshes();
  14547. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14548. };
  14549. Mesh.prototype.subdivide = function (count) {
  14550. if (count < 1) {
  14551. return;
  14552. }
  14553. var totalIndices = this.getTotalIndices();
  14554. var subdivisionSize = (totalIndices / count) | 0;
  14555. var offset = 0;
  14556. // Ensure that subdivisionSize is a multiple of 3
  14557. while (subdivisionSize % 3 !== 0) {
  14558. subdivisionSize++;
  14559. }
  14560. this.releaseSubMeshes();
  14561. for (var index = 0; index < count; index++) {
  14562. if (offset >= totalIndices) {
  14563. break;
  14564. }
  14565. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14566. offset += subdivisionSize;
  14567. }
  14568. this.synchronizeInstances();
  14569. };
  14570. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14571. if (!this._geometry) {
  14572. var vertexData = new BABYLON.VertexData();
  14573. vertexData.set(data, kind);
  14574. var scene = this.getScene();
  14575. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14576. }
  14577. else {
  14578. this._geometry.setVerticesData(kind, data, updatable, stride);
  14579. }
  14580. };
  14581. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14582. if (!this._geometry) {
  14583. return;
  14584. }
  14585. if (!makeItUnique) {
  14586. this._geometry.updateVerticesData(kind, data, updateExtends);
  14587. }
  14588. else {
  14589. this.makeGeometryUnique();
  14590. this.updateVerticesData(kind, data, updateExtends, false);
  14591. }
  14592. };
  14593. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14594. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14595. if (!this._geometry) {
  14596. return;
  14597. }
  14598. if (!makeItUnique) {
  14599. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14600. }
  14601. else {
  14602. this.makeGeometryUnique();
  14603. this.updateVerticesDataDirectly(kind, data, offset, false);
  14604. }
  14605. };
  14606. // Mesh positions update function :
  14607. // updates the mesh positions according to the positionFunction returned values.
  14608. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14609. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14610. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14611. if (computeNormals === void 0) { computeNormals = true; }
  14612. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14613. positionFunction(positions);
  14614. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14615. if (computeNormals) {
  14616. var indices = this.getIndices();
  14617. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14618. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14619. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14620. }
  14621. };
  14622. Mesh.prototype.makeGeometryUnique = function () {
  14623. if (!this._geometry) {
  14624. return;
  14625. }
  14626. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14627. geometry.applyToMesh(this);
  14628. };
  14629. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14630. if (!this._geometry) {
  14631. var vertexData = new BABYLON.VertexData();
  14632. vertexData.indices = indices;
  14633. var scene = this.getScene();
  14634. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14635. }
  14636. else {
  14637. this._geometry.setIndices(indices, totalVertices);
  14638. }
  14639. };
  14640. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14641. var engine = this.getScene().getEngine();
  14642. // Wireframe
  14643. var indexToBind;
  14644. switch (fillMode) {
  14645. case BABYLON.Material.PointFillMode:
  14646. indexToBind = null;
  14647. break;
  14648. case BABYLON.Material.WireFrameFillMode:
  14649. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14650. break;
  14651. default:
  14652. case BABYLON.Material.TriangleFillMode:
  14653. indexToBind = this._geometry.getIndexBuffer();
  14654. break;
  14655. }
  14656. // VBOs
  14657. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14658. };
  14659. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14660. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14661. return;
  14662. }
  14663. var engine = this.getScene().getEngine();
  14664. // Draw order
  14665. switch (fillMode) {
  14666. case BABYLON.Material.PointFillMode:
  14667. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14668. break;
  14669. case BABYLON.Material.WireFrameFillMode:
  14670. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14671. break;
  14672. default:
  14673. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14674. }
  14675. };
  14676. Mesh.prototype.registerBeforeRender = function (func) {
  14677. this._onBeforeRenderCallbacks.push(func);
  14678. };
  14679. Mesh.prototype.unregisterBeforeRender = function (func) {
  14680. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14681. if (index > -1) {
  14682. this._onBeforeRenderCallbacks.splice(index, 1);
  14683. }
  14684. };
  14685. Mesh.prototype.registerAfterRender = function (func) {
  14686. this._onAfterRenderCallbacks.push(func);
  14687. };
  14688. Mesh.prototype.unregisterAfterRender = function (func) {
  14689. var index = this._onAfterRenderCallbacks.indexOf(func);
  14690. if (index > -1) {
  14691. this._onAfterRenderCallbacks.splice(index, 1);
  14692. }
  14693. };
  14694. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14695. var scene = this.getScene();
  14696. this._batchCache.mustReturn = false;
  14697. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14698. this._batchCache.visibleInstances[subMeshId] = null;
  14699. if (this._visibleInstances) {
  14700. var currentRenderId = scene.getRenderId();
  14701. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14702. var selfRenderId = this._renderId;
  14703. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14704. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14705. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14706. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14707. }
  14708. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14709. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14710. this._batchCache.mustReturn = true;
  14711. return this._batchCache;
  14712. }
  14713. if (currentRenderId !== selfRenderId) {
  14714. this._batchCache.renderSelf[subMeshId] = false;
  14715. }
  14716. }
  14717. this._renderIdForInstances[subMeshId] = currentRenderId;
  14718. }
  14719. return this._batchCache;
  14720. };
  14721. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14722. var visibleInstances = batch.visibleInstances[subMesh._id];
  14723. var matricesCount = visibleInstances.length + 1;
  14724. var bufferSize = matricesCount * 16 * 4;
  14725. while (this._instancesBufferSize < bufferSize) {
  14726. this._instancesBufferSize *= 2;
  14727. }
  14728. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14729. if (this._worldMatricesInstancesBuffer) {
  14730. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14731. }
  14732. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14733. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14734. }
  14735. var offset = 0;
  14736. var instancesCount = 0;
  14737. var world = this.getWorldMatrix();
  14738. if (batch.renderSelf[subMesh._id]) {
  14739. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14740. offset += 16;
  14741. instancesCount++;
  14742. }
  14743. if (visibleInstances) {
  14744. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14745. var instance = visibleInstances[instanceIndex];
  14746. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14747. offset += 16;
  14748. instancesCount++;
  14749. }
  14750. }
  14751. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14752. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14753. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14754. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14755. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14756. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14757. this._draw(subMesh, fillMode, instancesCount);
  14758. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14759. };
  14760. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14761. var scene = this.getScene();
  14762. var engine = scene.getEngine();
  14763. if (hardwareInstancedRendering) {
  14764. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14765. }
  14766. else {
  14767. if (batch.renderSelf[subMesh._id]) {
  14768. // Draw
  14769. if (onBeforeDraw) {
  14770. onBeforeDraw(false, this.getWorldMatrix());
  14771. }
  14772. this._draw(subMesh, fillMode);
  14773. }
  14774. if (batch.visibleInstances[subMesh._id]) {
  14775. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14776. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14777. // World
  14778. var world = instance.getWorldMatrix();
  14779. if (onBeforeDraw) {
  14780. onBeforeDraw(true, world);
  14781. }
  14782. // Draw
  14783. this._draw(subMesh, fillMode);
  14784. }
  14785. }
  14786. }
  14787. };
  14788. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14789. var scene = this.getScene();
  14790. // Managing instances
  14791. var batch = this._getInstancesRenderList(subMesh._id);
  14792. if (batch.mustReturn) {
  14793. return;
  14794. }
  14795. // Checking geometry state
  14796. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14797. return;
  14798. }
  14799. var callbackIndex;
  14800. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14801. this._onBeforeRenderCallbacks[callbackIndex](this);
  14802. }
  14803. var engine = scene.getEngine();
  14804. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14805. // Material
  14806. var effectiveMaterial = subMesh.getMaterial();
  14807. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14808. return;
  14809. }
  14810. // Outline - step 1
  14811. var savedDepthWrite = engine.getDepthWrite();
  14812. if (this.renderOutline) {
  14813. engine.setDepthWrite(false);
  14814. scene.getOutlineRenderer().render(subMesh, batch);
  14815. engine.setDepthWrite(savedDepthWrite);
  14816. }
  14817. effectiveMaterial._preBind();
  14818. var effect = effectiveMaterial.getEffect();
  14819. // Bind
  14820. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14821. this._bind(subMesh, effect, fillMode);
  14822. var world = this.getWorldMatrix();
  14823. effectiveMaterial.bind(world, this);
  14824. // Alpha mode
  14825. if (enableAlphaMode) {
  14826. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14827. }
  14828. // Draw
  14829. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14830. if (isInstance) {
  14831. effectiveMaterial.bindOnlyWorldMatrix(world);
  14832. }
  14833. });
  14834. // Unbind
  14835. effectiveMaterial.unbind();
  14836. // Outline - step 2
  14837. if (this.renderOutline && savedDepthWrite) {
  14838. engine.setDepthWrite(true);
  14839. engine.setColorWrite(false);
  14840. scene.getOutlineRenderer().render(subMesh, batch);
  14841. engine.setColorWrite(true);
  14842. }
  14843. // Overlay
  14844. if (this.renderOverlay) {
  14845. var currentMode = engine.getAlphaMode();
  14846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14847. scene.getOutlineRenderer().render(subMesh, batch, true);
  14848. engine.setAlphaMode(currentMode);
  14849. }
  14850. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14851. this._onAfterRenderCallbacks[callbackIndex](this);
  14852. }
  14853. };
  14854. Mesh.prototype.getEmittedParticleSystems = function () {
  14855. var results = new Array();
  14856. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14857. var particleSystem = this.getScene().particleSystems[index];
  14858. if (particleSystem.emitter === this) {
  14859. results.push(particleSystem);
  14860. }
  14861. }
  14862. return results;
  14863. };
  14864. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14865. var results = new Array();
  14866. var descendants = this.getDescendants();
  14867. descendants.push(this);
  14868. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14869. var particleSystem = this.getScene().particleSystems[index];
  14870. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14871. results.push(particleSystem);
  14872. }
  14873. }
  14874. return results;
  14875. };
  14876. Mesh.prototype.getChildren = function () {
  14877. var results = [];
  14878. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14879. var mesh = this.getScene().meshes[index];
  14880. if (mesh.parent === this) {
  14881. results.push(mesh);
  14882. }
  14883. }
  14884. return results;
  14885. };
  14886. Mesh.prototype._checkDelayState = function () {
  14887. var _this = this;
  14888. var that = this;
  14889. var scene = this.getScene();
  14890. if (this._geometry) {
  14891. this._geometry.load(scene);
  14892. }
  14893. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14894. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14895. scene._addPendingData(that);
  14896. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14897. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14898. if (data instanceof ArrayBuffer) {
  14899. _this._delayLoadingFunction(data, _this);
  14900. }
  14901. else {
  14902. _this._delayLoadingFunction(JSON.parse(data), _this);
  14903. }
  14904. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14905. scene._removePendingData(_this);
  14906. }, function () { }, scene.database, getBinaryData);
  14907. }
  14908. };
  14909. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14910. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14911. return false;
  14912. }
  14913. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14914. return false;
  14915. }
  14916. this._checkDelayState();
  14917. return true;
  14918. };
  14919. Mesh.prototype.setMaterialByID = function (id) {
  14920. var materials = this.getScene().materials;
  14921. var index;
  14922. for (index = 0; index < materials.length; index++) {
  14923. if (materials[index].id === id) {
  14924. this.material = materials[index];
  14925. return;
  14926. }
  14927. }
  14928. // Multi
  14929. var multiMaterials = this.getScene().multiMaterials;
  14930. for (index = 0; index < multiMaterials.length; index++) {
  14931. if (multiMaterials[index].id === id) {
  14932. this.material = multiMaterials[index];
  14933. return;
  14934. }
  14935. }
  14936. };
  14937. Mesh.prototype.getAnimatables = function () {
  14938. var results = [];
  14939. if (this.material) {
  14940. results.push(this.material);
  14941. }
  14942. if (this.skeleton) {
  14943. results.push(this.skeleton);
  14944. }
  14945. return results;
  14946. };
  14947. // Geometry
  14948. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14949. // Position
  14950. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14951. return;
  14952. }
  14953. this._resetPointsArrayCache();
  14954. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14955. var temp = [];
  14956. var index;
  14957. for (index = 0; index < data.length; index += 3) {
  14958. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14959. }
  14960. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14961. // Normals
  14962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14963. return;
  14964. }
  14965. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14966. temp = [];
  14967. for (index = 0; index < data.length; index += 3) {
  14968. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14969. }
  14970. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14971. // flip faces?
  14972. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14973. this.flipFaces();
  14974. }
  14975. };
  14976. // Will apply current transform to mesh and reset world matrix
  14977. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14978. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14979. this.scaling.copyFromFloats(1, 1, 1);
  14980. this.position.copyFromFloats(0, 0, 0);
  14981. this.rotation.copyFromFloats(0, 0, 0);
  14982. //only if quaternion is already set
  14983. if (this.rotationQuaternion) {
  14984. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14985. }
  14986. this._worldMatrix = BABYLON.Matrix.Identity();
  14987. };
  14988. // Cache
  14989. Mesh.prototype._resetPointsArrayCache = function () {
  14990. this._positions = null;
  14991. };
  14992. Mesh.prototype._generatePointsArray = function () {
  14993. if (this._positions)
  14994. return true;
  14995. this._positions = [];
  14996. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14997. if (!data) {
  14998. return false;
  14999. }
  15000. for (var index = 0; index < data.length; index += 3) {
  15001. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15002. }
  15003. return true;
  15004. };
  15005. // Clone
  15006. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15007. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15008. };
  15009. // Dispose
  15010. Mesh.prototype.dispose = function (doNotRecurse) {
  15011. if (this._geometry) {
  15012. this._geometry.releaseForMesh(this, true);
  15013. }
  15014. // Instances
  15015. if (this._worldMatricesInstancesBuffer) {
  15016. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15017. this._worldMatricesInstancesBuffer = null;
  15018. }
  15019. while (this.instances.length) {
  15020. this.instances[0].dispose();
  15021. }
  15022. _super.prototype.dispose.call(this, doNotRecurse);
  15023. };
  15024. // Geometric tools
  15025. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15026. var _this = this;
  15027. var scene = this.getScene();
  15028. var onload = function (img) {
  15029. // Getting height map data
  15030. var canvas = document.createElement("canvas");
  15031. var context = canvas.getContext("2d");
  15032. var heightMapWidth = img.width;
  15033. var heightMapHeight = img.height;
  15034. canvas.width = heightMapWidth;
  15035. canvas.height = heightMapHeight;
  15036. context.drawImage(img, 0, 0);
  15037. // Create VertexData from map data
  15038. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15039. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15040. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15041. //execute success callback, if set
  15042. if (onSuccess) {
  15043. onSuccess(_this);
  15044. }
  15045. };
  15046. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15047. };
  15048. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15049. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15050. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15051. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15052. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15053. return;
  15054. }
  15055. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15056. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15057. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15058. var position = BABYLON.Vector3.Zero();
  15059. var normal = BABYLON.Vector3.Zero();
  15060. var uv = BABYLON.Vector2.Zero();
  15061. for (var index = 0; index < positions.length; index += 3) {
  15062. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15063. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15064. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15065. // Compute height
  15066. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15067. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15068. var pos = (u + v * heightMapWidth) * 4;
  15069. var r = buffer[pos] / 255.0;
  15070. var g = buffer[pos + 1] / 255.0;
  15071. var b = buffer[pos + 2] / 255.0;
  15072. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15073. normal.normalize();
  15074. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15075. position = position.add(normal);
  15076. position.toArray(positions, index);
  15077. }
  15078. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15079. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15080. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15081. };
  15082. Mesh.prototype.convertToFlatShadedMesh = function () {
  15083. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15084. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15085. var kinds = this.getVerticesDataKinds();
  15086. var vbs = [];
  15087. var data = [];
  15088. var newdata = [];
  15089. var updatableNormals = false;
  15090. var kindIndex;
  15091. var kind;
  15092. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15093. kind = kinds[kindIndex];
  15094. var vertexBuffer = this.getVertexBuffer(kind);
  15095. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15096. updatableNormals = vertexBuffer.isUpdatable();
  15097. kinds.splice(kindIndex, 1);
  15098. kindIndex--;
  15099. continue;
  15100. }
  15101. vbs[kind] = vertexBuffer;
  15102. data[kind] = vbs[kind].getData();
  15103. newdata[kind] = [];
  15104. }
  15105. // Save previous submeshes
  15106. var previousSubmeshes = this.subMeshes.slice(0);
  15107. var indices = this.getIndices();
  15108. var totalIndices = this.getTotalIndices();
  15109. // Generating unique vertices per face
  15110. var index;
  15111. for (index = 0; index < totalIndices; index++) {
  15112. var vertexIndex = indices[index];
  15113. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15114. kind = kinds[kindIndex];
  15115. var stride = vbs[kind].getStrideSize();
  15116. for (var offset = 0; offset < stride; offset++) {
  15117. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15118. }
  15119. }
  15120. }
  15121. // Updating faces & normal
  15122. var normals = [];
  15123. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15124. for (index = 0; index < totalIndices; index += 3) {
  15125. indices[index] = index;
  15126. indices[index + 1] = index + 1;
  15127. indices[index + 2] = index + 2;
  15128. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15129. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15130. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15131. var p1p2 = p1.subtract(p2);
  15132. var p3p2 = p3.subtract(p2);
  15133. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15134. // Store same normals for every vertex
  15135. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15136. normals.push(normal.x);
  15137. normals.push(normal.y);
  15138. normals.push(normal.z);
  15139. }
  15140. }
  15141. this.setIndices(indices);
  15142. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15143. // Updating vertex buffers
  15144. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15145. kind = kinds[kindIndex];
  15146. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15147. }
  15148. // Updating submeshes
  15149. this.releaseSubMeshes();
  15150. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15151. var previousOne = previousSubmeshes[submeshIndex];
  15152. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15153. }
  15154. this.synchronizeInstances();
  15155. };
  15156. // will inverse faces orientations, and invert normals too if specified
  15157. Mesh.prototype.flipFaces = function (flipNormals) {
  15158. if (flipNormals === void 0) { flipNormals = false; }
  15159. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15160. var i;
  15161. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15162. for (i = 0; i < vertex_data.normals.length; i++) {
  15163. vertex_data.normals[i] *= -1;
  15164. }
  15165. }
  15166. var temp;
  15167. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15168. // reassign indices
  15169. temp = vertex_data.indices[i + 1];
  15170. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15171. vertex_data.indices[i + 2] = temp;
  15172. }
  15173. vertex_data.applyToMesh(this);
  15174. };
  15175. // Instances
  15176. Mesh.prototype.createInstance = function (name) {
  15177. return new BABYLON.InstancedMesh(name, this);
  15178. };
  15179. Mesh.prototype.synchronizeInstances = function () {
  15180. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15181. var instance = this.instances[instanceIndex];
  15182. instance._syncSubMeshes();
  15183. }
  15184. };
  15185. /**
  15186. * Simplify the mesh according to the given array of settings.
  15187. * Function will return immediately and will simplify async.
  15188. * @param settings a collection of simplification settings.
  15189. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15190. * @param type the type of simplification to run.
  15191. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15192. */
  15193. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15194. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15195. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15196. this.getScene().simplificationQueue.addTask({
  15197. settings: settings,
  15198. parallelProcessing: parallelProcessing,
  15199. mesh: this,
  15200. simplificationType: simplificationType,
  15201. successCallback: successCallback
  15202. });
  15203. };
  15204. /**
  15205. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15206. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15207. * This should be used together with the simplification to avoid disappearing triangles.
  15208. * @param successCallback an optional success callback to be called after the optimization finished.
  15209. */
  15210. Mesh.prototype.optimizeIndices = function (successCallback) {
  15211. var _this = this;
  15212. var indices = this.getIndices();
  15213. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15214. var vectorPositions = [];
  15215. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15216. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15217. }
  15218. var dupes = [];
  15219. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15220. var realPos = vectorPositions.length - 1 - iteration;
  15221. var testedPosition = vectorPositions[realPos];
  15222. for (var j = 0; j < realPos; ++j) {
  15223. var againstPosition = vectorPositions[j];
  15224. if (testedPosition.equals(againstPosition)) {
  15225. dupes[realPos] = j;
  15226. break;
  15227. }
  15228. }
  15229. }, function () {
  15230. for (var i = 0; i < indices.length; ++i) {
  15231. indices[i] = dupes[indices[i]] || indices[i];
  15232. }
  15233. //indices are now reordered
  15234. var originalSubMeshes = _this.subMeshes.slice(0);
  15235. _this.setIndices(indices);
  15236. _this.subMeshes = originalSubMeshes;
  15237. if (successCallback) {
  15238. successCallback(_this);
  15239. }
  15240. });
  15241. };
  15242. // Statics
  15243. Mesh.ParseMesh = function (parsedMesh, scene, rootUrl) {
  15244. var mesh = new Mesh(parsedMesh.name, scene);
  15245. mesh.id = parsedMesh.id;
  15246. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15247. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15248. if (parsedMesh.rotationQuaternion) {
  15249. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15250. }
  15251. else if (parsedMesh.rotation) {
  15252. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15253. }
  15254. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15255. if (parsedMesh.localMatrix) {
  15256. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15257. }
  15258. else if (parsedMesh.pivotMatrix) {
  15259. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15260. }
  15261. mesh.setEnabled(parsedMesh.isEnabled);
  15262. mesh.isVisible = parsedMesh.isVisible;
  15263. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15264. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15265. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15266. if (parsedMesh.applyFog !== undefined) {
  15267. mesh.applyFog = parsedMesh.applyFog;
  15268. }
  15269. if (parsedMesh.pickable !== undefined) {
  15270. mesh.isPickable = parsedMesh.pickable;
  15271. }
  15272. if (parsedMesh.alphaIndex !== undefined) {
  15273. mesh.alphaIndex = parsedMesh.alphaIndex;
  15274. }
  15275. mesh.receiveShadows = parsedMesh.receiveShadows;
  15276. mesh.billboardMode = parsedMesh.billboardMode;
  15277. if (parsedMesh.visibility !== undefined) {
  15278. mesh.visibility = parsedMesh.visibility;
  15279. }
  15280. mesh.checkCollisions = parsedMesh.checkCollisions;
  15281. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15282. // freezeWorldMatrix
  15283. if (parsedMesh.freezeWorldMatrix) {
  15284. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15285. }
  15286. // Parent
  15287. if (parsedMesh.parentId) {
  15288. mesh._waitingParentId = parsedMesh.parentId;
  15289. }
  15290. // Actions
  15291. if (parsedMesh.actions !== undefined) {
  15292. mesh._waitingActions = parsedMesh.actions;
  15293. }
  15294. // Geometry
  15295. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15296. if (parsedMesh.delayLoadingFile) {
  15297. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15298. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15299. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15300. if (parsedMesh._binaryInfo) {
  15301. mesh._binaryInfo = parsedMesh._binaryInfo;
  15302. }
  15303. mesh._delayInfo = [];
  15304. if (parsedMesh.hasUVs) {
  15305. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15306. }
  15307. if (parsedMesh.hasUVs2) {
  15308. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15309. }
  15310. if (parsedMesh.hasUVs3) {
  15311. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15312. }
  15313. if (parsedMesh.hasUVs4) {
  15314. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15315. }
  15316. if (parsedMesh.hasUVs5) {
  15317. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15318. }
  15319. if (parsedMesh.hasUVs6) {
  15320. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15321. }
  15322. if (parsedMesh.hasColors) {
  15323. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15324. }
  15325. if (parsedMesh.hasMatricesIndices) {
  15326. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15327. }
  15328. if (parsedMesh.hasMatricesWeights) {
  15329. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15330. }
  15331. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15332. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15333. mesh._checkDelayState();
  15334. }
  15335. }
  15336. else {
  15337. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15338. }
  15339. // Material
  15340. if (parsedMesh.materialId) {
  15341. mesh.setMaterialByID(parsedMesh.materialId);
  15342. }
  15343. else {
  15344. mesh.material = null;
  15345. }
  15346. // Skeleton
  15347. if (parsedMesh.skeletonId > -1) {
  15348. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15349. if (parsedMesh.numBoneInfluencers) {
  15350. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15351. }
  15352. }
  15353. // Physics
  15354. if (parsedMesh.physicsImpostor) {
  15355. if (!scene.isPhysicsEnabled()) {
  15356. scene.enablePhysics();
  15357. }
  15358. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15359. }
  15360. // Animations
  15361. if (parsedMesh.animations) {
  15362. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15363. var parsedAnimation = parsedMesh.animations[animationIndex];
  15364. mesh.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  15365. }
  15366. }
  15367. if (parsedMesh.autoAnimate) {
  15368. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15369. }
  15370. // Layer Mask
  15371. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15372. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15373. }
  15374. else {
  15375. mesh.layerMask = 0x0FFFFFFF;
  15376. }
  15377. // Instances
  15378. if (parsedMesh.instances) {
  15379. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15380. var parsedInstance = parsedMesh.instances[index];
  15381. var instance = mesh.createInstance(parsedInstance.name);
  15382. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15383. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15384. if (parsedInstance.rotationQuaternion) {
  15385. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15386. }
  15387. else if (parsedInstance.rotation) {
  15388. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15389. }
  15390. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15391. instance.checkCollisions = mesh.checkCollisions;
  15392. if (parsedMesh.animations) {
  15393. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15394. parsedAnimation = parsedMesh.animations[animationIndex];
  15395. instance.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  15396. }
  15397. }
  15398. }
  15399. }
  15400. return mesh;
  15401. };
  15402. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15403. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15404. pathArray: pathArray,
  15405. closeArray: closeArray,
  15406. closePath: closePath,
  15407. offset: offset,
  15408. updatable: updatable,
  15409. sideOrientation: sideOrientation,
  15410. instance: instance
  15411. }, scene);
  15412. };
  15413. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15414. var options = {
  15415. radius: radius,
  15416. tessellation: tessellation,
  15417. sideOrientation: sideOrientation,
  15418. updatable: updatable
  15419. };
  15420. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15421. };
  15422. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15423. var options = {
  15424. size: size,
  15425. sideOrientation: sideOrientation,
  15426. updatable: updatable
  15427. };
  15428. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15429. };
  15430. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15431. var options = {
  15432. segments: segments,
  15433. diameterX: diameter,
  15434. diameterY: diameter,
  15435. diameterZ: diameter,
  15436. sideOrientation: sideOrientation,
  15437. updatable: updatable
  15438. };
  15439. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15440. };
  15441. // Cylinder and cone
  15442. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15443. var options = {
  15444. height: height,
  15445. diameterTop: diameterTop,
  15446. diameterBottom: diameterBottom,
  15447. tessellation: tessellation,
  15448. subdivisions: subdivisions,
  15449. sideOrientation: sideOrientation,
  15450. updatable: updatable
  15451. };
  15452. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15453. };
  15454. // Torus (Code from SharpDX.org)
  15455. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15456. var options = {
  15457. diameter: diameter,
  15458. thickness: thickness,
  15459. tessellation: tessellation,
  15460. sideOrientation: sideOrientation,
  15461. updatable: updatable
  15462. };
  15463. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15464. };
  15465. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15466. var options = {
  15467. radius: radius,
  15468. tube: tube,
  15469. radialSegments: radialSegments,
  15470. tubularSegments: tubularSegments,
  15471. p: p,
  15472. q: q,
  15473. sideOrientation: sideOrientation,
  15474. updatable: updatable
  15475. };
  15476. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15477. };
  15478. // Lines
  15479. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15480. var options = {
  15481. points: points,
  15482. updatable: updatable,
  15483. instance: instance
  15484. };
  15485. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15486. };
  15487. // Dashed Lines
  15488. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15489. var options = {
  15490. points: points,
  15491. dashSize: dashSize,
  15492. gapSize: gapSize,
  15493. dashNb: dashNb,
  15494. updatable: updatable
  15495. };
  15496. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15497. };
  15498. // Extrusion
  15499. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15500. var options = {
  15501. shape: shape,
  15502. path: path,
  15503. scale: scale,
  15504. rotation: rotation,
  15505. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15506. sideOrientation: sideOrientation,
  15507. instance: instance,
  15508. updatable: updatable
  15509. };
  15510. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15511. };
  15512. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15513. var options = {
  15514. shape: shape,
  15515. path: path,
  15516. scaleFunction: scaleFunction,
  15517. rotationFunction: rotationFunction,
  15518. ribbonCloseArray: ribbonCloseArray,
  15519. ribbonClosePath: ribbonClosePath,
  15520. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15521. sideOrientation: sideOrientation,
  15522. instance: instance,
  15523. updatable: updatable
  15524. };
  15525. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15526. };
  15527. // Lathe
  15528. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15529. var options = {
  15530. shape: shape,
  15531. radius: radius,
  15532. tessellation: tessellation,
  15533. sideOrientation: sideOrientation,
  15534. updatable: updatable
  15535. };
  15536. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15537. };
  15538. // Plane & ground
  15539. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15540. var options = {
  15541. size: size,
  15542. width: size,
  15543. height: size,
  15544. sideOrientation: sideOrientation,
  15545. updatable: updatable
  15546. };
  15547. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15548. };
  15549. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15550. var options = {
  15551. width: width,
  15552. height: height,
  15553. subdivisions: subdivisions,
  15554. updatable: updatable
  15555. };
  15556. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15557. };
  15558. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15559. var options = {
  15560. xmin: xmin,
  15561. zmin: zmin,
  15562. xmax: xmax,
  15563. zmax: zmax,
  15564. subdivisions: subdivisions,
  15565. precision: precision,
  15566. updatable: updatable
  15567. };
  15568. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15569. };
  15570. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15571. var options = {
  15572. width: width,
  15573. height: height,
  15574. subdivisions: subdivisions,
  15575. minHeight: minHeight,
  15576. maxHeight: maxHeight,
  15577. updatable: updatable,
  15578. onReady: onReady
  15579. };
  15580. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15581. };
  15582. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15583. var options = {
  15584. path: path,
  15585. radius: radius,
  15586. tessellation: tessellation,
  15587. radiusFunction: radiusFunction,
  15588. arc: 1,
  15589. cap: cap,
  15590. updatable: updatable,
  15591. sideOrientation: sideOrientation,
  15592. instance: instance
  15593. };
  15594. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15595. };
  15596. Mesh.CreatePolyhedron = function (name, options, scene) {
  15597. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15598. };
  15599. Mesh.CreateIcoSphere = function (name, options, scene) {
  15600. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15601. };
  15602. // Decals
  15603. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15604. var options = {
  15605. position: position,
  15606. normal: normal,
  15607. size: size,
  15608. angle: angle
  15609. };
  15610. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15611. };
  15612. // Skeletons
  15613. /**
  15614. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15615. */
  15616. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15617. var source;
  15618. if (!this._sourcePositions) {
  15619. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15620. this._sourcePositions = new Float32Array(source);
  15621. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15622. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15623. }
  15624. }
  15625. return this._sourcePositions;
  15626. };
  15627. /**
  15628. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15629. */
  15630. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15631. var source;
  15632. if (!this._sourceNormals) {
  15633. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15634. this._sourceNormals = new Float32Array(source);
  15635. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15636. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15637. }
  15638. }
  15639. return this._sourceNormals;
  15640. };
  15641. /**
  15642. * Update the vertex buffers by applying transformation from the bones
  15643. * @param {skeleton} skeleton to apply
  15644. */
  15645. Mesh.prototype.applySkeleton = function (skeleton) {
  15646. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15647. return this;
  15648. }
  15649. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15650. return this;
  15651. }
  15652. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15653. return this;
  15654. }
  15655. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15656. return this;
  15657. }
  15658. if (!this._sourcePositions) {
  15659. this.setPositionsForCPUSkinning();
  15660. }
  15661. if (!this._sourceNormals) {
  15662. this.setNormalsForCPUSkinning();
  15663. }
  15664. // positionsData checks for not being Float32Array will only pass at most once
  15665. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15666. if (!(positionsData instanceof Float32Array)) {
  15667. positionsData = new Float32Array(positionsData);
  15668. }
  15669. // normalsData checks for not being Float32Array will only pass at most once
  15670. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15671. if (!(normalsData instanceof Float32Array)) {
  15672. normalsData = new Float32Array(normalsData);
  15673. }
  15674. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15675. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15676. var needExtras = this.numBoneInfluencers > 4;
  15677. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15678. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15679. var skeletonMatrices = skeleton.getTransformMatrices();
  15680. var tempVector3 = BABYLON.Vector3.Zero();
  15681. var finalMatrix = new BABYLON.Matrix();
  15682. var tempMatrix = new BABYLON.Matrix();
  15683. var matWeightIdx = 0;
  15684. var inf;
  15685. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15686. var weight;
  15687. for (inf = 0; inf < 4; inf++) {
  15688. weight = matricesWeightsData[matWeightIdx + inf];
  15689. if (weight > 0) {
  15690. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15691. finalMatrix.addToSelf(tempMatrix);
  15692. }
  15693. else
  15694. break;
  15695. }
  15696. if (needExtras) {
  15697. for (inf = 0; inf < 4; inf++) {
  15698. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15699. if (weight > 0) {
  15700. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15701. finalMatrix.addToSelf(tempMatrix);
  15702. }
  15703. else
  15704. break;
  15705. }
  15706. }
  15707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15708. tempVector3.toArray(positionsData, index);
  15709. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15710. tempVector3.toArray(normalsData, index);
  15711. finalMatrix.reset();
  15712. }
  15713. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15714. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15715. return this;
  15716. };
  15717. // Tools
  15718. Mesh.MinMax = function (meshes) {
  15719. var minVector = null;
  15720. var maxVector = null;
  15721. for (var i in meshes) {
  15722. var mesh = meshes[i];
  15723. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15724. if (!minVector) {
  15725. minVector = boundingBox.minimumWorld;
  15726. maxVector = boundingBox.maximumWorld;
  15727. continue;
  15728. }
  15729. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15730. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15731. }
  15732. return {
  15733. min: minVector,
  15734. max: maxVector
  15735. };
  15736. };
  15737. Mesh.Center = function (meshesOrMinMaxVector) {
  15738. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15739. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15740. };
  15741. /**
  15742. * Merge the array of meshes into a single mesh for performance reasons.
  15743. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15744. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15745. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15746. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15747. */
  15748. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15749. if (disposeSource === void 0) { disposeSource = true; }
  15750. var index;
  15751. if (!allow32BitsIndices) {
  15752. var totalVertices = 0;
  15753. // Counting vertices
  15754. for (index = 0; index < meshes.length; index++) {
  15755. if (meshes[index]) {
  15756. totalVertices += meshes[index].getTotalVertices();
  15757. if (totalVertices > 65536) {
  15758. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15759. return null;
  15760. }
  15761. }
  15762. }
  15763. }
  15764. // Merge
  15765. var vertexData;
  15766. var otherVertexData;
  15767. var source;
  15768. for (index = 0; index < meshes.length; index++) {
  15769. if (meshes[index]) {
  15770. meshes[index].computeWorldMatrix(true);
  15771. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15772. otherVertexData.transform(meshes[index].getWorldMatrix());
  15773. if (vertexData) {
  15774. vertexData.merge(otherVertexData);
  15775. }
  15776. else {
  15777. vertexData = otherVertexData;
  15778. source = meshes[index];
  15779. }
  15780. }
  15781. }
  15782. if (!meshSubclass) {
  15783. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15784. }
  15785. vertexData.applyToMesh(meshSubclass);
  15786. // Setting properties
  15787. meshSubclass.material = source.material;
  15788. meshSubclass.checkCollisions = source.checkCollisions;
  15789. // Cleaning
  15790. if (disposeSource) {
  15791. for (index = 0; index < meshes.length; index++) {
  15792. if (meshes[index]) {
  15793. meshes[index].dispose();
  15794. }
  15795. }
  15796. }
  15797. return meshSubclass;
  15798. };
  15799. // Consts
  15800. Mesh._FRONTSIDE = 0;
  15801. Mesh._BACKSIDE = 1;
  15802. Mesh._DOUBLESIDE = 2;
  15803. Mesh._DEFAULTSIDE = 0;
  15804. Mesh._NO_CAP = 0;
  15805. Mesh._CAP_START = 1;
  15806. Mesh._CAP_END = 2;
  15807. Mesh._CAP_ALL = 3;
  15808. return Mesh;
  15809. })(BABYLON.AbstractMesh);
  15810. BABYLON.Mesh = Mesh;
  15811. })(BABYLON || (BABYLON = {}));
  15812. var BABYLON;
  15813. (function (BABYLON) {
  15814. var SubMesh = (function () {
  15815. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15816. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15817. this.materialIndex = materialIndex;
  15818. this.verticesStart = verticesStart;
  15819. this.verticesCount = verticesCount;
  15820. this.indexStart = indexStart;
  15821. this.indexCount = indexCount;
  15822. this._renderId = 0;
  15823. this._mesh = mesh;
  15824. this._renderingMesh = renderingMesh || mesh;
  15825. mesh.subMeshes.push(this);
  15826. this._trianglePlanes = [];
  15827. this._id = mesh.subMeshes.length - 1;
  15828. if (createBoundingBox) {
  15829. this.refreshBoundingInfo();
  15830. mesh.computeWorldMatrix(true);
  15831. }
  15832. }
  15833. SubMesh.prototype.getBoundingInfo = function () {
  15834. return this._boundingInfo;
  15835. };
  15836. SubMesh.prototype.getMesh = function () {
  15837. return this._mesh;
  15838. };
  15839. SubMesh.prototype.getRenderingMesh = function () {
  15840. return this._renderingMesh;
  15841. };
  15842. SubMesh.prototype.getMaterial = function () {
  15843. var rootMaterial = this._renderingMesh.material;
  15844. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15845. var multiMaterial = rootMaterial;
  15846. return multiMaterial.getSubMaterial(this.materialIndex);
  15847. }
  15848. if (!rootMaterial) {
  15849. return this._mesh.getScene().defaultMaterial;
  15850. }
  15851. return rootMaterial;
  15852. };
  15853. // Methods
  15854. SubMesh.prototype.refreshBoundingInfo = function () {
  15855. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15856. if (!data) {
  15857. this._boundingInfo = this._mesh._boundingInfo;
  15858. return;
  15859. }
  15860. var indices = this._renderingMesh.getIndices();
  15861. var extend;
  15862. //is this the only submesh?
  15863. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15864. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15865. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15866. }
  15867. else {
  15868. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15869. }
  15870. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15871. };
  15872. SubMesh.prototype._checkCollision = function (collider) {
  15873. return this._boundingInfo._checkCollision(collider);
  15874. };
  15875. SubMesh.prototype.updateBoundingInfo = function (world) {
  15876. if (!this._boundingInfo) {
  15877. this.refreshBoundingInfo();
  15878. }
  15879. this._boundingInfo._update(world);
  15880. };
  15881. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15882. return this._boundingInfo.isInFrustum(frustumPlanes);
  15883. };
  15884. SubMesh.prototype.render = function (enableAlphaMode) {
  15885. this._renderingMesh.render(this, enableAlphaMode);
  15886. };
  15887. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15888. if (!this._linesIndexBuffer) {
  15889. var linesIndices = [];
  15890. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15891. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15892. }
  15893. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15894. this.linesIndexCount = linesIndices.length;
  15895. }
  15896. return this._linesIndexBuffer;
  15897. };
  15898. SubMesh.prototype.canIntersects = function (ray) {
  15899. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15900. };
  15901. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15902. var intersectInfo = null;
  15903. // Triangles test
  15904. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15905. var p0 = positions[indices[index]];
  15906. var p1 = positions[indices[index + 1]];
  15907. var p2 = positions[indices[index + 2]];
  15908. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15909. if (currentIntersectInfo) {
  15910. if (currentIntersectInfo.distance < 0) {
  15911. continue;
  15912. }
  15913. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15914. intersectInfo = currentIntersectInfo;
  15915. intersectInfo.faceId = index / 3;
  15916. if (fastCheck) {
  15917. break;
  15918. }
  15919. }
  15920. }
  15921. }
  15922. return intersectInfo;
  15923. };
  15924. // Clone
  15925. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15926. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15927. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15928. return result;
  15929. };
  15930. // Dispose
  15931. SubMesh.prototype.dispose = function () {
  15932. if (this._linesIndexBuffer) {
  15933. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15934. this._linesIndexBuffer = null;
  15935. }
  15936. // Remove from mesh
  15937. var index = this._mesh.subMeshes.indexOf(this);
  15938. this._mesh.subMeshes.splice(index, 1);
  15939. };
  15940. // Statics
  15941. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15942. var minVertexIndex = Number.MAX_VALUE;
  15943. var maxVertexIndex = -Number.MAX_VALUE;
  15944. renderingMesh = renderingMesh || mesh;
  15945. var indices = renderingMesh.getIndices();
  15946. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15947. var vertexIndex = indices[index];
  15948. if (vertexIndex < minVertexIndex)
  15949. minVertexIndex = vertexIndex;
  15950. if (vertexIndex > maxVertexIndex)
  15951. maxVertexIndex = vertexIndex;
  15952. }
  15953. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15954. };
  15955. return SubMesh;
  15956. })();
  15957. BABYLON.SubMesh = SubMesh;
  15958. })(BABYLON || (BABYLON = {}));
  15959. var BABYLON;
  15960. (function (BABYLON) {
  15961. var MeshBuilder = (function () {
  15962. function MeshBuilder() {
  15963. }
  15964. MeshBuilder.CreateBox = function (name, options, scene) {
  15965. var box = new BABYLON.Mesh(name, scene);
  15966. var vertexData = BABYLON.VertexData.CreateBox(options);
  15967. vertexData.applyToMesh(box, options.updatable);
  15968. return box;
  15969. };
  15970. MeshBuilder.CreateSphere = function (name, options, scene) {
  15971. var sphere = new BABYLON.Mesh(name, scene);
  15972. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15973. vertexData.applyToMesh(sphere, options.updatable);
  15974. return sphere;
  15975. };
  15976. MeshBuilder.CreateDisc = function (name, options, scene) {
  15977. var disc = new BABYLON.Mesh(name, scene);
  15978. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15979. vertexData.applyToMesh(disc, options.updatable);
  15980. return disc;
  15981. };
  15982. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15983. var sphere = new BABYLON.Mesh(name, scene);
  15984. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15985. vertexData.applyToMesh(sphere, options.updatable);
  15986. return sphere;
  15987. };
  15988. ;
  15989. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15990. var pathArray = options.pathArray;
  15991. var closeArray = options.closeArray;
  15992. var closePath = options.closePath;
  15993. var offset = options.offset;
  15994. var sideOrientation = options.sideOrientation;
  15995. var instance = options.instance;
  15996. var updatable = options.updatable;
  15997. if (instance) {
  15998. // positionFunction : ribbon case
  15999. // only pathArray and sideOrientation parameters are taken into account for positions update
  16000. var positionFunction = function (positions) {
  16001. var minlg = pathArray[0].length;
  16002. var i = 0;
  16003. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16004. for (var si = 1; si <= ns; si++) {
  16005. for (var p = 0; p < pathArray.length; p++) {
  16006. var path = pathArray[p];
  16007. var l = path.length;
  16008. minlg = (minlg < l) ? minlg : l;
  16009. var j = 0;
  16010. while (j < minlg) {
  16011. positions[i] = path[j].x;
  16012. positions[i + 1] = path[j].y;
  16013. positions[i + 2] = path[j].z;
  16014. j++;
  16015. i += 3;
  16016. }
  16017. if (instance._closePath) {
  16018. positions[i] = path[0].x;
  16019. positions[i + 1] = path[0].y;
  16020. positions[i + 2] = path[0].z;
  16021. i += 3;
  16022. }
  16023. }
  16024. }
  16025. };
  16026. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16027. positionFunction(positions);
  16028. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16029. if (!(instance.areNormalsFrozen)) {
  16030. var indices = instance.getIndices();
  16031. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16032. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16033. if (instance._closePath) {
  16034. var indexFirst = 0;
  16035. var indexLast = 0;
  16036. for (var p = 0; p < pathArray.length; p++) {
  16037. indexFirst = instance._idx[p] * 3;
  16038. if (p + 1 < pathArray.length) {
  16039. indexLast = (instance._idx[p + 1] - 1) * 3;
  16040. }
  16041. else {
  16042. indexLast = normals.length - 3;
  16043. }
  16044. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16045. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16046. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16047. normals[indexLast] = normals[indexFirst];
  16048. normals[indexLast + 1] = normals[indexFirst + 1];
  16049. normals[indexLast + 2] = normals[indexFirst + 2];
  16050. }
  16051. }
  16052. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16053. }
  16054. return instance;
  16055. }
  16056. else {
  16057. var ribbon = new BABYLON.Mesh(name, scene);
  16058. ribbon.sideOrientation = sideOrientation;
  16059. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16060. if (closePath) {
  16061. ribbon._idx = vertexData._idx;
  16062. }
  16063. ribbon._closePath = closePath;
  16064. ribbon._closeArray = closeArray;
  16065. vertexData.applyToMesh(ribbon, updatable);
  16066. return ribbon;
  16067. }
  16068. };
  16069. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16070. var cylinder = new BABYLON.Mesh(name, scene);
  16071. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16072. vertexData.applyToMesh(cylinder, options.updatable);
  16073. return cylinder;
  16074. };
  16075. MeshBuilder.CreateTorus = function (name, options, scene) {
  16076. var torus = new BABYLON.Mesh(name, scene);
  16077. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16078. vertexData.applyToMesh(torus, options.updatable);
  16079. return torus;
  16080. };
  16081. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16082. var torusKnot = new BABYLON.Mesh(name, scene);
  16083. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16084. vertexData.applyToMesh(torusKnot, options.updatable);
  16085. return torusKnot;
  16086. };
  16087. MeshBuilder.CreateLines = function (name, options, scene) {
  16088. var instance = options.instance;
  16089. var points = options.points;
  16090. if (instance) {
  16091. var positionFunction = function (positions) {
  16092. var i = 0;
  16093. for (var p = 0; p < points.length; p++) {
  16094. positions[i] = points[p].x;
  16095. positions[i + 1] = points[p].y;
  16096. positions[i + 2] = points[p].z;
  16097. i += 3;
  16098. }
  16099. };
  16100. instance.updateMeshPositions(positionFunction, false);
  16101. return instance;
  16102. }
  16103. // lines creation
  16104. var lines = new BABYLON.LinesMesh(name, scene);
  16105. var vertexData = BABYLON.VertexData.CreateLines(options);
  16106. vertexData.applyToMesh(lines, options.updatable);
  16107. return lines;
  16108. };
  16109. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16110. var points = options.points;
  16111. var instance = options.instance;
  16112. var gapSize = options.gapSize;
  16113. var dashNb = options.dashNb;
  16114. var dashSize = options.dashSize;
  16115. if (instance) {
  16116. var positionFunction = function (positions) {
  16117. var curvect = BABYLON.Vector3.Zero();
  16118. var nbSeg = positions.length / 6;
  16119. var lg = 0;
  16120. var nb = 0;
  16121. var shft = 0;
  16122. var dashshft = 0;
  16123. var curshft = 0;
  16124. var p = 0;
  16125. var i = 0;
  16126. var j = 0;
  16127. for (i = 0; i < points.length - 1; i++) {
  16128. points[i + 1].subtractToRef(points[i], curvect);
  16129. lg += curvect.length();
  16130. }
  16131. shft = lg / nbSeg;
  16132. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16133. for (i = 0; i < points.length - 1; i++) {
  16134. points[i + 1].subtractToRef(points[i], curvect);
  16135. nb = Math.floor(curvect.length() / shft);
  16136. curvect.normalize();
  16137. j = 0;
  16138. while (j < nb && p < positions.length) {
  16139. curshft = shft * j;
  16140. positions[p] = points[i].x + curshft * curvect.x;
  16141. positions[p + 1] = points[i].y + curshft * curvect.y;
  16142. positions[p + 2] = points[i].z + curshft * curvect.z;
  16143. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16144. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16145. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16146. p += 6;
  16147. j++;
  16148. }
  16149. }
  16150. while (p < positions.length) {
  16151. positions[p] = points[i].x;
  16152. positions[p + 1] = points[i].y;
  16153. positions[p + 2] = points[i].z;
  16154. p += 3;
  16155. }
  16156. };
  16157. instance.updateMeshPositions(positionFunction, false);
  16158. return instance;
  16159. }
  16160. // dashed lines creation
  16161. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16162. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16163. vertexData.applyToMesh(dashedLines, options.updatable);
  16164. dashedLines.dashSize = dashSize;
  16165. dashedLines.gapSize = gapSize;
  16166. return dashedLines;
  16167. };
  16168. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16169. var path = options.path;
  16170. var shape = options.shape;
  16171. var scale = options.scale || 1;
  16172. var rotation = options.rotation || 0;
  16173. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16174. var updatable = options.updatable;
  16175. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16176. var instance = options.instance;
  16177. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16178. };
  16179. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16180. var path = options.path;
  16181. var shape = options.shape;
  16182. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16183. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16184. var ribbonCloseArray = options.ribbonCloseArray || false;
  16185. var ribbonClosePath = options.ribbonClosePath || false;
  16186. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16187. var updatable = options.updatable;
  16188. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16189. var instance = options.instance;
  16190. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16191. };
  16192. MeshBuilder.CreateLathe = function (name, options, scene) {
  16193. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16194. var closed = (options.closed === undefined) ? true : options.closed;
  16195. var shape = options.shape;
  16196. var radius = options.radius || 1;
  16197. var tessellation = options.tessellation || 64;
  16198. var updatable = options.updatable;
  16199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16200. var pi2 = Math.PI * 2;
  16201. var shapeLathe = new Array();
  16202. // first rotatable point
  16203. var i = 0;
  16204. while (shape[i].x === 0) {
  16205. i++;
  16206. }
  16207. var pt = shape[i];
  16208. for (i = 0; i < shape.length; i++) {
  16209. shapeLathe.push(shape[i].subtract(pt));
  16210. }
  16211. // circle path
  16212. var step = pi2 / tessellation * arc;
  16213. var rotated;
  16214. var path = new Array();
  16215. ;
  16216. for (i = 0; i <= tessellation; i++) {
  16217. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16218. path.push(rotated);
  16219. }
  16220. if (closed) {
  16221. path.push(path[0]);
  16222. }
  16223. // extrusion
  16224. var scaleFunction = function () { return 1; };
  16225. var rotateFunction = function () { return 0; };
  16226. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16227. return lathe;
  16228. };
  16229. MeshBuilder.CreatePlane = function (name, options, scene) {
  16230. var plane = new BABYLON.Mesh(name, scene);
  16231. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16232. vertexData.applyToMesh(plane, options.updatable);
  16233. if (options.sourcePlane) {
  16234. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16235. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16236. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16237. plane.rotate(vectorProduct, product);
  16238. }
  16239. return plane;
  16240. };
  16241. MeshBuilder.CreateGround = function (name, options, scene) {
  16242. var ground = new BABYLON.GroundMesh(name, scene);
  16243. ground._setReady(false);
  16244. ground._subdivisions = options.subdivisions || 1;
  16245. var vertexData = BABYLON.VertexData.CreateGround(options);
  16246. vertexData.applyToMesh(ground, options.updatable);
  16247. ground._setReady(true);
  16248. return ground;
  16249. };
  16250. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16251. var tiledGround = new BABYLON.Mesh(name, scene);
  16252. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16253. vertexData.applyToMesh(tiledGround, options.updatable);
  16254. return tiledGround;
  16255. };
  16256. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16257. var width = options.width || 10;
  16258. var height = options.height || 10;
  16259. var subdivisions = options.subdivisions || 1;
  16260. var minHeight = options.minHeight;
  16261. var maxHeight = options.maxHeight || 10;
  16262. var updatable = options.updatable;
  16263. var onReady = options.onReady;
  16264. var ground = new BABYLON.GroundMesh(name, scene);
  16265. ground._subdivisions = subdivisions;
  16266. ground._setReady(false);
  16267. var onload = function (img) {
  16268. // Getting height map data
  16269. var canvas = document.createElement("canvas");
  16270. var context = canvas.getContext("2d");
  16271. var bufferWidth = img.width;
  16272. var bufferHeight = img.height;
  16273. canvas.width = bufferWidth;
  16274. canvas.height = bufferHeight;
  16275. context.drawImage(img, 0, 0);
  16276. // Create VertexData from map data
  16277. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16278. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16279. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16280. width: width, height: height,
  16281. subdivisions: subdivisions,
  16282. minHeight: minHeight, maxHeight: maxHeight,
  16283. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16284. });
  16285. vertexData.applyToMesh(ground, updatable);
  16286. ground._setReady(true);
  16287. //execute ready callback, if set
  16288. if (onReady) {
  16289. onReady(ground);
  16290. }
  16291. };
  16292. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16293. return ground;
  16294. };
  16295. MeshBuilder.CreateTube = function (name, options, scene) {
  16296. var path = options.path;
  16297. var radius = options.radius || 1;
  16298. var tessellation = options.tessellation || 64;
  16299. var radiusFunction = options.radiusFunction;
  16300. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16301. var updatable = options.updatable;
  16302. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16303. var instance = options.instance;
  16304. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16305. // tube geometry
  16306. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16307. var tangents = path3D.getTangents();
  16308. var normals = path3D.getNormals();
  16309. var distances = path3D.getDistances();
  16310. var pi2 = Math.PI * 2;
  16311. var step = pi2 / tessellation * arc;
  16312. var returnRadius = function () { return radius; };
  16313. var radiusFunctionFinal = radiusFunction || returnRadius;
  16314. var circlePath;
  16315. var rad;
  16316. var normal;
  16317. var rotated;
  16318. var rotationMatrix = BABYLON.Matrix.Zero();
  16319. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16320. for (var i = 0; i < path.length; i++) {
  16321. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16322. circlePath = Array(); // current circle array
  16323. normal = normals[i]; // current normal
  16324. for (var t = 0; t < tessellation; t++) {
  16325. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16326. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16327. circlePath.push(rotated);
  16328. }
  16329. circlePaths[index] = circlePath;
  16330. index++;
  16331. }
  16332. // cap
  16333. var capPath = function (nbPoints, pathIndex) {
  16334. var pointCap = Array();
  16335. for (var i = 0; i < nbPoints; i++) {
  16336. pointCap.push(path[pathIndex]);
  16337. }
  16338. return pointCap;
  16339. };
  16340. switch (cap) {
  16341. case BABYLON.Mesh.NO_CAP:
  16342. break;
  16343. case BABYLON.Mesh.CAP_START:
  16344. circlePaths[0] = capPath(tessellation, 0);
  16345. circlePaths[1] = circlePaths[2].slice(0);
  16346. break;
  16347. case BABYLON.Mesh.CAP_END:
  16348. circlePaths[index] = circlePaths[index - 1].slice(0);
  16349. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16350. break;
  16351. case BABYLON.Mesh.CAP_ALL:
  16352. circlePaths[0] = capPath(tessellation, 0);
  16353. circlePaths[1] = circlePaths[2].slice(0);
  16354. circlePaths[index] = circlePaths[index - 1].slice(0);
  16355. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16356. break;
  16357. default:
  16358. break;
  16359. }
  16360. return circlePaths;
  16361. };
  16362. var path3D;
  16363. var pathArray;
  16364. if (instance) {
  16365. var arc = options.arc || instance.arc;
  16366. path3D = (instance.path3D).update(path);
  16367. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16368. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16369. instance.path3D = path3D;
  16370. instance.pathArray = pathArray;
  16371. instance.arc = arc;
  16372. return instance;
  16373. }
  16374. // tube creation
  16375. path3D = new BABYLON.Path3D(path);
  16376. var newPathArray = new Array();
  16377. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16378. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16379. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16380. tube.pathArray = pathArray;
  16381. tube.path3D = path3D;
  16382. tube.tessellation = tessellation;
  16383. tube.cap = cap;
  16384. tube.arc = options.arc;
  16385. return tube;
  16386. };
  16387. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16388. var polyhedron = new BABYLON.Mesh(name, scene);
  16389. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16390. vertexData.applyToMesh(polyhedron, options.updatable);
  16391. return polyhedron;
  16392. };
  16393. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16394. var indices = sourceMesh.getIndices();
  16395. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16396. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16397. var position = options.position || BABYLON.Vector3.Zero();
  16398. var normal = options.normal || BABYLON.Vector3.Up();
  16399. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16400. var angle = options.angle || 0;
  16401. // Getting correct rotation
  16402. if (!normal) {
  16403. var target = new BABYLON.Vector3(0, 0, 1);
  16404. var camera = sourceMesh.getScene().activeCamera;
  16405. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16406. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16407. }
  16408. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16409. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16410. var pitch = Math.atan2(normal.y, len);
  16411. // Matrix
  16412. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16413. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16414. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16415. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16416. var vertexData = new BABYLON.VertexData();
  16417. vertexData.indices = [];
  16418. vertexData.positions = [];
  16419. vertexData.normals = [];
  16420. vertexData.uvs = [];
  16421. var currentVertexDataIndex = 0;
  16422. var extractDecalVector3 = function (indexId) {
  16423. var vertexId = indices[indexId];
  16424. var result = new BABYLON.PositionNormalVertex();
  16425. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16426. // Send vector to decal local world
  16427. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16428. // Get normal
  16429. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16430. return result;
  16431. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16432. var clip = function (vertices, axis) {
  16433. if (vertices.length === 0) {
  16434. return vertices;
  16435. }
  16436. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16437. var clipVertices = function (v0, v1) {
  16438. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16439. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16440. };
  16441. var result = new Array();
  16442. for (var index = 0; index < vertices.length; index += 3) {
  16443. var v1Out;
  16444. var v2Out;
  16445. var v3Out;
  16446. var total = 0;
  16447. var nV1, nV2, nV3, nV4;
  16448. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16449. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16450. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16451. v1Out = d1 > 0;
  16452. v2Out = d2 > 0;
  16453. v3Out = d3 > 0;
  16454. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16455. switch (total) {
  16456. case 0:
  16457. result.push(vertices[index]);
  16458. result.push(vertices[index + 1]);
  16459. result.push(vertices[index + 2]);
  16460. break;
  16461. case 1:
  16462. if (v1Out) {
  16463. nV1 = vertices[index + 1];
  16464. nV2 = vertices[index + 2];
  16465. nV3 = clipVertices(vertices[index], nV1);
  16466. nV4 = clipVertices(vertices[index], nV2);
  16467. }
  16468. if (v2Out) {
  16469. nV1 = vertices[index];
  16470. nV2 = vertices[index + 2];
  16471. nV3 = clipVertices(vertices[index + 1], nV1);
  16472. nV4 = clipVertices(vertices[index + 1], nV2);
  16473. result.push(nV3);
  16474. result.push(nV2.clone());
  16475. result.push(nV1.clone());
  16476. result.push(nV2.clone());
  16477. result.push(nV3.clone());
  16478. result.push(nV4);
  16479. break;
  16480. }
  16481. if (v3Out) {
  16482. nV1 = vertices[index];
  16483. nV2 = vertices[index + 1];
  16484. nV3 = clipVertices(vertices[index + 2], nV1);
  16485. nV4 = clipVertices(vertices[index + 2], nV2);
  16486. }
  16487. result.push(nV1.clone());
  16488. result.push(nV2.clone());
  16489. result.push(nV3);
  16490. result.push(nV4);
  16491. result.push(nV3.clone());
  16492. result.push(nV2.clone());
  16493. break;
  16494. case 2:
  16495. if (!v1Out) {
  16496. nV1 = vertices[index].clone();
  16497. nV2 = clipVertices(nV1, vertices[index + 1]);
  16498. nV3 = clipVertices(nV1, vertices[index + 2]);
  16499. result.push(nV1);
  16500. result.push(nV2);
  16501. result.push(nV3);
  16502. }
  16503. if (!v2Out) {
  16504. nV1 = vertices[index + 1].clone();
  16505. nV2 = clipVertices(nV1, vertices[index + 2]);
  16506. nV3 = clipVertices(nV1, vertices[index]);
  16507. result.push(nV1);
  16508. result.push(nV2);
  16509. result.push(nV3);
  16510. }
  16511. if (!v3Out) {
  16512. nV1 = vertices[index + 2].clone();
  16513. nV2 = clipVertices(nV1, vertices[index]);
  16514. nV3 = clipVertices(nV1, vertices[index + 1]);
  16515. result.push(nV1);
  16516. result.push(nV2);
  16517. result.push(nV3);
  16518. }
  16519. break;
  16520. case 3:
  16521. break;
  16522. }
  16523. }
  16524. return result;
  16525. };
  16526. for (var index = 0; index < indices.length; index += 3) {
  16527. var faceVertices = new Array();
  16528. faceVertices.push(extractDecalVector3(index));
  16529. faceVertices.push(extractDecalVector3(index + 1));
  16530. faceVertices.push(extractDecalVector3(index + 2));
  16531. // Clip
  16532. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16533. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16534. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16535. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16536. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16537. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16538. if (faceVertices.length === 0) {
  16539. continue;
  16540. }
  16541. // Add UVs and get back to world
  16542. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16543. var vertex = faceVertices[vIndex];
  16544. //TODO check for Int32Array
  16545. vertexData.indices.push(currentVertexDataIndex);
  16546. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16547. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16548. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16549. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16550. currentVertexDataIndex++;
  16551. }
  16552. }
  16553. // Return mesh
  16554. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16555. vertexData.applyToMesh(decal);
  16556. decal.position = position.clone();
  16557. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16558. return decal;
  16559. };
  16560. // Privates
  16561. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16562. // extrusion geometry
  16563. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16564. var tangents = path3D.getTangents();
  16565. var normals = path3D.getNormals();
  16566. var binormals = path3D.getBinormals();
  16567. var distances = path3D.getDistances();
  16568. var angle = 0;
  16569. var returnScale = function () { return scale; };
  16570. var returnRotation = function () { return rotation; };
  16571. var rotate = custom ? rotateFunction : returnRotation;
  16572. var scl = custom ? scaleFunction : returnScale;
  16573. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16574. var rotationMatrix = BABYLON.Matrix.Zero();
  16575. for (var i = 0; i < curve.length; i++) {
  16576. var shapePath = new Array();
  16577. var angleStep = rotate(i, distances[i]);
  16578. var scaleRatio = scl(i, distances[i]);
  16579. for (var p = 0; p < shape.length; p++) {
  16580. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16581. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16582. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16583. shapePath.push(rotated);
  16584. }
  16585. shapePaths[index] = shapePath;
  16586. angle += angleStep;
  16587. index++;
  16588. }
  16589. // cap
  16590. var capPath = function (shapePath) {
  16591. var pointCap = Array();
  16592. var barycenter = BABYLON.Vector3.Zero();
  16593. var i;
  16594. for (i = 0; i < shapePath.length; i++) {
  16595. barycenter.addInPlace(shapePath[i]);
  16596. }
  16597. barycenter.scaleInPlace(1 / shapePath.length);
  16598. for (i = 0; i < shapePath.length; i++) {
  16599. pointCap.push(barycenter);
  16600. }
  16601. return pointCap;
  16602. };
  16603. switch (cap) {
  16604. case BABYLON.Mesh.NO_CAP:
  16605. break;
  16606. case BABYLON.Mesh.CAP_START:
  16607. shapePaths[0] = capPath(shapePaths[2]);
  16608. shapePaths[1] = shapePaths[2].slice(0);
  16609. break;
  16610. case BABYLON.Mesh.CAP_END:
  16611. shapePaths[index] = shapePaths[index - 1];
  16612. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16613. break;
  16614. case BABYLON.Mesh.CAP_ALL:
  16615. shapePaths[0] = capPath(shapePaths[2]);
  16616. shapePaths[1] = shapePaths[2].slice(0);
  16617. shapePaths[index] = shapePaths[index - 1];
  16618. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16619. break;
  16620. default:
  16621. break;
  16622. }
  16623. return shapePaths;
  16624. };
  16625. var path3D;
  16626. var pathArray;
  16627. if (instance) {
  16628. path3D = (instance.path3D).update(curve);
  16629. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16630. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16631. return instance;
  16632. }
  16633. // extruded shape creation
  16634. path3D = new BABYLON.Path3D(curve);
  16635. var newShapePaths = new Array();
  16636. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16637. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16638. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16639. extrudedGeneric.pathArray = pathArray;
  16640. extrudedGeneric.path3D = path3D;
  16641. extrudedGeneric.cap = cap;
  16642. return extrudedGeneric;
  16643. };
  16644. return MeshBuilder;
  16645. })();
  16646. BABYLON.MeshBuilder = MeshBuilder;
  16647. })(BABYLON || (BABYLON = {}));
  16648. var BABYLON;
  16649. (function (BABYLON) {
  16650. var BaseTexture = (function () {
  16651. function BaseTexture(scene) {
  16652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16653. this.hasAlpha = false;
  16654. this.getAlphaFromRGB = false;
  16655. this.level = 1;
  16656. this.isCube = false;
  16657. this.isRenderTarget = false;
  16658. this.animations = new Array();
  16659. this.coordinatesIndex = 0;
  16660. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16661. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16662. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16663. this.anisotropicFilteringLevel = 4;
  16664. this._scene = scene;
  16665. this._scene.textures.push(this);
  16666. }
  16667. BaseTexture.prototype.getScene = function () {
  16668. return this._scene;
  16669. };
  16670. BaseTexture.prototype.getTextureMatrix = function () {
  16671. return null;
  16672. };
  16673. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16674. return null;
  16675. };
  16676. BaseTexture.prototype.getInternalTexture = function () {
  16677. return this._texture;
  16678. };
  16679. BaseTexture.prototype.isReady = function () {
  16680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16681. return true;
  16682. }
  16683. if (this._texture) {
  16684. return this._texture.isReady;
  16685. }
  16686. return false;
  16687. };
  16688. BaseTexture.prototype.getSize = function () {
  16689. if (this._texture._width) {
  16690. return { width: this._texture._width, height: this._texture._height };
  16691. }
  16692. if (this._texture._size) {
  16693. return { width: this._texture._size, height: this._texture._size };
  16694. }
  16695. return { width: 0, height: 0 };
  16696. };
  16697. BaseTexture.prototype.getBaseSize = function () {
  16698. if (!this.isReady())
  16699. return { width: 0, height: 0 };
  16700. if (this._texture._size) {
  16701. return { width: this._texture._size, height: this._texture._size };
  16702. }
  16703. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16704. };
  16705. BaseTexture.prototype.scale = function (ratio) {
  16706. };
  16707. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16708. get: function () {
  16709. return false;
  16710. },
  16711. enumerable: true,
  16712. configurable: true
  16713. });
  16714. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16715. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16716. for (var index = 0; index < texturesCache.length; index++) {
  16717. var texturesCacheEntry = texturesCache[index];
  16718. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16719. texturesCache.splice(index, 1);
  16720. return;
  16721. }
  16722. }
  16723. };
  16724. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16725. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16726. for (var index = 0; index < texturesCache.length; index++) {
  16727. var texturesCacheEntry = texturesCache[index];
  16728. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16729. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16730. texturesCacheEntry.references++;
  16731. return texturesCacheEntry;
  16732. }
  16733. }
  16734. }
  16735. return null;
  16736. };
  16737. BaseTexture.prototype.delayLoad = function () {
  16738. };
  16739. BaseTexture.prototype.clone = function () {
  16740. return null;
  16741. };
  16742. BaseTexture.prototype.releaseInternalTexture = function () {
  16743. if (this._texture) {
  16744. this._scene.getEngine().releaseInternalTexture(this._texture);
  16745. delete this._texture;
  16746. }
  16747. };
  16748. BaseTexture.prototype.dispose = function () {
  16749. // Animations
  16750. this.getScene().stopAnimation(this);
  16751. // Remove from scene
  16752. var index = this._scene.textures.indexOf(this);
  16753. if (index >= 0) {
  16754. this._scene.textures.splice(index, 1);
  16755. }
  16756. if (this._texture === undefined) {
  16757. return;
  16758. }
  16759. // Callback
  16760. if (this.onDispose) {
  16761. this.onDispose();
  16762. }
  16763. };
  16764. BaseTexture.prototype.serialize = function () {
  16765. var serializationObject = {};
  16766. if (!this.name) {
  16767. return null;
  16768. }
  16769. serializationObject.name = this.name;
  16770. serializationObject.hasAlpha = this.hasAlpha;
  16771. serializationObject.level = this.level;
  16772. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16773. serializationObject.coordinatesMode = this.coordinatesMode;
  16774. serializationObject.wrapU = this.wrapU;
  16775. serializationObject.wrapV = this.wrapV;
  16776. // Animations
  16777. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16778. return serializationObject;
  16779. };
  16780. BaseTexture.ParseCubeTexture = function (parsedTexture, scene, rootUrl) {
  16781. var texture = null;
  16782. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  16783. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  16784. texture.name = parsedTexture.name;
  16785. texture.hasAlpha = parsedTexture.hasAlpha;
  16786. texture.level = parsedTexture.level;
  16787. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16788. }
  16789. return texture;
  16790. };
  16791. BaseTexture.ParseTexture = function (parsedTexture, scene, rootUrl) {
  16792. if (parsedTexture.isCube) {
  16793. return BaseTexture.ParseCubeTexture(parsedTexture, scene, rootUrl);
  16794. }
  16795. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16796. return null;
  16797. }
  16798. var texture;
  16799. if (parsedTexture.mirrorPlane) {
  16800. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16801. texture._waitingRenderList = parsedTexture.renderList;
  16802. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  16803. }
  16804. else if (parsedTexture.isRenderTarget) {
  16805. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16806. texture._waitingRenderList = parsedTexture.renderList;
  16807. }
  16808. else {
  16809. if (parsedTexture.base64String) {
  16810. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  16811. }
  16812. else {
  16813. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  16814. }
  16815. }
  16816. texture.name = parsedTexture.name;
  16817. texture.hasAlpha = parsedTexture.hasAlpha;
  16818. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  16819. texture.level = parsedTexture.level;
  16820. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  16821. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16822. texture.uOffset = parsedTexture.uOffset;
  16823. texture.vOffset = parsedTexture.vOffset;
  16824. texture.uScale = parsedTexture.uScale;
  16825. texture.vScale = parsedTexture.vScale;
  16826. texture.uAng = parsedTexture.uAng;
  16827. texture.vAng = parsedTexture.vAng;
  16828. texture.wAng = parsedTexture.wAng;
  16829. texture.wrapU = parsedTexture.wrapU;
  16830. texture.wrapV = parsedTexture.wrapV;
  16831. // Animations
  16832. if (parsedTexture.animations) {
  16833. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  16834. var parsedAnimation = parsedTexture.animations[animationIndex];
  16835. texture.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  16836. }
  16837. }
  16838. return texture;
  16839. };
  16840. return BaseTexture;
  16841. })();
  16842. BABYLON.BaseTexture = BaseTexture;
  16843. })(BABYLON || (BABYLON = {}));
  16844. var BABYLON;
  16845. (function (BABYLON) {
  16846. var Texture = (function (_super) {
  16847. __extends(Texture, _super);
  16848. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16849. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16850. if (onLoad === void 0) { onLoad = null; }
  16851. if (onError === void 0) { onError = null; }
  16852. if (buffer === void 0) { buffer = null; }
  16853. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16854. _super.call(this, scene);
  16855. this.uOffset = 0;
  16856. this.vOffset = 0;
  16857. this.uScale = 1.0;
  16858. this.vScale = 1.0;
  16859. this.uAng = 0;
  16860. this.vAng = 0;
  16861. this.wAng = 0;
  16862. this.name = url;
  16863. this.url = url;
  16864. this._noMipmap = noMipmap;
  16865. this._invertY = invertY;
  16866. this._samplingMode = samplingMode;
  16867. this._buffer = buffer;
  16868. this._deleteBuffer = deleteBuffer;
  16869. if (!url) {
  16870. return;
  16871. }
  16872. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16873. if (!this._texture) {
  16874. if (!scene.useDelayedTextureLoading) {
  16875. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16876. if (deleteBuffer) {
  16877. delete this._buffer;
  16878. }
  16879. }
  16880. else {
  16881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16882. }
  16883. }
  16884. else {
  16885. BABYLON.Tools.SetImmediate(function () {
  16886. if (onLoad) {
  16887. onLoad();
  16888. }
  16889. });
  16890. }
  16891. }
  16892. Texture.prototype.delayLoad = function () {
  16893. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16894. return;
  16895. }
  16896. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16897. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16898. if (!this._texture) {
  16899. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16900. if (this._deleteBuffer) {
  16901. delete this._buffer;
  16902. }
  16903. }
  16904. };
  16905. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16906. if (!this._texture) {
  16907. return;
  16908. }
  16909. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16910. };
  16911. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16912. x *= this.uScale;
  16913. y *= this.vScale;
  16914. x -= 0.5 * this.uScale;
  16915. y -= 0.5 * this.vScale;
  16916. z -= 0.5;
  16917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16918. t.x += 0.5 * this.uScale + this.uOffset;
  16919. t.y += 0.5 * this.vScale + this.vOffset;
  16920. t.z += 0.5;
  16921. };
  16922. Texture.prototype.getTextureMatrix = function () {
  16923. if (this.uOffset === this._cachedUOffset &&
  16924. this.vOffset === this._cachedVOffset &&
  16925. this.uScale === this._cachedUScale &&
  16926. this.vScale === this._cachedVScale &&
  16927. this.uAng === this._cachedUAng &&
  16928. this.vAng === this._cachedVAng &&
  16929. this.wAng === this._cachedWAng) {
  16930. return this._cachedTextureMatrix;
  16931. }
  16932. this._cachedUOffset = this.uOffset;
  16933. this._cachedVOffset = this.vOffset;
  16934. this._cachedUScale = this.uScale;
  16935. this._cachedVScale = this.vScale;
  16936. this._cachedUAng = this.uAng;
  16937. this._cachedVAng = this.vAng;
  16938. this._cachedWAng = this.wAng;
  16939. if (!this._cachedTextureMatrix) {
  16940. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16941. this._rowGenerationMatrix = new BABYLON.Matrix();
  16942. this._t0 = BABYLON.Vector3.Zero();
  16943. this._t1 = BABYLON.Vector3.Zero();
  16944. this._t2 = BABYLON.Vector3.Zero();
  16945. }
  16946. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16947. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16948. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16949. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16950. this._t1.subtractInPlace(this._t0);
  16951. this._t2.subtractInPlace(this._t0);
  16952. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16953. this._cachedTextureMatrix.m[0] = this._t1.x;
  16954. this._cachedTextureMatrix.m[1] = this._t1.y;
  16955. this._cachedTextureMatrix.m[2] = this._t1.z;
  16956. this._cachedTextureMatrix.m[4] = this._t2.x;
  16957. this._cachedTextureMatrix.m[5] = this._t2.y;
  16958. this._cachedTextureMatrix.m[6] = this._t2.z;
  16959. this._cachedTextureMatrix.m[8] = this._t0.x;
  16960. this._cachedTextureMatrix.m[9] = this._t0.y;
  16961. this._cachedTextureMatrix.m[10] = this._t0.z;
  16962. return this._cachedTextureMatrix;
  16963. };
  16964. Texture.prototype.getReflectionTextureMatrix = function () {
  16965. if (this.uOffset === this._cachedUOffset &&
  16966. this.vOffset === this._cachedVOffset &&
  16967. this.uScale === this._cachedUScale &&
  16968. this.vScale === this._cachedVScale &&
  16969. this.coordinatesMode === this._cachedCoordinatesMode) {
  16970. return this._cachedTextureMatrix;
  16971. }
  16972. if (!this._cachedTextureMatrix) {
  16973. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16974. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16975. }
  16976. this._cachedCoordinatesMode = this.coordinatesMode;
  16977. switch (this.coordinatesMode) {
  16978. case Texture.PLANAR_MODE:
  16979. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16980. this._cachedTextureMatrix[0] = this.uScale;
  16981. this._cachedTextureMatrix[5] = this.vScale;
  16982. this._cachedTextureMatrix[12] = this.uOffset;
  16983. this._cachedTextureMatrix[13] = this.vOffset;
  16984. break;
  16985. case Texture.PROJECTION_MODE:
  16986. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16987. this._projectionModeMatrix.m[0] = 0.5;
  16988. this._projectionModeMatrix.m[5] = -0.5;
  16989. this._projectionModeMatrix.m[10] = 0.0;
  16990. this._projectionModeMatrix.m[12] = 0.5;
  16991. this._projectionModeMatrix.m[13] = 0.5;
  16992. this._projectionModeMatrix.m[14] = 1.0;
  16993. this._projectionModeMatrix.m[15] = 1.0;
  16994. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16995. break;
  16996. default:
  16997. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16998. break;
  16999. }
  17000. return this._cachedTextureMatrix;
  17001. };
  17002. Texture.prototype.clone = function () {
  17003. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17004. // Base texture
  17005. newTexture.hasAlpha = this.hasAlpha;
  17006. newTexture.level = this.level;
  17007. newTexture.wrapU = this.wrapU;
  17008. newTexture.wrapV = this.wrapV;
  17009. newTexture.coordinatesIndex = this.coordinatesIndex;
  17010. newTexture.coordinatesMode = this.coordinatesMode;
  17011. // Texture
  17012. newTexture.uOffset = this.uOffset;
  17013. newTexture.vOffset = this.vOffset;
  17014. newTexture.uScale = this.uScale;
  17015. newTexture.vScale = this.vScale;
  17016. newTexture.uAng = this.uAng;
  17017. newTexture.vAng = this.vAng;
  17018. newTexture.wAng = this.wAng;
  17019. return newTexture;
  17020. };
  17021. Texture.prototype.serialize = function () {
  17022. if (!this.name) {
  17023. return null;
  17024. }
  17025. var serializationObject = _super.prototype.serialize.call(this);
  17026. serializationObject.uOffset = this.uOffset;
  17027. serializationObject.vOffset = this.vOffset;
  17028. serializationObject.uScale = this.uScale;
  17029. serializationObject.vScale = this.vScale;
  17030. serializationObject.uAng = this.uAng;
  17031. serializationObject.vAng = this.vAng;
  17032. serializationObject.wAng = this.wAng;
  17033. return serializationObject;
  17034. };
  17035. // Statics
  17036. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17037. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17038. if (onLoad === void 0) { onLoad = null; }
  17039. if (onError === void 0) { onError = null; }
  17040. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17041. };
  17042. Texture.ParseTexture = function (parsedTexture, scene, rootUrl) {
  17043. if (parsedTexture.isCube) {
  17044. return BABYLON.CubeTexture.ParseCubeTexture(parsedTexture, scene, rootUrl);
  17045. }
  17046. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17047. return null;
  17048. }
  17049. var texture;
  17050. if (parsedTexture.mirrorPlane) {
  17051. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17052. texture._waitingRenderList = parsedTexture.renderList;
  17053. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17054. }
  17055. else if (parsedTexture.isRenderTarget) {
  17056. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17057. texture._waitingRenderList = parsedTexture.renderList;
  17058. }
  17059. else {
  17060. if (parsedTexture.base64String) {
  17061. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17062. }
  17063. else {
  17064. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17065. }
  17066. }
  17067. texture.name = parsedTexture.name;
  17068. texture.hasAlpha = parsedTexture.hasAlpha;
  17069. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17070. texture.level = parsedTexture.level;
  17071. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17072. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17073. texture.uOffset = parsedTexture.uOffset;
  17074. texture.vOffset = parsedTexture.vOffset;
  17075. texture.uScale = parsedTexture.uScale;
  17076. texture.vScale = parsedTexture.vScale;
  17077. texture.uAng = parsedTexture.uAng;
  17078. texture.vAng = parsedTexture.vAng;
  17079. texture.wAng = parsedTexture.wAng;
  17080. texture.wrapU = parsedTexture.wrapU;
  17081. texture.wrapV = parsedTexture.wrapV;
  17082. // Animations
  17083. if (parsedTexture.animations) {
  17084. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17085. var parsedAnimation = parsedTexture.animations[animationIndex];
  17086. texture.animations.push(BABYLON.Animation.ParseAnimation(parsedAnimation));
  17087. }
  17088. }
  17089. return texture;
  17090. };
  17091. // Constants
  17092. Texture.NEAREST_SAMPLINGMODE = 1;
  17093. Texture.BILINEAR_SAMPLINGMODE = 2;
  17094. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17095. Texture.EXPLICIT_MODE = 0;
  17096. Texture.SPHERICAL_MODE = 1;
  17097. Texture.PLANAR_MODE = 2;
  17098. Texture.CUBIC_MODE = 3;
  17099. Texture.PROJECTION_MODE = 4;
  17100. Texture.SKYBOX_MODE = 5;
  17101. Texture.INVCUBIC_MODE = 6;
  17102. Texture.EQUIRECTANGULAR_MODE = 7;
  17103. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17104. Texture.CLAMP_ADDRESSMODE = 0;
  17105. Texture.WRAP_ADDRESSMODE = 1;
  17106. Texture.MIRROR_ADDRESSMODE = 2;
  17107. return Texture;
  17108. })(BABYLON.BaseTexture);
  17109. BABYLON.Texture = Texture;
  17110. })(BABYLON || (BABYLON = {}));
  17111. var BABYLON;
  17112. (function (BABYLON) {
  17113. var CubeTexture = (function (_super) {
  17114. __extends(CubeTexture, _super);
  17115. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17116. _super.call(this, scene);
  17117. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17118. this.name = rootUrl;
  17119. this.url = rootUrl;
  17120. this._noMipmap = noMipmap;
  17121. this.hasAlpha = false;
  17122. if (!rootUrl) {
  17123. return;
  17124. }
  17125. this._texture = this._getFromCache(rootUrl, noMipmap);
  17126. if (!extensions) {
  17127. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17128. }
  17129. this._extensions = extensions;
  17130. if (!this._texture) {
  17131. if (!scene.useDelayedTextureLoading) {
  17132. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17133. }
  17134. else {
  17135. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17136. }
  17137. }
  17138. this.isCube = true;
  17139. this._textureMatrix = BABYLON.Matrix.Identity();
  17140. }
  17141. CubeTexture.prototype.clone = function () {
  17142. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17143. // Base texture
  17144. newTexture.level = this.level;
  17145. newTexture.wrapU = this.wrapU;
  17146. newTexture.wrapV = this.wrapV;
  17147. newTexture.coordinatesIndex = this.coordinatesIndex;
  17148. newTexture.coordinatesMode = this.coordinatesMode;
  17149. return newTexture;
  17150. };
  17151. // Methods
  17152. CubeTexture.prototype.delayLoad = function () {
  17153. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17154. return;
  17155. }
  17156. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17157. this._texture = this._getFromCache(this.url, this._noMipmap);
  17158. if (!this._texture) {
  17159. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17160. }
  17161. };
  17162. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17163. return this._textureMatrix;
  17164. };
  17165. CubeTexture.ParseCubeTexture = function (parsedTexture, scene, rootUrl) {
  17166. var texture = null;
  17167. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17168. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17169. texture.name = parsedTexture.name;
  17170. texture.hasAlpha = parsedTexture.hasAlpha;
  17171. texture.level = parsedTexture.level;
  17172. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17173. }
  17174. return texture;
  17175. };
  17176. CubeTexture.prototype.serialize = function () {
  17177. if (!this.name) {
  17178. return null;
  17179. }
  17180. var serializationObject = {};
  17181. serializationObject.name = this.name;
  17182. serializationObject.hasAlpha = this.hasAlpha;
  17183. serializationObject.isCube = true;
  17184. serializationObject.level = this.level;
  17185. serializationObject.coordinatesMode = this.coordinatesMode;
  17186. return serializationObject;
  17187. };
  17188. return CubeTexture;
  17189. })(BABYLON.BaseTexture);
  17190. BABYLON.CubeTexture = CubeTexture;
  17191. })(BABYLON || (BABYLON = {}));
  17192. var BABYLON;
  17193. (function (BABYLON) {
  17194. var RenderTargetTexture = (function (_super) {
  17195. __extends(RenderTargetTexture, _super);
  17196. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17197. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17198. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17199. if (isCube === void 0) { isCube = false; }
  17200. _super.call(this, null, scene, !generateMipMaps);
  17201. this.isCube = isCube;
  17202. this.renderList = new Array();
  17203. this.renderParticles = true;
  17204. this.renderSprites = false;
  17205. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17206. this._currentRefreshId = -1;
  17207. this._refreshRate = 1;
  17208. this.name = name;
  17209. this.isRenderTarget = true;
  17210. this._size = size;
  17211. this._generateMipMaps = generateMipMaps;
  17212. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17213. if (isCube) {
  17214. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17215. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17216. this._textureMatrix = BABYLON.Matrix.Identity();
  17217. }
  17218. else {
  17219. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17220. }
  17221. // Rendering groups
  17222. this._renderingManager = new BABYLON.RenderingManager(scene);
  17223. }
  17224. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17225. get: function () {
  17226. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17232. get: function () {
  17233. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17234. },
  17235. enumerable: true,
  17236. configurable: true
  17237. });
  17238. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17239. get: function () {
  17240. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17241. },
  17242. enumerable: true,
  17243. configurable: true
  17244. });
  17245. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17246. this._currentRefreshId = -1;
  17247. };
  17248. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17249. get: function () {
  17250. return this._refreshRate;
  17251. },
  17252. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17253. set: function (value) {
  17254. this._refreshRate = value;
  17255. this.resetRefreshCounter();
  17256. },
  17257. enumerable: true,
  17258. configurable: true
  17259. });
  17260. RenderTargetTexture.prototype._shouldRender = function () {
  17261. if (this._currentRefreshId === -1) {
  17262. this._currentRefreshId = 1;
  17263. return true;
  17264. }
  17265. if (this.refreshRate === this._currentRefreshId) {
  17266. this._currentRefreshId = 1;
  17267. return true;
  17268. }
  17269. this._currentRefreshId++;
  17270. return false;
  17271. };
  17272. RenderTargetTexture.prototype.isReady = function () {
  17273. if (!this.getScene().renderTargetsEnabled) {
  17274. return false;
  17275. }
  17276. return _super.prototype.isReady.call(this);
  17277. };
  17278. RenderTargetTexture.prototype.getRenderSize = function () {
  17279. return this._size;
  17280. };
  17281. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17282. get: function () {
  17283. return true;
  17284. },
  17285. enumerable: true,
  17286. configurable: true
  17287. });
  17288. RenderTargetTexture.prototype.scale = function (ratio) {
  17289. var newSize = this._size * ratio;
  17290. this.resize(newSize, this._generateMipMaps);
  17291. };
  17292. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17293. if (this.isCube) {
  17294. return this._textureMatrix;
  17295. }
  17296. return _super.prototype.getReflectionTextureMatrix.call(this);
  17297. };
  17298. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17299. this.releaseInternalTexture();
  17300. if (this.isCube) {
  17301. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17302. }
  17303. else {
  17304. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17305. }
  17306. };
  17307. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17308. var scene = this.getScene();
  17309. if (this._waitingRenderList) {
  17310. this.renderList = [];
  17311. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17312. var id = this._waitingRenderList[index];
  17313. this.renderList.push(scene.getMeshByID(id));
  17314. }
  17315. delete this._waitingRenderList;
  17316. }
  17317. if (this.renderList && this.renderList.length === 0) {
  17318. return;
  17319. }
  17320. // Prepare renderingManager
  17321. this._renderingManager.reset();
  17322. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17323. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17324. var mesh = currentRenderList[meshIndex];
  17325. if (mesh) {
  17326. if (!mesh.isReady()) {
  17327. // Reset _currentRefreshId
  17328. this.resetRefreshCounter();
  17329. continue;
  17330. }
  17331. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17332. mesh._activate(scene.getRenderId());
  17333. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17334. var subMesh = mesh.subMeshes[subIndex];
  17335. scene._activeIndices += subMesh.indexCount;
  17336. this._renderingManager.dispatch(subMesh);
  17337. }
  17338. }
  17339. }
  17340. }
  17341. if (this.isCube) {
  17342. for (var face = 0; face < 6; face++) {
  17343. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17344. }
  17345. }
  17346. else {
  17347. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17348. }
  17349. if (this.onAfterUnbind) {
  17350. this.onAfterUnbind();
  17351. }
  17352. scene.resetCachedMaterial();
  17353. };
  17354. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17355. var scene = this.getScene();
  17356. var engine = scene.getEngine();
  17357. // Bind
  17358. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17359. if (this.isCube) {
  17360. engine.bindFramebuffer(this._texture, faceIndex);
  17361. }
  17362. else {
  17363. engine.bindFramebuffer(this._texture);
  17364. }
  17365. }
  17366. if (this.onBeforeRender) {
  17367. this.onBeforeRender(faceIndex);
  17368. }
  17369. // Clear
  17370. if (this.onClear) {
  17371. this.onClear(engine);
  17372. }
  17373. else {
  17374. engine.clear(scene.clearColor, true, true);
  17375. }
  17376. if (!this._doNotChangeAspectRatio) {
  17377. scene.updateTransformMatrix(true);
  17378. }
  17379. // Render
  17380. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17381. if (useCameraPostProcess) {
  17382. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17383. }
  17384. if (!this._doNotChangeAspectRatio) {
  17385. scene.updateTransformMatrix(true);
  17386. }
  17387. if (this.onAfterRender) {
  17388. this.onAfterRender(faceIndex);
  17389. }
  17390. // Dump ?
  17391. if (dumpForDebug) {
  17392. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17393. }
  17394. // Unbind
  17395. if (!this.isCube || faceIndex === 5) {
  17396. if (this.isCube) {
  17397. if (faceIndex === 5) {
  17398. engine.generateMipMapsForCubemap(this._texture);
  17399. }
  17400. }
  17401. engine.unBindFramebuffer(this._texture, this.isCube);
  17402. }
  17403. };
  17404. RenderTargetTexture.prototype.clone = function () {
  17405. var textureSize = this.getSize();
  17406. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17407. // Base texture
  17408. newTexture.hasAlpha = this.hasAlpha;
  17409. newTexture.level = this.level;
  17410. // RenderTarget Texture
  17411. newTexture.coordinatesMode = this.coordinatesMode;
  17412. newTexture.renderList = this.renderList.slice(0);
  17413. return newTexture;
  17414. };
  17415. RenderTargetTexture.prototype.serialize = function () {
  17416. if (!this.name) {
  17417. return null;
  17418. }
  17419. var serializationObject = _super.prototype.serialize.call(this);
  17420. serializationObject.renderTargetSize = this.getRenderSize();
  17421. serializationObject.renderList = [];
  17422. for (var index = 0; index < this.renderList.length; index++) {
  17423. serializationObject.renderList.push(this.renderList[index].id);
  17424. }
  17425. return serializationObject;
  17426. };
  17427. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17428. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17429. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17430. return RenderTargetTexture;
  17431. })(BABYLON.Texture);
  17432. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17433. })(BABYLON || (BABYLON = {}));
  17434. var BABYLON;
  17435. (function (BABYLON) {
  17436. var ProceduralTexture = (function (_super) {
  17437. __extends(ProceduralTexture, _super);
  17438. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17440. _super.call(this, null, scene, !generateMipMaps);
  17441. this.isEnabled = true;
  17442. this._currentRefreshId = -1;
  17443. this._refreshRate = 1;
  17444. this._vertexDeclaration = [2];
  17445. this._vertexStrideSize = 2 * 4;
  17446. this._uniforms = new Array();
  17447. this._samplers = new Array();
  17448. this._textures = new Array();
  17449. this._floats = new Array();
  17450. this._floatsArrays = {};
  17451. this._colors3 = new Array();
  17452. this._colors4 = new Array();
  17453. this._vectors2 = new Array();
  17454. this._vectors3 = new Array();
  17455. this._matrices = new Array();
  17456. this._fallbackTextureUsed = false;
  17457. scene._proceduralTextures.push(this);
  17458. this.name = name;
  17459. this.isRenderTarget = true;
  17460. this._size = size;
  17461. this._generateMipMaps = generateMipMaps;
  17462. this.setFragment(fragment);
  17463. this._fallbackTexture = fallbackTexture;
  17464. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17465. // VBO
  17466. var vertices = [];
  17467. vertices.push(1, 1);
  17468. vertices.push(-1, 1);
  17469. vertices.push(-1, -1);
  17470. vertices.push(1, -1);
  17471. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17472. // Indices
  17473. var indices = [];
  17474. indices.push(0);
  17475. indices.push(1);
  17476. indices.push(2);
  17477. indices.push(0);
  17478. indices.push(2);
  17479. indices.push(3);
  17480. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17481. }
  17482. ProceduralTexture.prototype.reset = function () {
  17483. if (this._effect === undefined) {
  17484. return;
  17485. }
  17486. var engine = this.getScene().getEngine();
  17487. engine._releaseEffect(this._effect);
  17488. };
  17489. ProceduralTexture.prototype.isReady = function () {
  17490. var _this = this;
  17491. var engine = this.getScene().getEngine();
  17492. var shaders;
  17493. if (!this._fragment) {
  17494. return false;
  17495. }
  17496. if (this._fallbackTextureUsed) {
  17497. return true;
  17498. }
  17499. if (this._fragment.fragmentElement !== undefined) {
  17500. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17501. }
  17502. else {
  17503. shaders = { vertex: "procedural", fragment: this._fragment };
  17504. }
  17505. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17506. _this.releaseInternalTexture();
  17507. if (_this._fallbackTexture) {
  17508. _this._texture = _this._fallbackTexture._texture;
  17509. _this._texture.references++;
  17510. }
  17511. _this._fallbackTextureUsed = true;
  17512. });
  17513. return this._effect.isReady();
  17514. };
  17515. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17516. this._currentRefreshId = -1;
  17517. };
  17518. ProceduralTexture.prototype.setFragment = function (fragment) {
  17519. this._fragment = fragment;
  17520. };
  17521. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17522. get: function () {
  17523. return this._refreshRate;
  17524. },
  17525. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17526. set: function (value) {
  17527. this._refreshRate = value;
  17528. this.resetRefreshCounter();
  17529. },
  17530. enumerable: true,
  17531. configurable: true
  17532. });
  17533. ProceduralTexture.prototype._shouldRender = function () {
  17534. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17535. return false;
  17536. }
  17537. if (this._fallbackTextureUsed) {
  17538. return false;
  17539. }
  17540. if (this._currentRefreshId === -1) {
  17541. this._currentRefreshId = 1;
  17542. return true;
  17543. }
  17544. if (this.refreshRate === this._currentRefreshId) {
  17545. this._currentRefreshId = 1;
  17546. return true;
  17547. }
  17548. this._currentRefreshId++;
  17549. return false;
  17550. };
  17551. ProceduralTexture.prototype.getRenderSize = function () {
  17552. return this._size;
  17553. };
  17554. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17555. if (this._fallbackTextureUsed) {
  17556. return;
  17557. }
  17558. this.releaseInternalTexture();
  17559. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17560. };
  17561. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17562. if (this._uniforms.indexOf(uniformName) === -1) {
  17563. this._uniforms.push(uniformName);
  17564. }
  17565. };
  17566. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17567. if (this._samplers.indexOf(name) === -1) {
  17568. this._samplers.push(name);
  17569. }
  17570. this._textures[name] = texture;
  17571. return this;
  17572. };
  17573. ProceduralTexture.prototype.setFloat = function (name, value) {
  17574. this._checkUniform(name);
  17575. this._floats[name] = value;
  17576. return this;
  17577. };
  17578. ProceduralTexture.prototype.setFloats = function (name, value) {
  17579. this._checkUniform(name);
  17580. this._floatsArrays[name] = value;
  17581. return this;
  17582. };
  17583. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17584. this._checkUniform(name);
  17585. this._colors3[name] = value;
  17586. return this;
  17587. };
  17588. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17589. this._checkUniform(name);
  17590. this._colors4[name] = value;
  17591. return this;
  17592. };
  17593. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17594. this._checkUniform(name);
  17595. this._vectors2[name] = value;
  17596. return this;
  17597. };
  17598. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17599. this._checkUniform(name);
  17600. this._vectors3[name] = value;
  17601. return this;
  17602. };
  17603. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17604. this._checkUniform(name);
  17605. this._matrices[name] = value;
  17606. return this;
  17607. };
  17608. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17609. var scene = this.getScene();
  17610. var engine = scene.getEngine();
  17611. engine.bindFramebuffer(this._texture);
  17612. // Clear
  17613. engine.clear(scene.clearColor, true, true);
  17614. // Render
  17615. engine.enableEffect(this._effect);
  17616. engine.setState(false);
  17617. // Texture
  17618. for (var name in this._textures) {
  17619. this._effect.setTexture(name, this._textures[name]);
  17620. }
  17621. // Float
  17622. for (name in this._floats) {
  17623. this._effect.setFloat(name, this._floats[name]);
  17624. }
  17625. // Floats
  17626. for (name in this._floatsArrays) {
  17627. this._effect.setArray(name, this._floatsArrays[name]);
  17628. }
  17629. // Color3
  17630. for (name in this._colors3) {
  17631. this._effect.setColor3(name, this._colors3[name]);
  17632. }
  17633. // Color4
  17634. for (name in this._colors4) {
  17635. var color = this._colors4[name];
  17636. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17637. }
  17638. // Vector2
  17639. for (name in this._vectors2) {
  17640. this._effect.setVector2(name, this._vectors2[name]);
  17641. }
  17642. // Vector3
  17643. for (name in this._vectors3) {
  17644. this._effect.setVector3(name, this._vectors3[name]);
  17645. }
  17646. // Matrix
  17647. for (name in this._matrices) {
  17648. this._effect.setMatrix(name, this._matrices[name]);
  17649. }
  17650. // VBOs
  17651. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17652. // Draw order
  17653. engine.draw(true, 0, 6);
  17654. // Unbind
  17655. engine.unBindFramebuffer(this._texture);
  17656. };
  17657. ProceduralTexture.prototype.clone = function () {
  17658. var textureSize = this.getSize();
  17659. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17660. // Base texture
  17661. newTexture.hasAlpha = this.hasAlpha;
  17662. newTexture.level = this.level;
  17663. // RenderTarget Texture
  17664. newTexture.coordinatesMode = this.coordinatesMode;
  17665. return newTexture;
  17666. };
  17667. ProceduralTexture.prototype.dispose = function () {
  17668. var index = this.getScene()._proceduralTextures.indexOf(this);
  17669. if (index >= 0) {
  17670. this.getScene()._proceduralTextures.splice(index, 1);
  17671. }
  17672. _super.prototype.dispose.call(this);
  17673. };
  17674. return ProceduralTexture;
  17675. })(BABYLON.Texture);
  17676. BABYLON.ProceduralTexture = ProceduralTexture;
  17677. })(BABYLON || (BABYLON = {}));
  17678. var BABYLON;
  17679. (function (BABYLON) {
  17680. var MirrorTexture = (function (_super) {
  17681. __extends(MirrorTexture, _super);
  17682. function MirrorTexture(name, size, scene, generateMipMaps) {
  17683. var _this = this;
  17684. _super.call(this, name, size, scene, generateMipMaps, true);
  17685. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17686. this._transformMatrix = BABYLON.Matrix.Zero();
  17687. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17688. this.onBeforeRender = function () {
  17689. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17690. _this._savedViewMatrix = scene.getViewMatrix();
  17691. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17692. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17693. scene.clipPlane = _this.mirrorPlane;
  17694. scene.getEngine().cullBackFaces = false;
  17695. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17696. };
  17697. this.onAfterRender = function () {
  17698. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17699. scene.getEngine().cullBackFaces = true;
  17700. scene._mirroredCameraPosition = null;
  17701. delete scene.clipPlane;
  17702. };
  17703. }
  17704. MirrorTexture.prototype.clone = function () {
  17705. var textureSize = this.getSize();
  17706. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17707. // Base texture
  17708. newTexture.hasAlpha = this.hasAlpha;
  17709. newTexture.level = this.level;
  17710. // Mirror Texture
  17711. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17712. newTexture.renderList = this.renderList.slice(0);
  17713. return newTexture;
  17714. };
  17715. MirrorTexture.prototype.serialize = function () {
  17716. if (!this.name) {
  17717. return null;
  17718. }
  17719. var serializationObject = _super.prototype.serialize.call(this);
  17720. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17721. return serializationObject;
  17722. };
  17723. return MirrorTexture;
  17724. })(BABYLON.RenderTargetTexture);
  17725. BABYLON.MirrorTexture = MirrorTexture;
  17726. })(BABYLON || (BABYLON = {}));
  17727. var BABYLON;
  17728. (function (BABYLON) {
  17729. var DynamicTexture = (function (_super) {
  17730. __extends(DynamicTexture, _super);
  17731. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17733. _super.call(this, null, scene, !generateMipMaps);
  17734. this.name = name;
  17735. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17736. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17737. this._generateMipMaps = generateMipMaps;
  17738. if (options.getContext) {
  17739. this._canvas = options;
  17740. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17741. }
  17742. else {
  17743. this._canvas = document.createElement("canvas");
  17744. if (options.width) {
  17745. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17746. }
  17747. else {
  17748. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17749. }
  17750. }
  17751. var textureSize = this.getSize();
  17752. this._canvas.width = textureSize.width;
  17753. this._canvas.height = textureSize.height;
  17754. this._context = this._canvas.getContext("2d");
  17755. }
  17756. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17757. get: function () {
  17758. return true;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. DynamicTexture.prototype.scale = function (ratio) {
  17764. var textureSize = this.getSize();
  17765. textureSize.width *= ratio;
  17766. textureSize.height *= ratio;
  17767. this._canvas.width = textureSize.width;
  17768. this._canvas.height = textureSize.height;
  17769. this.releaseInternalTexture();
  17770. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17771. };
  17772. DynamicTexture.prototype.getContext = function () {
  17773. return this._context;
  17774. };
  17775. DynamicTexture.prototype.clear = function () {
  17776. var size = this.getSize();
  17777. this._context.fillRect(0, 0, size.width, size.height);
  17778. };
  17779. DynamicTexture.prototype.update = function (invertY) {
  17780. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17781. };
  17782. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17783. if (update === void 0) { update = true; }
  17784. var size = this.getSize();
  17785. if (clearColor) {
  17786. this._context.fillStyle = clearColor;
  17787. this._context.fillRect(0, 0, size.width, size.height);
  17788. }
  17789. this._context.font = font;
  17790. if (x === null) {
  17791. var textSize = this._context.measureText(text);
  17792. x = (size.width - textSize.width) / 2;
  17793. }
  17794. this._context.fillStyle = color;
  17795. this._context.fillText(text, x, y);
  17796. if (update) {
  17797. this.update(invertY);
  17798. }
  17799. };
  17800. DynamicTexture.prototype.clone = function () {
  17801. var textureSize = this.getSize();
  17802. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17803. // Base texture
  17804. newTexture.hasAlpha = this.hasAlpha;
  17805. newTexture.level = this.level;
  17806. // Dynamic Texture
  17807. newTexture.wrapU = this.wrapU;
  17808. newTexture.wrapV = this.wrapV;
  17809. return newTexture;
  17810. };
  17811. return DynamicTexture;
  17812. })(BABYLON.Texture);
  17813. BABYLON.DynamicTexture = DynamicTexture;
  17814. })(BABYLON || (BABYLON = {}));
  17815. var BABYLON;
  17816. (function (BABYLON) {
  17817. var VideoTexture = (function (_super) {
  17818. __extends(VideoTexture, _super);
  17819. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17820. var _this = this;
  17821. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17822. if (invertY === void 0) { invertY = false; }
  17823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17824. _super.call(this, null, scene, !generateMipMaps, invertY);
  17825. this._autoLaunch = true;
  17826. this.name = name;
  17827. this.video = document.createElement("video");
  17828. this.video.autoplay = false;
  17829. this.video.loop = true;
  17830. this.video.addEventListener("canplaythrough", function () {
  17831. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17832. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17833. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17834. }
  17835. else {
  17836. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17837. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17838. generateMipMaps = false;
  17839. }
  17840. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17841. _this._texture.isReady = true;
  17842. });
  17843. urls.forEach(function (url) {
  17844. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17845. var source = document.createElement("source");
  17846. source.src = url;
  17847. _this.video.appendChild(source);
  17848. });
  17849. this._lastUpdate = BABYLON.Tools.Now;
  17850. }
  17851. VideoTexture.prototype.update = function () {
  17852. if (this._autoLaunch) {
  17853. this._autoLaunch = false;
  17854. this.video.play();
  17855. }
  17856. var now = BABYLON.Tools.Now;
  17857. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17858. return false;
  17859. }
  17860. this._lastUpdate = now;
  17861. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17862. return true;
  17863. };
  17864. return VideoTexture;
  17865. })(BABYLON.Texture);
  17866. BABYLON.VideoTexture = VideoTexture;
  17867. })(BABYLON || (BABYLON = {}));
  17868. var BABYLON;
  17869. (function (BABYLON) {
  17870. var CustomProceduralTexture = (function (_super) {
  17871. __extends(CustomProceduralTexture, _super);
  17872. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17873. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17874. this._animate = true;
  17875. this._time = 0;
  17876. this._texturePath = texturePath;
  17877. //Try to load json
  17878. this.loadJson(texturePath);
  17879. this.refreshRate = 1;
  17880. }
  17881. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17882. var _this = this;
  17883. var that = this;
  17884. function noConfigFile() {
  17885. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17886. try {
  17887. that.setFragment(that._texturePath);
  17888. }
  17889. catch (ex) {
  17890. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17891. }
  17892. }
  17893. var configFileUrl = jsonUrl + "/config.json";
  17894. var xhr = new XMLHttpRequest();
  17895. xhr.open("GET", configFileUrl, true);
  17896. xhr.addEventListener("load", function () {
  17897. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17898. try {
  17899. _this._config = JSON.parse(xhr.response);
  17900. _this.updateShaderUniforms();
  17901. _this.updateTextures();
  17902. _this.setFragment(_this._texturePath + "/custom");
  17903. _this._animate = _this._config.animate;
  17904. _this.refreshRate = _this._config.refreshrate;
  17905. }
  17906. catch (ex) {
  17907. noConfigFile();
  17908. }
  17909. }
  17910. else {
  17911. noConfigFile();
  17912. }
  17913. }, false);
  17914. xhr.addEventListener("error", function () {
  17915. noConfigFile();
  17916. }, false);
  17917. try {
  17918. xhr.send();
  17919. }
  17920. catch (ex) {
  17921. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17922. }
  17923. };
  17924. CustomProceduralTexture.prototype.isReady = function () {
  17925. if (!_super.prototype.isReady.call(this)) {
  17926. return false;
  17927. }
  17928. for (var name in this._textures) {
  17929. var texture = this._textures[name];
  17930. if (!texture.isReady()) {
  17931. return false;
  17932. }
  17933. }
  17934. return true;
  17935. };
  17936. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17937. if (this._animate) {
  17938. this._time += this.getScene().getAnimationRatio() * 0.03;
  17939. this.updateShaderUniforms();
  17940. }
  17941. _super.prototype.render.call(this, useCameraPostProcess);
  17942. };
  17943. CustomProceduralTexture.prototype.updateTextures = function () {
  17944. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17945. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17946. }
  17947. };
  17948. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17949. if (this._config) {
  17950. for (var j = 0; j < this._config.uniforms.length; j++) {
  17951. var uniform = this._config.uniforms[j];
  17952. switch (uniform.type) {
  17953. case "float":
  17954. this.setFloat(uniform.name, uniform.value);
  17955. break;
  17956. case "color3":
  17957. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17958. break;
  17959. case "color4":
  17960. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17961. break;
  17962. case "vector2":
  17963. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17964. break;
  17965. case "vector3":
  17966. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17967. break;
  17968. }
  17969. }
  17970. }
  17971. this.setFloat("time", this._time);
  17972. };
  17973. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17974. get: function () {
  17975. return this._animate;
  17976. },
  17977. set: function (value) {
  17978. this._animate = value;
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. return CustomProceduralTexture;
  17984. })(BABYLON.ProceduralTexture);
  17985. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17986. })(BABYLON || (BABYLON = {}));
  17987. var BABYLON;
  17988. (function (BABYLON) {
  17989. var EffectFallbacks = (function () {
  17990. function EffectFallbacks() {
  17991. this._defines = {};
  17992. this._currentRank = 32;
  17993. this._maxRank = -1;
  17994. }
  17995. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17996. if (!this._defines[rank]) {
  17997. if (rank < this._currentRank) {
  17998. this._currentRank = rank;
  17999. }
  18000. if (rank > this._maxRank) {
  18001. this._maxRank = rank;
  18002. }
  18003. this._defines[rank] = new Array();
  18004. }
  18005. this._defines[rank].push(define);
  18006. };
  18007. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18008. this._meshRank = rank;
  18009. this._mesh = mesh;
  18010. if (rank > this._maxRank) {
  18011. this._maxRank = rank;
  18012. }
  18013. };
  18014. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18015. get: function () {
  18016. return this._currentRank <= this._maxRank;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18022. var currentFallbacks = this._defines[this._currentRank];
  18023. for (var index = 0; index < currentFallbacks.length; index++) {
  18024. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18025. }
  18026. if (this._mesh && this._currentRank === this._meshRank) {
  18027. this._mesh.computeBonesUsingShaders = false;
  18028. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18029. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18030. }
  18031. this._currentRank++;
  18032. return currentDefines;
  18033. };
  18034. return EffectFallbacks;
  18035. })();
  18036. BABYLON.EffectFallbacks = EffectFallbacks;
  18037. var Effect = (function () {
  18038. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18039. var _this = this;
  18040. this._isReady = false;
  18041. this._compilationError = "";
  18042. this._valueCache = [];
  18043. this._engine = engine;
  18044. this.name = baseName;
  18045. this.defines = defines;
  18046. this._uniformsNames = uniformsNames.concat(samplers);
  18047. this._samplers = samplers;
  18048. this._attributesNames = attributesNames;
  18049. this.onError = onError;
  18050. this.onCompiled = onCompiled;
  18051. var vertexSource;
  18052. var fragmentSource;
  18053. if (baseName.vertexElement) {
  18054. vertexSource = document.getElementById(baseName.vertexElement);
  18055. if (!vertexSource) {
  18056. vertexSource = baseName.vertexElement;
  18057. }
  18058. }
  18059. else {
  18060. vertexSource = baseName.vertex || baseName;
  18061. }
  18062. if (baseName.fragmentElement) {
  18063. fragmentSource = document.getElementById(baseName.fragmentElement);
  18064. if (!fragmentSource) {
  18065. fragmentSource = baseName.fragmentElement;
  18066. }
  18067. }
  18068. else {
  18069. fragmentSource = baseName.fragment || baseName;
  18070. }
  18071. this._loadVertexShader(vertexSource, function (vertexCode) {
  18072. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18073. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18074. });
  18075. });
  18076. }
  18077. // Properties
  18078. Effect.prototype.isReady = function () {
  18079. return this._isReady;
  18080. };
  18081. Effect.prototype.getProgram = function () {
  18082. return this._program;
  18083. };
  18084. Effect.prototype.getAttributesNames = function () {
  18085. return this._attributesNames;
  18086. };
  18087. Effect.prototype.getAttributeLocation = function (index) {
  18088. return this._attributes[index];
  18089. };
  18090. Effect.prototype.getAttributeLocationByName = function (name) {
  18091. var index = this._attributesNames.indexOf(name);
  18092. return this._attributes[index];
  18093. };
  18094. Effect.prototype.getAttributesCount = function () {
  18095. return this._attributes.length;
  18096. };
  18097. Effect.prototype.getUniformIndex = function (uniformName) {
  18098. return this._uniformsNames.indexOf(uniformName);
  18099. };
  18100. Effect.prototype.getUniform = function (uniformName) {
  18101. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18102. };
  18103. Effect.prototype.getSamplers = function () {
  18104. return this._samplers;
  18105. };
  18106. Effect.prototype.getCompilationError = function () {
  18107. return this._compilationError;
  18108. };
  18109. // Methods
  18110. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18111. // DOM element ?
  18112. if (vertex instanceof HTMLElement) {
  18113. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18114. callback(vertexCode);
  18115. return;
  18116. }
  18117. // Is in local store ?
  18118. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18119. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18120. return;
  18121. }
  18122. var vertexShaderUrl;
  18123. if (vertex[0] === "." || vertex[0] === "/") {
  18124. vertexShaderUrl = vertex;
  18125. }
  18126. else {
  18127. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18128. }
  18129. // Vertex shader
  18130. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18131. };
  18132. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18133. // DOM element ?
  18134. if (fragment instanceof HTMLElement) {
  18135. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18136. callback(fragmentCode);
  18137. return;
  18138. }
  18139. // Is in local store ?
  18140. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18141. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18142. return;
  18143. }
  18144. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18145. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18146. return;
  18147. }
  18148. var fragmentShaderUrl;
  18149. if (fragment[0] === "." || fragment[0] === "/") {
  18150. fragmentShaderUrl = fragment;
  18151. }
  18152. else {
  18153. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18154. }
  18155. // Fragment shader
  18156. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18157. };
  18158. Effect.prototype._dumpShadersName = function () {
  18159. if (this.name.vertexElement) {
  18160. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18161. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18162. }
  18163. else if (this.name.vertex) {
  18164. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18165. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18166. }
  18167. else {
  18168. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18169. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18170. }
  18171. };
  18172. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18173. try {
  18174. var engine = this._engine;
  18175. if (!engine.getCaps().highPrecisionShaderSupported) {
  18176. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18177. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18178. }
  18179. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18180. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18181. this._attributes = engine.getAttributes(this._program, attributesNames);
  18182. for (var index = 0; index < this._samplers.length; index++) {
  18183. var sampler = this.getUniform(this._samplers[index]);
  18184. if (sampler == null) {
  18185. this._samplers.splice(index, 1);
  18186. index--;
  18187. }
  18188. }
  18189. engine.bindSamplers(this);
  18190. this._isReady = true;
  18191. if (this.onCompiled) {
  18192. this.onCompiled(this);
  18193. }
  18194. }
  18195. catch (e) {
  18196. // Is it a problem with precision?
  18197. if (e.message.indexOf("highp") !== -1) {
  18198. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18199. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18200. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18201. return;
  18202. }
  18203. // Let's go through fallbacks then
  18204. if (fallbacks && fallbacks.isMoreFallbacks) {
  18205. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18206. this._dumpShadersName();
  18207. defines = fallbacks.reduce(defines);
  18208. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18209. }
  18210. else {
  18211. BABYLON.Tools.Error("Unable to compile effect: ");
  18212. this._dumpShadersName();
  18213. BABYLON.Tools.Error("Defines: " + defines);
  18214. BABYLON.Tools.Error("Error: " + e.message);
  18215. this._compilationError = e.message;
  18216. if (this.onError) {
  18217. this.onError(this, this._compilationError);
  18218. }
  18219. }
  18220. }
  18221. };
  18222. Object.defineProperty(Effect.prototype, "isSupported", {
  18223. get: function () {
  18224. return this._compilationError === "";
  18225. },
  18226. enumerable: true,
  18227. configurable: true
  18228. });
  18229. Effect.prototype._bindTexture = function (channel, texture) {
  18230. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18231. };
  18232. Effect.prototype.setTexture = function (channel, texture) {
  18233. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18234. };
  18235. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18236. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18237. };
  18238. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18239. if (!this._valueCache[uniformName]) {
  18240. this._valueCache[uniformName] = new BABYLON.Matrix();
  18241. }
  18242. for (var index = 0; index < 16; index++) {
  18243. this._valueCache[uniformName].m[index] = matrix.m[index];
  18244. }
  18245. };
  18246. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18247. if (!this._valueCache[uniformName]) {
  18248. this._valueCache[uniformName] = [x, y];
  18249. return;
  18250. }
  18251. this._valueCache[uniformName][0] = x;
  18252. this._valueCache[uniformName][1] = y;
  18253. };
  18254. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18255. if (!this._valueCache[uniformName]) {
  18256. this._valueCache[uniformName] = [x, y, z];
  18257. return;
  18258. }
  18259. this._valueCache[uniformName][0] = x;
  18260. this._valueCache[uniformName][1] = y;
  18261. this._valueCache[uniformName][2] = z;
  18262. };
  18263. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18264. if (!this._valueCache[uniformName]) {
  18265. this._valueCache[uniformName] = [x, y, z, w];
  18266. return;
  18267. }
  18268. this._valueCache[uniformName][0] = x;
  18269. this._valueCache[uniformName][1] = y;
  18270. this._valueCache[uniformName][2] = z;
  18271. this._valueCache[uniformName][3] = w;
  18272. };
  18273. Effect.prototype.setArray = function (uniformName, array) {
  18274. this._engine.setArray(this.getUniform(uniformName), array);
  18275. return this;
  18276. };
  18277. Effect.prototype.setArray2 = function (uniformName, array) {
  18278. this._engine.setArray2(this.getUniform(uniformName), array);
  18279. return this;
  18280. };
  18281. Effect.prototype.setArray3 = function (uniformName, array) {
  18282. this._engine.setArray3(this.getUniform(uniformName), array);
  18283. return this;
  18284. };
  18285. Effect.prototype.setArray4 = function (uniformName, array) {
  18286. this._engine.setArray4(this.getUniform(uniformName), array);
  18287. return this;
  18288. };
  18289. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18290. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18291. return this;
  18292. };
  18293. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18294. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18295. return this;
  18296. this._cacheMatrix(uniformName, matrix);
  18297. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18298. return this;
  18299. };
  18300. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18301. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18302. return this;
  18303. };
  18304. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18305. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18306. return this;
  18307. };
  18308. Effect.prototype.setFloat = function (uniformName, value) {
  18309. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18310. return this;
  18311. this._valueCache[uniformName] = value;
  18312. this._engine.setFloat(this.getUniform(uniformName), value);
  18313. return this;
  18314. };
  18315. Effect.prototype.setBool = function (uniformName, bool) {
  18316. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18317. return this;
  18318. this._valueCache[uniformName] = bool;
  18319. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18320. return this;
  18321. };
  18322. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18323. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18324. return this;
  18325. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18326. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18327. return this;
  18328. };
  18329. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18330. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18331. return this;
  18332. this._cacheFloat2(uniformName, x, y);
  18333. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18334. return this;
  18335. };
  18336. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18337. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18338. return this;
  18339. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18340. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18341. return this;
  18342. };
  18343. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18344. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18345. return this;
  18346. this._cacheFloat3(uniformName, x, y, z);
  18347. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18348. return this;
  18349. };
  18350. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18351. 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)
  18352. return this;
  18353. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18354. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18355. return this;
  18356. };
  18357. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18358. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18359. return this;
  18360. this._cacheFloat4(uniformName, x, y, z, w);
  18361. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18362. return this;
  18363. };
  18364. Effect.prototype.setColor3 = function (uniformName, color3) {
  18365. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18366. return this;
  18367. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18368. this._engine.setColor3(this.getUniform(uniformName), color3);
  18369. return this;
  18370. };
  18371. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18372. 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)
  18373. return this;
  18374. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18375. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18376. return this;
  18377. };
  18378. // Statics
  18379. Effect.ShadersStore = {};
  18380. return Effect;
  18381. })();
  18382. BABYLON.Effect = Effect;
  18383. })(BABYLON || (BABYLON = {}));
  18384. var BABYLON;
  18385. (function (BABYLON) {
  18386. var MaterialDefines = (function () {
  18387. function MaterialDefines() {
  18388. }
  18389. MaterialDefines.prototype.isEqual = function (other) {
  18390. for (var index = 0; index < this._keys.length; index++) {
  18391. var prop = this._keys[index];
  18392. if (this[prop] !== other[prop]) {
  18393. return false;
  18394. }
  18395. }
  18396. return true;
  18397. };
  18398. MaterialDefines.prototype.cloneTo = function (other) {
  18399. for (var index = 0; index < this._keys.length; index++) {
  18400. var prop = this._keys[index];
  18401. other[prop] = this[prop];
  18402. }
  18403. };
  18404. MaterialDefines.prototype.reset = function () {
  18405. for (var index = 0; index < this._keys.length; index++) {
  18406. var prop = this._keys[index];
  18407. if (typeof (this[prop]) === "number") {
  18408. this[prop] = 0;
  18409. }
  18410. else {
  18411. this[prop] = false;
  18412. }
  18413. }
  18414. };
  18415. MaterialDefines.prototype.toString = function () {
  18416. var result = "";
  18417. for (var index = 0; index < this._keys.length; index++) {
  18418. var prop = this._keys[index];
  18419. if (typeof (this[prop]) === "number") {
  18420. result += "#define " + prop + " " + this[prop] + "\n";
  18421. }
  18422. else if (this[prop]) {
  18423. result += "#define " + prop + "\n";
  18424. }
  18425. }
  18426. return result;
  18427. };
  18428. return MaterialDefines;
  18429. })();
  18430. BABYLON.MaterialDefines = MaterialDefines;
  18431. var Material = (function () {
  18432. function Material(name, scene, doNotAdd) {
  18433. this.name = name;
  18434. this.checkReadyOnEveryCall = false;
  18435. this.checkReadyOnlyOnce = false;
  18436. this.state = "";
  18437. this.alpha = 1.0;
  18438. this.backFaceCulling = true;
  18439. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18440. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18441. this.disableDepthWrite = false;
  18442. this.fogEnabled = true;
  18443. this._wasPreviouslyReady = false;
  18444. this._fillMode = Material.TriangleFillMode;
  18445. this.pointSize = 1.0;
  18446. this.zOffset = 0;
  18447. this.id = name;
  18448. this._scene = scene;
  18449. if (!doNotAdd) {
  18450. scene.materials.push(this);
  18451. }
  18452. }
  18453. Object.defineProperty(Material, "TriangleFillMode", {
  18454. get: function () {
  18455. return Material._TriangleFillMode;
  18456. },
  18457. enumerable: true,
  18458. configurable: true
  18459. });
  18460. Object.defineProperty(Material, "WireFrameFillMode", {
  18461. get: function () {
  18462. return Material._WireFrameFillMode;
  18463. },
  18464. enumerable: true,
  18465. configurable: true
  18466. });
  18467. Object.defineProperty(Material, "PointFillMode", {
  18468. get: function () {
  18469. return Material._PointFillMode;
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18475. get: function () {
  18476. return Material._ClockWiseSideOrientation;
  18477. },
  18478. enumerable: true,
  18479. configurable: true
  18480. });
  18481. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18482. get: function () {
  18483. return Material._CounterClockWiseSideOrientation;
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. Object.defineProperty(Material.prototype, "wireframe", {
  18489. get: function () {
  18490. return this._fillMode === Material.WireFrameFillMode;
  18491. },
  18492. set: function (value) {
  18493. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Material.prototype, "pointsCloud", {
  18499. get: function () {
  18500. return this._fillMode === Material.PointFillMode;
  18501. },
  18502. set: function (value) {
  18503. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Material.prototype, "fillMode", {
  18509. get: function () {
  18510. return this._fillMode;
  18511. },
  18512. set: function (value) {
  18513. this._fillMode = value;
  18514. },
  18515. enumerable: true,
  18516. configurable: true
  18517. });
  18518. Material.prototype.isReady = function (mesh, useInstances) {
  18519. return true;
  18520. };
  18521. Material.prototype.getEffect = function () {
  18522. return this._effect;
  18523. };
  18524. Material.prototype.getScene = function () {
  18525. return this._scene;
  18526. };
  18527. Material.prototype.needAlphaBlending = function () {
  18528. return (this.alpha < 1.0);
  18529. };
  18530. Material.prototype.needAlphaTesting = function () {
  18531. return false;
  18532. };
  18533. Material.prototype.getAlphaTestTexture = function () {
  18534. return null;
  18535. };
  18536. Material.prototype.trackCreation = function (onCompiled, onError) {
  18537. };
  18538. Material.prototype.markDirty = function () {
  18539. this._wasPreviouslyReady = false;
  18540. };
  18541. Material.prototype._preBind = function () {
  18542. var engine = this._scene.getEngine();
  18543. engine.enableEffect(this._effect);
  18544. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18545. };
  18546. Material.prototype.bind = function (world, mesh) {
  18547. this._scene._cachedMaterial = this;
  18548. if (this.onBind) {
  18549. this.onBind(this, mesh);
  18550. }
  18551. if (this.disableDepthWrite) {
  18552. var engine = this._scene.getEngine();
  18553. this._cachedDepthWriteState = engine.getDepthWrite();
  18554. engine.setDepthWrite(false);
  18555. }
  18556. };
  18557. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18558. };
  18559. Material.prototype.unbind = function () {
  18560. if (this.disableDepthWrite) {
  18561. var engine = this._scene.getEngine();
  18562. engine.setDepthWrite(this._cachedDepthWriteState);
  18563. }
  18564. };
  18565. Material.prototype.clone = function (name) {
  18566. return null;
  18567. };
  18568. Material.prototype.getBindedMeshes = function () {
  18569. var result = new Array();
  18570. for (var index = 0; index < this._scene.meshes.length; index++) {
  18571. var mesh = this._scene.meshes[index];
  18572. if (mesh.material === this) {
  18573. result.push(mesh);
  18574. }
  18575. }
  18576. return result;
  18577. };
  18578. Material.prototype.dispose = function (forceDisposeEffect) {
  18579. // Animations
  18580. this.getScene().stopAnimation(this);
  18581. // Remove from scene
  18582. var index = this._scene.materials.indexOf(this);
  18583. if (index >= 0) {
  18584. this._scene.materials.splice(index, 1);
  18585. }
  18586. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18587. if (forceDisposeEffect && this._effect) {
  18588. this._scene.getEngine()._releaseEffect(this._effect);
  18589. this._effect = null;
  18590. }
  18591. // Remove from meshes
  18592. for (index = 0; index < this._scene.meshes.length; index++) {
  18593. var mesh = this._scene.meshes[index];
  18594. if (mesh.material === this) {
  18595. mesh.material = null;
  18596. }
  18597. }
  18598. // Callback
  18599. if (this.onDispose) {
  18600. this.onDispose();
  18601. }
  18602. };
  18603. Material.prototype.copyTo = function (other) {
  18604. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18605. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18606. other.alpha = this.alpha;
  18607. other.fillMode = this.fillMode;
  18608. other.backFaceCulling = this.backFaceCulling;
  18609. other.fogEnabled = this.fogEnabled;
  18610. other.wireframe = this.wireframe;
  18611. other.zOffset = this.zOffset;
  18612. other.alphaMode = this.alphaMode;
  18613. other.sideOrientation = this.sideOrientation;
  18614. other.disableDepthWrite = this.disableDepthWrite;
  18615. other.pointSize = this.pointSize;
  18616. other.pointsCloud = this.pointsCloud;
  18617. };
  18618. Material.prototype.serialize = function () {
  18619. var serializationObject = {};
  18620. serializationObject.name = this.name;
  18621. serializationObject.alpha = this.alpha;
  18622. serializationObject.id = this.id;
  18623. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18624. serializationObject.backFaceCulling = this.backFaceCulling;
  18625. return serializationObject;
  18626. };
  18627. Material.ParseMaterial = function (parsedMaterial, scene, rootUrl) {
  18628. if (!parsedMaterial.customType) {
  18629. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18630. }
  18631. //TODO this is where custom materials are inspected and parsed.
  18632. return null;
  18633. };
  18634. Material._TriangleFillMode = 0;
  18635. Material._WireFrameFillMode = 1;
  18636. Material._PointFillMode = 2;
  18637. Material._ClockWiseSideOrientation = 0;
  18638. Material._CounterClockWiseSideOrientation = 1;
  18639. return Material;
  18640. })();
  18641. BABYLON.Material = Material;
  18642. })(BABYLON || (BABYLON = {}));
  18643. var BABYLON;
  18644. (function (BABYLON) {
  18645. var maxSimultaneousLights = 4;
  18646. var FresnelParameters = (function () {
  18647. function FresnelParameters() {
  18648. this.isEnabled = true;
  18649. this.leftColor = BABYLON.Color3.White();
  18650. this.rightColor = BABYLON.Color3.Black();
  18651. this.bias = 0;
  18652. this.power = 1;
  18653. }
  18654. FresnelParameters.prototype.clone = function () {
  18655. var newFresnelParameters = new FresnelParameters();
  18656. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18657. return new FresnelParameters;
  18658. };
  18659. FresnelParameters.prototype.serialize = function () {
  18660. var serializationObject = {};
  18661. serializationObject.isEnabled = this.isEnabled;
  18662. serializationObject.leftColor = this.leftColor;
  18663. serializationObject.rightColor = this.rightColor;
  18664. serializationObject.bias = this.bias;
  18665. serializationObject.power = this.power;
  18666. return serializationObject;
  18667. };
  18668. return FresnelParameters;
  18669. })();
  18670. BABYLON.FresnelParameters = FresnelParameters;
  18671. var StandardMaterialDefines = (function (_super) {
  18672. __extends(StandardMaterialDefines, _super);
  18673. function StandardMaterialDefines() {
  18674. _super.call(this);
  18675. this.DIFFUSE = false;
  18676. this.AMBIENT = false;
  18677. this.OPACITY = false;
  18678. this.OPACITYRGB = false;
  18679. this.REFLECTION = false;
  18680. this.EMISSIVE = false;
  18681. this.SPECULAR = false;
  18682. this.BUMP = false;
  18683. this.SPECULAROVERALPHA = false;
  18684. this.CLIPPLANE = false;
  18685. this.ALPHATEST = false;
  18686. this.ALPHAFROMDIFFUSE = false;
  18687. this.POINTSIZE = false;
  18688. this.FOG = false;
  18689. this.LIGHT0 = false;
  18690. this.LIGHT1 = false;
  18691. this.LIGHT2 = false;
  18692. this.LIGHT3 = false;
  18693. this.SPOTLIGHT0 = false;
  18694. this.SPOTLIGHT1 = false;
  18695. this.SPOTLIGHT2 = false;
  18696. this.SPOTLIGHT3 = false;
  18697. this.HEMILIGHT0 = false;
  18698. this.HEMILIGHT1 = false;
  18699. this.HEMILIGHT2 = false;
  18700. this.HEMILIGHT3 = false;
  18701. this.POINTLIGHT0 = false;
  18702. this.POINTLIGHT1 = false;
  18703. this.POINTLIGHT2 = false;
  18704. this.POINTLIGHT3 = false;
  18705. this.DIRLIGHT0 = false;
  18706. this.DIRLIGHT1 = false;
  18707. this.DIRLIGHT2 = false;
  18708. this.DIRLIGHT3 = false;
  18709. this.SPECULARTERM = false;
  18710. this.SHADOW0 = false;
  18711. this.SHADOW1 = false;
  18712. this.SHADOW2 = false;
  18713. this.SHADOW3 = false;
  18714. this.SHADOWS = false;
  18715. this.SHADOWVSM0 = false;
  18716. this.SHADOWVSM1 = false;
  18717. this.SHADOWVSM2 = false;
  18718. this.SHADOWVSM3 = false;
  18719. this.SHADOWPCF0 = false;
  18720. this.SHADOWPCF1 = false;
  18721. this.SHADOWPCF2 = false;
  18722. this.SHADOWPCF3 = false;
  18723. this.DIFFUSEFRESNEL = false;
  18724. this.OPACITYFRESNEL = false;
  18725. this.REFLECTIONFRESNEL = false;
  18726. this.EMISSIVEFRESNEL = false;
  18727. this.FRESNEL = false;
  18728. this.NORMAL = false;
  18729. this.UV1 = false;
  18730. this.UV2 = false;
  18731. this.VERTEXCOLOR = false;
  18732. this.VERTEXALPHA = false;
  18733. this.NUM_BONE_INFLUENCERS = 0;
  18734. this.BonesPerMesh = 0;
  18735. this.INSTANCES = false;
  18736. this.GLOSSINESS = false;
  18737. this.ROUGHNESS = false;
  18738. this.EMISSIVEASILLUMINATION = false;
  18739. this.LINKEMISSIVEWITHDIFFUSE = false;
  18740. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18741. this.LIGHTMAP = false;
  18742. this.USELIGHTMAPASSHADOWMAP = false;
  18743. this.REFLECTIONMAP_3D = false;
  18744. this.REFLECTIONMAP_SPHERICAL = false;
  18745. this.REFLECTIONMAP_PLANAR = false;
  18746. this.REFLECTIONMAP_CUBIC = false;
  18747. this.REFLECTIONMAP_PROJECTION = false;
  18748. this.REFLECTIONMAP_SKYBOX = false;
  18749. this.REFLECTIONMAP_EXPLICIT = false;
  18750. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18751. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18752. this.INVERTCUBICMAP = false;
  18753. this.LOGARITHMICDEPTH = false;
  18754. this._keys = Object.keys(this);
  18755. }
  18756. return StandardMaterialDefines;
  18757. })(BABYLON.MaterialDefines);
  18758. var StandardMaterial = (function (_super) {
  18759. __extends(StandardMaterial, _super);
  18760. function StandardMaterial(name, scene) {
  18761. var _this = this;
  18762. _super.call(this, name, scene);
  18763. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18764. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18765. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18766. this.specularPower = 64;
  18767. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18768. this.useAlphaFromDiffuseTexture = false;
  18769. this.useEmissiveAsIllumination = false;
  18770. this.linkEmissiveWithDiffuse = false;
  18771. this.useReflectionFresnelFromSpecular = false;
  18772. this.useSpecularOverAlpha = true;
  18773. this.disableLighting = false;
  18774. this.roughness = 0;
  18775. this.useLightmapAsShadowmap = false;
  18776. this.useGlossinessFromSpecularMapAlpha = false;
  18777. this._renderTargets = new BABYLON.SmartArray(16);
  18778. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18779. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18780. this._defines = new StandardMaterialDefines();
  18781. this._cachedDefines = new StandardMaterialDefines();
  18782. this._cachedDefines.BonesPerMesh = -1;
  18783. this.getRenderTargetTextures = function () {
  18784. _this._renderTargets.reset();
  18785. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18786. _this._renderTargets.push(_this.reflectionTexture);
  18787. }
  18788. return _this._renderTargets;
  18789. };
  18790. }
  18791. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18792. get: function () {
  18793. return this._useLogarithmicDepth;
  18794. },
  18795. set: function (value) {
  18796. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. StandardMaterial.prototype.needAlphaBlending = function () {
  18802. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18803. };
  18804. StandardMaterial.prototype.needAlphaTesting = function () {
  18805. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18806. };
  18807. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18808. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18809. };
  18810. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18811. return this.diffuseTexture;
  18812. };
  18813. // Methods
  18814. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18815. if (!mesh) {
  18816. return true;
  18817. }
  18818. if (this._defines.INSTANCES !== useInstances) {
  18819. return false;
  18820. }
  18821. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18822. return true;
  18823. }
  18824. return false;
  18825. };
  18826. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18827. var lightIndex = 0;
  18828. var needNormals = false;
  18829. for (var index = 0; index < scene.lights.length; index++) {
  18830. var light = scene.lights[index];
  18831. if (!light.isEnabled()) {
  18832. continue;
  18833. }
  18834. // Excluded check
  18835. if (light._excludedMeshesIds.length > 0) {
  18836. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18837. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18838. if (excludedMesh) {
  18839. light.excludedMeshes.push(excludedMesh);
  18840. }
  18841. }
  18842. light._excludedMeshesIds = [];
  18843. }
  18844. // Included check
  18845. if (light._includedOnlyMeshesIds.length > 0) {
  18846. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18847. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18848. if (includedOnlyMesh) {
  18849. light.includedOnlyMeshes.push(includedOnlyMesh);
  18850. }
  18851. }
  18852. light._includedOnlyMeshesIds = [];
  18853. }
  18854. if (!light.canAffectMesh(mesh)) {
  18855. continue;
  18856. }
  18857. needNormals = true;
  18858. defines["LIGHT" + lightIndex] = true;
  18859. var type;
  18860. if (light instanceof BABYLON.SpotLight) {
  18861. type = "SPOTLIGHT" + lightIndex;
  18862. }
  18863. else if (light instanceof BABYLON.HemisphericLight) {
  18864. type = "HEMILIGHT" + lightIndex;
  18865. }
  18866. else if (light instanceof BABYLON.PointLight) {
  18867. type = "POINTLIGHT" + lightIndex;
  18868. }
  18869. else {
  18870. type = "DIRLIGHT" + lightIndex;
  18871. }
  18872. defines[type] = true;
  18873. // Specular
  18874. if (!light.specular.equalsFloats(0, 0, 0)) {
  18875. defines["SPECULARTERM"] = true;
  18876. }
  18877. // Shadows
  18878. if (scene.shadowsEnabled) {
  18879. var shadowGenerator = light.getShadowGenerator();
  18880. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18881. defines["SHADOW" + lightIndex] = true;
  18882. defines["SHADOWS"] = true;
  18883. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18884. defines["SHADOWVSM" + lightIndex] = true;
  18885. }
  18886. if (shadowGenerator.usePoissonSampling) {
  18887. defines["SHADOWPCF" + lightIndex] = true;
  18888. }
  18889. }
  18890. }
  18891. lightIndex++;
  18892. if (lightIndex === maxSimultaneousLights)
  18893. break;
  18894. }
  18895. return needNormals;
  18896. };
  18897. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18898. var lightIndex = 0;
  18899. for (var index = 0; index < scene.lights.length; index++) {
  18900. var light = scene.lights[index];
  18901. if (!light.isEnabled()) {
  18902. continue;
  18903. }
  18904. if (!light.canAffectMesh(mesh)) {
  18905. continue;
  18906. }
  18907. if (light instanceof BABYLON.PointLight) {
  18908. // Point Light
  18909. light.transferToEffect(effect, "vLightData" + lightIndex);
  18910. }
  18911. else if (light instanceof BABYLON.DirectionalLight) {
  18912. // Directional Light
  18913. light.transferToEffect(effect, "vLightData" + lightIndex);
  18914. }
  18915. else if (light instanceof BABYLON.SpotLight) {
  18916. // Spot Light
  18917. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18918. }
  18919. else if (light instanceof BABYLON.HemisphericLight) {
  18920. // Hemispheric Light
  18921. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18922. }
  18923. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18924. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18925. if (defines["SPECULARTERM"]) {
  18926. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18927. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18928. }
  18929. // Shadows
  18930. if (scene.shadowsEnabled) {
  18931. var shadowGenerator = light.getShadowGenerator();
  18932. if (mesh.receiveShadows && shadowGenerator) {
  18933. if (!light.needCube()) {
  18934. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18935. }
  18936. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18937. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18938. }
  18939. }
  18940. lightIndex++;
  18941. if (lightIndex === maxSimultaneousLights)
  18942. break;
  18943. }
  18944. };
  18945. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18946. if (this.checkReadyOnlyOnce) {
  18947. if (this._wasPreviouslyReady) {
  18948. return true;
  18949. }
  18950. }
  18951. var scene = this.getScene();
  18952. if (!this.checkReadyOnEveryCall) {
  18953. if (this._renderId === scene.getRenderId()) {
  18954. if (this._checkCache(scene, mesh, useInstances)) {
  18955. return true;
  18956. }
  18957. }
  18958. }
  18959. var engine = scene.getEngine();
  18960. var needNormals = false;
  18961. var needUVs = false;
  18962. this._defines.reset();
  18963. // Textures
  18964. if (scene.texturesEnabled) {
  18965. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18966. if (!this.diffuseTexture.isReady()) {
  18967. return false;
  18968. }
  18969. else {
  18970. needUVs = true;
  18971. this._defines.DIFFUSE = true;
  18972. }
  18973. }
  18974. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18975. if (!this.ambientTexture.isReady()) {
  18976. return false;
  18977. }
  18978. else {
  18979. needUVs = true;
  18980. this._defines.AMBIENT = true;
  18981. }
  18982. }
  18983. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18984. if (!this.opacityTexture.isReady()) {
  18985. return false;
  18986. }
  18987. else {
  18988. needUVs = true;
  18989. this._defines.OPACITY = true;
  18990. if (this.opacityTexture.getAlphaFromRGB) {
  18991. this._defines.OPACITYRGB = true;
  18992. }
  18993. }
  18994. }
  18995. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18996. if (!this.reflectionTexture.isReady()) {
  18997. return false;
  18998. }
  18999. else {
  19000. needNormals = true;
  19001. this._defines.REFLECTION = true;
  19002. if (this.roughness > 0) {
  19003. this._defines.ROUGHNESS = true;
  19004. }
  19005. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19006. this._defines.INVERTCUBICMAP = true;
  19007. }
  19008. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19009. switch (this.reflectionTexture.coordinatesMode) {
  19010. case BABYLON.Texture.CUBIC_MODE:
  19011. case BABYLON.Texture.INVCUBIC_MODE:
  19012. this._defines.REFLECTIONMAP_CUBIC = true;
  19013. break;
  19014. case BABYLON.Texture.EXPLICIT_MODE:
  19015. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19016. break;
  19017. case BABYLON.Texture.PLANAR_MODE:
  19018. this._defines.REFLECTIONMAP_PLANAR = true;
  19019. break;
  19020. case BABYLON.Texture.PROJECTION_MODE:
  19021. this._defines.REFLECTIONMAP_PROJECTION = true;
  19022. break;
  19023. case BABYLON.Texture.SKYBOX_MODE:
  19024. this._defines.REFLECTIONMAP_SKYBOX = true;
  19025. break;
  19026. case BABYLON.Texture.SPHERICAL_MODE:
  19027. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19028. break;
  19029. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19030. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19031. break;
  19032. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19033. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19034. break;
  19035. }
  19036. }
  19037. }
  19038. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19039. if (!this.emissiveTexture.isReady()) {
  19040. return false;
  19041. }
  19042. else {
  19043. needUVs = true;
  19044. this._defines.EMISSIVE = true;
  19045. }
  19046. }
  19047. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19048. if (!this.lightmapTexture.isReady()) {
  19049. return false;
  19050. }
  19051. else {
  19052. needUVs = true;
  19053. this._defines.LIGHTMAP = true;
  19054. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19055. }
  19056. }
  19057. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19058. if (!this.specularTexture.isReady()) {
  19059. return false;
  19060. }
  19061. else {
  19062. needUVs = true;
  19063. this._defines.SPECULAR = true;
  19064. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19065. }
  19066. }
  19067. }
  19068. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19069. if (!this.bumpTexture.isReady()) {
  19070. return false;
  19071. }
  19072. else {
  19073. needUVs = true;
  19074. this._defines.BUMP = true;
  19075. }
  19076. }
  19077. // Effect
  19078. if (scene.clipPlane) {
  19079. this._defines.CLIPPLANE = true;
  19080. }
  19081. if (engine.getAlphaTesting()) {
  19082. this._defines.ALPHATEST = true;
  19083. }
  19084. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19085. this._defines.ALPHAFROMDIFFUSE = true;
  19086. }
  19087. if (this.useEmissiveAsIllumination) {
  19088. this._defines.EMISSIVEASILLUMINATION = true;
  19089. }
  19090. if (this.linkEmissiveWithDiffuse) {
  19091. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19092. }
  19093. if (this.useReflectionFresnelFromSpecular) {
  19094. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19095. }
  19096. if (this.useLogarithmicDepth) {
  19097. this._defines.LOGARITHMICDEPTH = true;
  19098. }
  19099. // Point size
  19100. if (this.pointsCloud || scene.forcePointsCloud) {
  19101. this._defines.POINTSIZE = true;
  19102. }
  19103. // Fog
  19104. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19105. this._defines.FOG = true;
  19106. }
  19107. if (scene.lightsEnabled && !this.disableLighting) {
  19108. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19109. }
  19110. if (StandardMaterial.FresnelEnabled) {
  19111. // Fresnel
  19112. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19113. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19114. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19115. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19116. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19117. this._defines.DIFFUSEFRESNEL = true;
  19118. }
  19119. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19120. this._defines.OPACITYFRESNEL = true;
  19121. }
  19122. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19123. this._defines.REFLECTIONFRESNEL = true;
  19124. }
  19125. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19126. this._defines.EMISSIVEFRESNEL = true;
  19127. }
  19128. needNormals = true;
  19129. this._defines.FRESNEL = true;
  19130. }
  19131. }
  19132. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19133. this._defines.SPECULAROVERALPHA = true;
  19134. }
  19135. // Attribs
  19136. if (mesh) {
  19137. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19138. this._defines.NORMAL = true;
  19139. }
  19140. if (needUVs) {
  19141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19142. this._defines.UV1 = true;
  19143. }
  19144. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19145. this._defines.UV2 = true;
  19146. }
  19147. }
  19148. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19149. this._defines.VERTEXCOLOR = true;
  19150. if (mesh.hasVertexAlpha) {
  19151. this._defines.VERTEXALPHA = true;
  19152. }
  19153. }
  19154. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19155. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19156. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19157. }
  19158. // Instances
  19159. if (useInstances) {
  19160. this._defines.INSTANCES = true;
  19161. }
  19162. }
  19163. // Get correct effect
  19164. if (!this._defines.isEqual(this._cachedDefines)) {
  19165. this._defines.cloneTo(this._cachedDefines);
  19166. scene.resetCachedMaterial();
  19167. // Fallbacks
  19168. var fallbacks = new BABYLON.EffectFallbacks();
  19169. if (this._defines.REFLECTION) {
  19170. fallbacks.addFallback(0, "REFLECTION");
  19171. }
  19172. if (this._defines.SPECULAR) {
  19173. fallbacks.addFallback(0, "SPECULAR");
  19174. }
  19175. if (this._defines.BUMP) {
  19176. fallbacks.addFallback(0, "BUMP");
  19177. }
  19178. if (this._defines.SPECULAROVERALPHA) {
  19179. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19180. }
  19181. if (this._defines.FOG) {
  19182. fallbacks.addFallback(1, "FOG");
  19183. }
  19184. if (this._defines.POINTSIZE) {
  19185. fallbacks.addFallback(0, "POINTSIZE");
  19186. }
  19187. if (this._defines.LOGARITHMICDEPTH) {
  19188. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19189. }
  19190. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19191. if (!this._defines["LIGHT" + lightIndex]) {
  19192. continue;
  19193. }
  19194. if (lightIndex > 0) {
  19195. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19196. }
  19197. if (this._defines["SHADOW" + lightIndex]) {
  19198. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19199. }
  19200. if (this._defines["SHADOWPCF" + lightIndex]) {
  19201. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19202. }
  19203. if (this._defines["SHADOWVSM" + lightIndex]) {
  19204. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19205. }
  19206. }
  19207. if (this._defines.SPECULARTERM) {
  19208. fallbacks.addFallback(0, "SPECULARTERM");
  19209. }
  19210. if (this._defines.DIFFUSEFRESNEL) {
  19211. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19212. }
  19213. if (this._defines.OPACITYFRESNEL) {
  19214. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19215. }
  19216. if (this._defines.REFLECTIONFRESNEL) {
  19217. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19218. }
  19219. if (this._defines.EMISSIVEFRESNEL) {
  19220. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19221. }
  19222. if (this._defines.FRESNEL) {
  19223. fallbacks.addFallback(4, "FRESNEL");
  19224. }
  19225. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19226. fallbacks.addCPUSkinningFallback(0, mesh);
  19227. }
  19228. //Attributes
  19229. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19230. if (this._defines.NORMAL) {
  19231. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19232. }
  19233. if (this._defines.UV1) {
  19234. attribs.push(BABYLON.VertexBuffer.UVKind);
  19235. }
  19236. if (this._defines.UV2) {
  19237. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19238. }
  19239. if (this._defines.VERTEXCOLOR) {
  19240. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19241. }
  19242. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19243. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19244. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19245. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19246. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19247. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19248. }
  19249. }
  19250. if (this._defines.INSTANCES) {
  19251. attribs.push("world0");
  19252. attribs.push("world1");
  19253. attribs.push("world2");
  19254. attribs.push("world3");
  19255. }
  19256. // Legacy browser patch
  19257. var shaderName = "default";
  19258. if (!scene.getEngine().getCaps().standardDerivatives) {
  19259. shaderName = "legacydefault";
  19260. }
  19261. var join = this._defines.toString();
  19262. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19263. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19264. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19265. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19266. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19267. "vFogInfos", "vFogColor", "pointSize",
  19268. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19269. "mBones",
  19270. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19271. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19272. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19273. "logarithmicDepthConstant"
  19274. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19275. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19276. ], join, fallbacks, this.onCompiled, this.onError);
  19277. }
  19278. if (!this._effect.isReady()) {
  19279. return false;
  19280. }
  19281. this._renderId = scene.getRenderId();
  19282. this._wasPreviouslyReady = true;
  19283. if (mesh) {
  19284. if (!mesh._materialDefines) {
  19285. mesh._materialDefines = new StandardMaterialDefines();
  19286. }
  19287. this._defines.cloneTo(mesh._materialDefines);
  19288. }
  19289. return true;
  19290. };
  19291. StandardMaterial.prototype.unbind = function () {
  19292. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19293. this._effect.setTexture("reflection2DSampler", null);
  19294. }
  19295. _super.prototype.unbind.call(this);
  19296. };
  19297. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19298. this._effect.setMatrix("world", world);
  19299. };
  19300. StandardMaterial.prototype.bind = function (world, mesh) {
  19301. var scene = this.getScene();
  19302. // Matrices
  19303. this.bindOnlyWorldMatrix(world);
  19304. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19305. // Bones
  19306. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19307. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19308. }
  19309. if (scene.getCachedMaterial() !== this) {
  19310. if (StandardMaterial.FresnelEnabled) {
  19311. // Fresnel
  19312. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19313. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19314. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19315. }
  19316. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19317. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19318. }
  19319. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19320. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19321. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19322. }
  19323. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19324. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19325. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19326. }
  19327. }
  19328. // Textures
  19329. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19330. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19331. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19332. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19333. }
  19334. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19335. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19336. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19337. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19338. }
  19339. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19340. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19341. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19342. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19343. }
  19344. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19345. if (this.reflectionTexture.isCube) {
  19346. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19347. }
  19348. else {
  19349. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19350. }
  19351. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19352. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19353. }
  19354. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19355. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19356. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19357. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19358. }
  19359. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19360. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19361. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19362. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19363. }
  19364. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19365. this._effect.setTexture("specularSampler", this.specularTexture);
  19366. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19367. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19368. }
  19369. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19370. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19371. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19372. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19373. }
  19374. // Clip plane
  19375. if (scene.clipPlane) {
  19376. var clipPlane = scene.clipPlane;
  19377. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19378. }
  19379. // Point size
  19380. if (this.pointsCloud) {
  19381. this._effect.setFloat("pointSize", this.pointSize);
  19382. }
  19383. // Colors
  19384. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19385. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19386. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19387. if (this._defines.SPECULARTERM) {
  19388. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19389. }
  19390. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19391. }
  19392. // Diffuse
  19393. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19394. // Lights
  19395. if (scene.lightsEnabled && !this.disableLighting) {
  19396. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19397. }
  19398. // View
  19399. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19400. this._effect.setMatrix("view", scene.getViewMatrix());
  19401. }
  19402. // Fog
  19403. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19404. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19405. this._effect.setColor3("vFogColor", scene.fogColor);
  19406. }
  19407. // Log. depth
  19408. if (this._defines.LOGARITHMICDEPTH) {
  19409. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19410. }
  19411. _super.prototype.bind.call(this, world, mesh);
  19412. };
  19413. StandardMaterial.prototype.getAnimatables = function () {
  19414. var results = [];
  19415. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19416. results.push(this.diffuseTexture);
  19417. }
  19418. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19419. results.push(this.ambientTexture);
  19420. }
  19421. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19422. results.push(this.opacityTexture);
  19423. }
  19424. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19425. results.push(this.reflectionTexture);
  19426. }
  19427. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19428. results.push(this.emissiveTexture);
  19429. }
  19430. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19431. results.push(this.specularTexture);
  19432. }
  19433. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19434. results.push(this.bumpTexture);
  19435. }
  19436. return results;
  19437. };
  19438. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19439. if (this.diffuseTexture) {
  19440. this.diffuseTexture.dispose();
  19441. }
  19442. if (this.ambientTexture) {
  19443. this.ambientTexture.dispose();
  19444. }
  19445. if (this.opacityTexture) {
  19446. this.opacityTexture.dispose();
  19447. }
  19448. if (this.reflectionTexture) {
  19449. this.reflectionTexture.dispose();
  19450. }
  19451. if (this.emissiveTexture) {
  19452. this.emissiveTexture.dispose();
  19453. }
  19454. if (this.specularTexture) {
  19455. this.specularTexture.dispose();
  19456. }
  19457. if (this.bumpTexture) {
  19458. this.bumpTexture.dispose();
  19459. }
  19460. _super.prototype.dispose.call(this, forceDisposeEffect);
  19461. };
  19462. StandardMaterial.prototype.clone = function (name) {
  19463. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19464. // Base material
  19465. this.copyTo(newStandardMaterial);
  19466. // Standard material
  19467. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19468. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19469. }
  19470. if (this.ambientTexture && this.ambientTexture.clone) {
  19471. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19472. }
  19473. if (this.opacityTexture && this.opacityTexture.clone) {
  19474. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19475. }
  19476. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19477. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19478. }
  19479. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19480. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19481. }
  19482. if (this.specularTexture && this.specularTexture.clone) {
  19483. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19484. }
  19485. if (this.bumpTexture && this.bumpTexture.clone) {
  19486. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19487. }
  19488. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19489. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19490. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19491. }
  19492. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19493. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19494. newStandardMaterial.specularColor = this.specularColor.clone();
  19495. newStandardMaterial.specularPower = this.specularPower;
  19496. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19497. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19498. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19499. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19500. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19501. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19502. newStandardMaterial.roughness = this.roughness;
  19503. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19504. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19505. }
  19506. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19507. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19508. }
  19509. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19510. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19511. }
  19512. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19513. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19514. }
  19515. return newStandardMaterial;
  19516. };
  19517. StandardMaterial.prototype.serialize = function () {
  19518. var serializationObject = _super.prototype.serialize.call(this);
  19519. serializationObject.ambient = this.ambientColor.asArray();
  19520. serializationObject.diffuse = this.diffuseColor.asArray();
  19521. serializationObject.specular = this.specularColor.asArray();
  19522. serializationObject.specularPower = this.specularPower;
  19523. serializationObject.emissive = this.emissiveColor.asArray();
  19524. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19525. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19526. if (this.diffuseTexture) {
  19527. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19528. }
  19529. if (this.diffuseFresnelParameters) {
  19530. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19531. }
  19532. if (this.ambientTexture) {
  19533. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19534. }
  19535. if (this.opacityTexture) {
  19536. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19537. }
  19538. if (this.opacityFresnelParameters) {
  19539. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19540. }
  19541. if (this.reflectionTexture) {
  19542. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19543. }
  19544. if (this.reflectionFresnelParameters) {
  19545. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19546. }
  19547. if (this.emissiveTexture) {
  19548. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19549. }
  19550. if (this.lightmapTexture) {
  19551. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19552. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19553. }
  19554. if (this.emissiveFresnelParameters) {
  19555. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19556. }
  19557. if (this.specularTexture) {
  19558. serializationObject.specularTexture = this.specularTexture.serialize();
  19559. }
  19560. if (this.bumpTexture) {
  19561. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19562. }
  19563. return serializationObject;
  19564. };
  19565. StandardMaterial.ParseFresnelParameters = function (parsedFresnelParameters) {
  19566. var fresnelParameters = new FresnelParameters();
  19567. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19568. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19569. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19570. fresnelParameters.bias = parsedFresnelParameters.bias;
  19571. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19572. return fresnelParameters;
  19573. };
  19574. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19575. var material = new StandardMaterial(source.name, scene);
  19576. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19577. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19578. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19579. material.specularPower = source.specularPower;
  19580. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19581. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19582. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19583. material.alpha = source.alpha;
  19584. material.id = source.id;
  19585. if (source.disableDepthWrite) {
  19586. material.disableDepthWrite = source.disableDepthWrite;
  19587. }
  19588. BABYLON.Tags.AddTagsTo(material, source.tags);
  19589. material.backFaceCulling = source.backFaceCulling;
  19590. material.wireframe = source.wireframe;
  19591. if (source.diffuseTexture) {
  19592. material.diffuseTexture = BABYLON.Texture.ParseTexture(source.diffuseTexture, scene, rootUrl);
  19593. }
  19594. if (source.diffuseFresnelParameters) {
  19595. material.diffuseFresnelParameters = StandardMaterial.ParseFresnelParameters(source.diffuseFresnelParameters);
  19596. }
  19597. if (source.ambientTexture) {
  19598. material.ambientTexture = BABYLON.Texture.ParseTexture(source.ambientTexture, scene, rootUrl);
  19599. }
  19600. if (source.opacityTexture) {
  19601. material.opacityTexture = BABYLON.Texture.ParseTexture(source.opacityTexture, scene, rootUrl);
  19602. }
  19603. if (source.opacityFresnelParameters) {
  19604. material.opacityFresnelParameters = StandardMaterial.ParseFresnelParameters(source.opacityFresnelParameters);
  19605. }
  19606. if (source.reflectionTexture) {
  19607. material.reflectionTexture = BABYLON.Texture.ParseTexture(source.reflectionTexture, scene, rootUrl);
  19608. }
  19609. if (source.reflectionFresnelParameters) {
  19610. material.reflectionFresnelParameters = StandardMaterial.ParseFresnelParameters(source.reflectionFresnelParameters);
  19611. }
  19612. if (source.emissiveTexture) {
  19613. material.emissiveTexture = BABYLON.Texture.ParseTexture(source.emissiveTexture, scene, rootUrl);
  19614. }
  19615. if (source.lightmapTexture) {
  19616. material.lightmapTexture = BABYLON.Texture.ParseTexture(source.lightmapTexture, scene, rootUrl);
  19617. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19618. }
  19619. if (source.emissiveFresnelParameters) {
  19620. material.emissiveFresnelParameters = StandardMaterial.ParseFresnelParameters(source.emissiveFresnelParameters);
  19621. }
  19622. if (source.specularTexture) {
  19623. material.specularTexture = BABYLON.Texture.ParseTexture(source.specularTexture, scene, rootUrl);
  19624. }
  19625. if (source.bumpTexture) {
  19626. material.bumpTexture = BABYLON.Texture.ParseTexture(source.bumpTexture, scene, rootUrl);
  19627. }
  19628. if (source.checkReadyOnlyOnce) {
  19629. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19630. }
  19631. return material;
  19632. };
  19633. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19634. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19635. // Statics
  19636. // Flags used to enable or disable a type of texture for all Standard Materials
  19637. StandardMaterial.DiffuseTextureEnabled = true;
  19638. StandardMaterial.AmbientTextureEnabled = true;
  19639. StandardMaterial.OpacityTextureEnabled = true;
  19640. StandardMaterial.ReflectionTextureEnabled = true;
  19641. StandardMaterial.EmissiveTextureEnabled = true;
  19642. StandardMaterial.SpecularTextureEnabled = true;
  19643. StandardMaterial.BumpTextureEnabled = true;
  19644. StandardMaterial.FresnelEnabled = true;
  19645. StandardMaterial.LightmapEnabled = true;
  19646. return StandardMaterial;
  19647. })(BABYLON.Material);
  19648. BABYLON.StandardMaterial = StandardMaterial;
  19649. })(BABYLON || (BABYLON = {}));
  19650. var BABYLON;
  19651. (function (BABYLON) {
  19652. var MultiMaterial = (function (_super) {
  19653. __extends(MultiMaterial, _super);
  19654. function MultiMaterial(name, scene) {
  19655. _super.call(this, name, scene, true);
  19656. this.subMaterials = new Array();
  19657. scene.multiMaterials.push(this);
  19658. }
  19659. // Properties
  19660. MultiMaterial.prototype.getSubMaterial = function (index) {
  19661. if (index < 0 || index >= this.subMaterials.length) {
  19662. return this.getScene().defaultMaterial;
  19663. }
  19664. return this.subMaterials[index];
  19665. };
  19666. // Methods
  19667. MultiMaterial.prototype.isReady = function (mesh) {
  19668. for (var index = 0; index < this.subMaterials.length; index++) {
  19669. var subMaterial = this.subMaterials[index];
  19670. if (subMaterial) {
  19671. if (!this.subMaterials[index].isReady(mesh)) {
  19672. return false;
  19673. }
  19674. }
  19675. }
  19676. return true;
  19677. };
  19678. MultiMaterial.prototype.clone = function (name) {
  19679. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19680. for (var index = 0; index < this.subMaterials.length; index++) {
  19681. var subMaterial = this.subMaterials[index];
  19682. newMultiMaterial.subMaterials.push(subMaterial);
  19683. }
  19684. return newMultiMaterial;
  19685. };
  19686. MultiMaterial.prototype.serialize = function () {
  19687. var serializationObject = {};
  19688. serializationObject.name = this.name;
  19689. serializationObject.id = this.id;
  19690. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19691. serializationObject.materials = [];
  19692. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19693. var subMat = this.subMaterials[matIndex];
  19694. if (subMat) {
  19695. serializationObject.materials.push(subMat.id);
  19696. }
  19697. else {
  19698. serializationObject.materials.push(null);
  19699. }
  19700. }
  19701. return serializationObject;
  19702. };
  19703. MultiMaterial.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19704. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19705. multiMaterial.id = parsedMultiMaterial.id;
  19706. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19707. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19708. var subMatId = parsedMultiMaterial.materials[matIndex];
  19709. if (subMatId) {
  19710. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19711. }
  19712. else {
  19713. multiMaterial.subMaterials.push(null);
  19714. }
  19715. }
  19716. return multiMaterial;
  19717. };
  19718. return MultiMaterial;
  19719. })(BABYLON.Material);
  19720. BABYLON.MultiMaterial = MultiMaterial;
  19721. })(BABYLON || (BABYLON = {}));
  19722. var BABYLON;
  19723. (function (BABYLON) {
  19724. var SceneLoader = (function () {
  19725. function SceneLoader() {
  19726. }
  19727. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19728. get: function () {
  19729. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19730. },
  19731. set: function (value) {
  19732. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19738. get: function () {
  19739. return SceneLoader._ShowLoadingScreen;
  19740. },
  19741. set: function (value) {
  19742. SceneLoader._ShowLoadingScreen = value;
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19748. var dotPosition = sceneFilename.lastIndexOf(".");
  19749. var queryStringPosition = sceneFilename.indexOf("?");
  19750. if (queryStringPosition === -1) {
  19751. queryStringPosition = sceneFilename.length;
  19752. }
  19753. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19754. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19755. var plugin = this._registeredPlugins[index];
  19756. if (plugin.extensions.indexOf(extension) !== -1) {
  19757. return plugin;
  19758. }
  19759. }
  19760. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19761. };
  19762. // Public functions
  19763. SceneLoader.RegisterPlugin = function (plugin) {
  19764. plugin.extensions = plugin.extensions.toLowerCase();
  19765. SceneLoader._registeredPlugins.push(plugin);
  19766. };
  19767. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19768. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19769. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19770. return;
  19771. }
  19772. var loadingToken = {};
  19773. scene._addPendingData(loadingToken);
  19774. var manifestChecked = function (success) {
  19775. scene.database = database;
  19776. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19777. var importMeshFromData = function (data) {
  19778. var meshes = [];
  19779. var particleSystems = [];
  19780. var skeletons = [];
  19781. try {
  19782. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19783. if (onerror) {
  19784. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19785. }
  19786. scene._removePendingData(loadingToken);
  19787. return;
  19788. }
  19789. }
  19790. catch (e) {
  19791. if (onerror) {
  19792. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19793. }
  19794. scene._removePendingData(loadingToken);
  19795. return;
  19796. }
  19797. if (onsuccess) {
  19798. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19799. onsuccess(meshes, particleSystems, skeletons);
  19800. scene._removePendingData(loadingToken);
  19801. }
  19802. };
  19803. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19804. // Direct load
  19805. importMeshFromData(sceneFilename.substr(5));
  19806. return;
  19807. }
  19808. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19809. importMeshFromData(data);
  19810. }, progressCallBack, database);
  19811. };
  19812. if (scene.getEngine().enableOfflineSupport) {
  19813. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19814. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19815. }
  19816. else {
  19817. manifestChecked(true);
  19818. }
  19819. };
  19820. /**
  19821. * Load a scene
  19822. * @param rootUrl a string that defines the root url for scene and resources
  19823. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19824. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19825. */
  19826. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19827. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19828. };
  19829. /**
  19830. * Append a scene
  19831. * @param rootUrl a string that defines the root url for scene and resources
  19832. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19833. * @param scene is the instance of BABYLON.Scene to append to
  19834. */
  19835. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19836. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19837. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19838. return;
  19839. }
  19840. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19841. var database;
  19842. var loadingToken = {};
  19843. scene._addPendingData(loadingToken);
  19844. if (SceneLoader.ShowLoadingScreen) {
  19845. scene.getEngine().displayLoadingUI();
  19846. }
  19847. var loadSceneFromData = function (data) {
  19848. scene.database = database;
  19849. if (!plugin.load(scene, data, rootUrl)) {
  19850. if (onerror) {
  19851. onerror(scene);
  19852. }
  19853. scene._removePendingData(loadingToken);
  19854. scene.getEngine().hideLoadingUI();
  19855. return;
  19856. }
  19857. if (onsuccess) {
  19858. onsuccess(scene);
  19859. }
  19860. scene._removePendingData(loadingToken);
  19861. if (SceneLoader.ShowLoadingScreen) {
  19862. scene.executeWhenReady(function () {
  19863. scene.getEngine().hideLoadingUI();
  19864. });
  19865. }
  19866. };
  19867. var manifestChecked = function (success) {
  19868. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19869. };
  19870. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19871. // Direct load
  19872. loadSceneFromData(sceneFilename.substr(5));
  19873. return;
  19874. }
  19875. if (rootUrl.indexOf("file:") === -1) {
  19876. if (scene.getEngine().enableOfflineSupport) {
  19877. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19878. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19879. }
  19880. else {
  19881. manifestChecked(true);
  19882. }
  19883. }
  19884. else {
  19885. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19886. }
  19887. };
  19888. // Flags
  19889. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19890. SceneLoader._ShowLoadingScreen = true;
  19891. // Members
  19892. SceneLoader._registeredPlugins = new Array();
  19893. return SceneLoader;
  19894. })();
  19895. BABYLON.SceneLoader = SceneLoader;
  19896. ;
  19897. })(BABYLON || (BABYLON = {}));
  19898. var BABYLON;
  19899. (function (BABYLON) {
  19900. var Internals;
  19901. (function (Internals) {
  19902. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19903. for (var index = 0; index < parsedData.materials.length; index++) {
  19904. var parsedMaterial = parsedData.materials[index];
  19905. if (parsedMaterial.id === id) {
  19906. return BABYLON.Material.ParseMaterial(parsedMaterial, scene, rootUrl);
  19907. }
  19908. }
  19909. return null;
  19910. };
  19911. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19912. names = (names instanceof Array) ? names : [names];
  19913. for (var i in names) {
  19914. if (mesh.name === names[i]) {
  19915. hierarchyIds.push(mesh.id);
  19916. return true;
  19917. }
  19918. }
  19919. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19920. hierarchyIds.push(mesh.id);
  19921. return true;
  19922. }
  19923. return false;
  19924. };
  19925. BABYLON.SceneLoader.RegisterPlugin({
  19926. extensions: ".babylon",
  19927. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19928. var parsedData = JSON.parse(data);
  19929. var loadedSkeletonsIds = [];
  19930. var loadedMaterialsIds = [];
  19931. var hierarchyIds = [];
  19932. var index;
  19933. for (index = 0; index < parsedData.meshes.length; index++) {
  19934. var parsedMesh = parsedData.meshes[index];
  19935. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19936. if (meshesNames instanceof Array) {
  19937. // Remove found mesh name from list.
  19938. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19939. }
  19940. //Geometry?
  19941. if (parsedMesh.geometryId) {
  19942. //does the file contain geometries?
  19943. if (parsedData.geometries) {
  19944. //find the correct geometry and add it to the scene
  19945. var found = false;
  19946. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19947. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19948. return;
  19949. }
  19950. else {
  19951. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19952. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19953. switch (geometryType) {
  19954. case "boxes":
  19955. BABYLON.Geometry.Primitives.Box.ParseBox(parsedGeometryData, scene);
  19956. break;
  19957. case "spheres":
  19958. BABYLON.Geometry.Primitives.Sphere.ParseSphere(parsedGeometryData, scene);
  19959. break;
  19960. case "cylinders":
  19961. BABYLON.Geometry.Primitives.Cylinder.ParseCylinder(parsedGeometryData, scene);
  19962. break;
  19963. case "toruses":
  19964. BABYLON.Geometry.Primitives.Torus.ParseTorus(parsedGeometryData, scene);
  19965. break;
  19966. case "grounds":
  19967. BABYLON.Geometry.Primitives.Ground.ParseGround(parsedGeometryData, scene);
  19968. break;
  19969. case "planes":
  19970. BABYLON.Geometry.Primitives.Plane.ParsePlane(parsedGeometryData, scene);
  19971. break;
  19972. case "torusKnots":
  19973. BABYLON.Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedGeometryData, scene);
  19974. break;
  19975. case "vertexData":
  19976. BABYLON.Geometry.ParseGeometry(parsedGeometryData, scene, rootUrl);
  19977. break;
  19978. }
  19979. found = true;
  19980. }
  19981. });
  19982. }
  19983. });
  19984. if (!found) {
  19985. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  19986. }
  19987. }
  19988. }
  19989. // Material ?
  19990. if (parsedMesh.materialId) {
  19991. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19992. if (!materialFound && parsedData.multiMaterials) {
  19993. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19994. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19995. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19996. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19997. var subMatId = parsedMultiMaterial.materials[matIndex];
  19998. loadedMaterialsIds.push(subMatId);
  19999. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20000. }
  20001. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20002. parsedMultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
  20003. materialFound = true;
  20004. break;
  20005. }
  20006. }
  20007. }
  20008. if (!materialFound) {
  20009. loadedMaterialsIds.push(parsedMesh.materialId);
  20010. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20011. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20012. }
  20013. }
  20014. }
  20015. // Skeleton ?
  20016. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20017. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20018. if (!skeletonAlreadyLoaded) {
  20019. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20020. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20021. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20022. skeletons.push(BABYLON.Skeleton.ParseSkeleton(parsedSkeleton, scene));
  20023. loadedSkeletonsIds.push(parsedSkeleton.id);
  20024. }
  20025. }
  20026. }
  20027. }
  20028. var mesh = BABYLON.Mesh.ParseMesh(parsedMesh, scene, rootUrl);
  20029. meshes.push(mesh);
  20030. }
  20031. }
  20032. // Connecting parents
  20033. var currentMesh;
  20034. for (index = 0; index < scene.meshes.length; index++) {
  20035. currentMesh = scene.meshes[index];
  20036. if (currentMesh._waitingParentId) {
  20037. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20038. currentMesh._waitingParentId = undefined;
  20039. }
  20040. }
  20041. // freeze world matrix application
  20042. for (index = 0; index < scene.meshes.length; index++) {
  20043. currentMesh = scene.meshes[index];
  20044. if (currentMesh._waitingFreezeWorldMatrix) {
  20045. currentMesh.freezeWorldMatrix();
  20046. currentMesh._waitingFreezeWorldMatrix = undefined;
  20047. }
  20048. }
  20049. // Particles
  20050. if (parsedData.particleSystems) {
  20051. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20052. var parsedParticleSystem = parsedData.particleSystems[index];
  20053. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20054. particleSystems.push(BABYLON.ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20055. }
  20056. }
  20057. }
  20058. return true;
  20059. },
  20060. load: function (scene, data, rootUrl) {
  20061. var parsedData = JSON.parse(data);
  20062. // Scene
  20063. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20064. scene.autoClear = parsedData.autoClear;
  20065. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20066. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20067. if (parsedData.gravity) {
  20068. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20069. }
  20070. // Fog
  20071. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20072. scene.fogMode = parsedData.fogMode;
  20073. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20074. scene.fogStart = parsedData.fogStart;
  20075. scene.fogEnd = parsedData.fogEnd;
  20076. scene.fogDensity = parsedData.fogDensity;
  20077. }
  20078. //Physics
  20079. if (parsedData.physicsEnabled) {
  20080. var physicsPlugin;
  20081. if (parsedData.physicsEngine === "cannon") {
  20082. physicsPlugin = new BABYLON.CannonJSPlugin();
  20083. }
  20084. else if (parsedData.physicsEngine === "oimo") {
  20085. physicsPlugin = new BABYLON.OimoJSPlugin();
  20086. }
  20087. //else - default engine, which is currently oimo
  20088. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20089. scene.enablePhysics(physicsGravity, physicsPlugin);
  20090. }
  20091. //collisions, if defined. otherwise, default is true
  20092. if (parsedData.collisionsEnabled != undefined) {
  20093. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20094. }
  20095. scene.workerCollisions = !!parsedData.workerCollisions;
  20096. // Lights
  20097. var index;
  20098. for (index = 0; index < parsedData.lights.length; index++) {
  20099. var parsedLight = parsedData.lights[index];
  20100. BABYLON.Light.ParseLight(parsedLight, scene);
  20101. }
  20102. // Materials
  20103. if (parsedData.materials) {
  20104. for (index = 0; index < parsedData.materials.length; index++) {
  20105. var parsedMaterial = parsedData.materials[index];
  20106. BABYLON.Material.ParseMaterial(parsedMaterial, scene, rootUrl);
  20107. }
  20108. }
  20109. if (parsedData.multiMaterials) {
  20110. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20111. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20112. BABYLON.MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
  20113. }
  20114. }
  20115. // Skeletons
  20116. if (parsedData.skeletons) {
  20117. for (index = 0; index < parsedData.skeletons.length; index++) {
  20118. var parsedSkeleton = parsedData.skeletons[index];
  20119. BABYLON.Skeleton.ParseSkeleton(parsedSkeleton, scene);
  20120. }
  20121. }
  20122. // Geometries
  20123. var geometries = parsedData.geometries;
  20124. if (geometries) {
  20125. // Boxes
  20126. var boxes = geometries.boxes;
  20127. if (boxes) {
  20128. for (index = 0; index < boxes.length; index++) {
  20129. var parsedBox = boxes[index];
  20130. BABYLON.Geometry.Primitives.Box.ParseBox(parsedBox, scene);
  20131. }
  20132. }
  20133. // Spheres
  20134. var spheres = geometries.spheres;
  20135. if (spheres) {
  20136. for (index = 0; index < spheres.length; index++) {
  20137. var parsedSphere = spheres[index];
  20138. BABYLON.Geometry.Primitives.Sphere.ParseSphere(parsedSphere, scene);
  20139. }
  20140. }
  20141. // Cylinders
  20142. var cylinders = geometries.cylinders;
  20143. if (cylinders) {
  20144. for (index = 0; index < cylinders.length; index++) {
  20145. var parsedCylinder = cylinders[index];
  20146. BABYLON.Geometry.Primitives.Cylinder.ParseCylinder(parsedCylinder, scene);
  20147. }
  20148. }
  20149. // Toruses
  20150. var toruses = geometries.toruses;
  20151. if (toruses) {
  20152. for (index = 0; index < toruses.length; index++) {
  20153. var parsedTorus = toruses[index];
  20154. BABYLON.Geometry.Primitives.Torus.ParseTorus(parsedTorus, scene);
  20155. }
  20156. }
  20157. // Grounds
  20158. var grounds = geometries.grounds;
  20159. if (grounds) {
  20160. for (index = 0; index < grounds.length; index++) {
  20161. var parsedGround = grounds[index];
  20162. BABYLON.Geometry.Primitives.Ground.ParseGround(parsedGround, scene);
  20163. }
  20164. }
  20165. // Planes
  20166. var planes = geometries.planes;
  20167. if (planes) {
  20168. for (index = 0; index < planes.length; index++) {
  20169. var parsedPlane = planes[index];
  20170. BABYLON.Geometry.Primitives.Plane.ParsePlane(parsedPlane, scene);
  20171. }
  20172. }
  20173. // TorusKnots
  20174. var torusKnots = geometries.torusKnots;
  20175. if (torusKnots) {
  20176. for (index = 0; index < torusKnots.length; index++) {
  20177. var parsedTorusKnot = torusKnots[index];
  20178. BABYLON.Geometry.Primitives.TorusKnot.ParseTorusKnot(parsedTorusKnot, scene);
  20179. }
  20180. }
  20181. // VertexData
  20182. var vertexData = geometries.vertexData;
  20183. if (vertexData) {
  20184. for (index = 0; index < vertexData.length; index++) {
  20185. var parsedVertexData = vertexData[index];
  20186. BABYLON.Geometry.ParseGeometry(parsedVertexData, scene, rootUrl);
  20187. }
  20188. }
  20189. }
  20190. // Meshes
  20191. for (index = 0; index < parsedData.meshes.length; index++) {
  20192. var parsedMesh = parsedData.meshes[index];
  20193. BABYLON.Mesh.ParseMesh(parsedMesh, scene, rootUrl);
  20194. }
  20195. // Cameras
  20196. for (index = 0; index < parsedData.cameras.length; index++) {
  20197. var parsedCamera = parsedData.cameras[index];
  20198. BABYLON.Camera.ParseCamera(parsedCamera, scene);
  20199. }
  20200. if (parsedData.activeCameraID) {
  20201. scene.setActiveCameraByID(parsedData.activeCameraID);
  20202. }
  20203. // Browsing all the graph to connect the dots
  20204. for (index = 0; index < scene.cameras.length; index++) {
  20205. var camera = scene.cameras[index];
  20206. if (camera._waitingParentId) {
  20207. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20208. camera._waitingParentId = undefined;
  20209. }
  20210. }
  20211. for (index = 0; index < scene.lights.length; index++) {
  20212. var light = scene.lights[index];
  20213. if (light._waitingParentId) {
  20214. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20215. light._waitingParentId = undefined;
  20216. }
  20217. }
  20218. // Sounds
  20219. if (BABYLON.AudioEngine && parsedData.sounds) {
  20220. for (index = 0; index < parsedData.sounds.length; index++) {
  20221. var parsedSound = parsedData.sounds[index];
  20222. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20223. BABYLON.Sound.ParseSound(parsedSound, scene, rootUrl);
  20224. }
  20225. else {
  20226. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20227. }
  20228. }
  20229. }
  20230. // Connect parents & children and parse actions
  20231. for (index = 0; index < scene.meshes.length; index++) {
  20232. var mesh = scene.meshes[index];
  20233. if (mesh._waitingParentId) {
  20234. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20235. mesh._waitingParentId = undefined;
  20236. }
  20237. if (mesh._waitingActions) {
  20238. BABYLON.ActionManager.ParseActions(mesh._waitingActions, mesh, scene);
  20239. mesh._waitingActions = undefined;
  20240. }
  20241. }
  20242. // freeze world matrix application
  20243. for (index = 0; index < scene.meshes.length; index++) {
  20244. var currentMesh = scene.meshes[index];
  20245. if (currentMesh._waitingFreezeWorldMatrix) {
  20246. currentMesh.freezeWorldMatrix();
  20247. currentMesh._waitingFreezeWorldMatrix = undefined;
  20248. }
  20249. }
  20250. // Particles Systems
  20251. if (parsedData.particleSystems) {
  20252. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20253. var parsedParticleSystem = parsedData.particleSystems[index];
  20254. BABYLON.ParticleSystem.ParseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20255. }
  20256. }
  20257. // Lens flares
  20258. if (parsedData.lensFlareSystems) {
  20259. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20260. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20261. BABYLON.LensFlareSystem.ParseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20262. }
  20263. }
  20264. // Shadows
  20265. if (parsedData.shadowGenerators) {
  20266. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20267. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20268. BABYLON.ShadowGenerator.ParseShadowGenerator(parsedShadowGenerator, scene);
  20269. }
  20270. }
  20271. // Actions (scene)
  20272. if (parsedData.actions) {
  20273. BABYLON.ActionManager.ParseActions(parsedData.actions, null, scene);
  20274. }
  20275. // Finish
  20276. return true;
  20277. }
  20278. });
  20279. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20280. })(BABYLON || (BABYLON = {}));
  20281. var BABYLON;
  20282. (function (BABYLON) {
  20283. var SpriteManager = (function () {
  20284. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20286. this.name = name;
  20287. this.cellSize = cellSize;
  20288. this.sprites = new Array();
  20289. this.renderingGroupId = 0;
  20290. this.layerMask = 0x0FFFFFFF;
  20291. this.fogEnabled = true;
  20292. this.isPickable = false;
  20293. this._vertexDeclaration = [4, 4, 4, 4];
  20294. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20295. this._capacity = capacity;
  20296. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20297. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20298. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20299. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20300. this._scene = scene;
  20301. this._scene.spriteManagers.push(this);
  20302. // VBO
  20303. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20304. var indices = [];
  20305. var index = 0;
  20306. for (var count = 0; count < capacity; count++) {
  20307. indices.push(index);
  20308. indices.push(index + 1);
  20309. indices.push(index + 2);
  20310. indices.push(index);
  20311. indices.push(index + 2);
  20312. indices.push(index + 3);
  20313. index += 4;
  20314. }
  20315. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20316. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20317. // Effects
  20318. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20319. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20320. }
  20321. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20322. var arrayOffset = index * 16;
  20323. if (offsetX === 0)
  20324. offsetX = this._epsilon;
  20325. else if (offsetX === 1)
  20326. offsetX = 1 - this._epsilon;
  20327. if (offsetY === 0)
  20328. offsetY = this._epsilon;
  20329. else if (offsetY === 1)
  20330. offsetY = 1 - this._epsilon;
  20331. this._vertices[arrayOffset] = sprite.position.x;
  20332. this._vertices[arrayOffset + 1] = sprite.position.y;
  20333. this._vertices[arrayOffset + 2] = sprite.position.z;
  20334. this._vertices[arrayOffset + 3] = sprite.angle;
  20335. this._vertices[arrayOffset + 4] = sprite.width;
  20336. this._vertices[arrayOffset + 5] = sprite.height;
  20337. this._vertices[arrayOffset + 6] = offsetX;
  20338. this._vertices[arrayOffset + 7] = offsetY;
  20339. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20340. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20341. var offset = (sprite.cellIndex / rowSize) >> 0;
  20342. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20343. this._vertices[arrayOffset + 11] = offset;
  20344. // Color
  20345. this._vertices[arrayOffset + 12] = sprite.color.r;
  20346. this._vertices[arrayOffset + 13] = sprite.color.g;
  20347. this._vertices[arrayOffset + 14] = sprite.color.b;
  20348. this._vertices[arrayOffset + 15] = sprite.color.a;
  20349. };
  20350. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20351. var count = Math.min(this._capacity, this.sprites.length);
  20352. var min = BABYLON.Vector3.Zero();
  20353. var max = BABYLON.Vector3.Zero();
  20354. var distance = Number.MAX_VALUE;
  20355. var currentSprite;
  20356. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20357. var cameraView = camera.getViewMatrix();
  20358. for (var index = 0; index < count; index++) {
  20359. var sprite = this.sprites[index];
  20360. if (!sprite) {
  20361. continue;
  20362. }
  20363. if (predicate) {
  20364. if (!predicate(sprite)) {
  20365. continue;
  20366. }
  20367. }
  20368. else if (!sprite.isPickable) {
  20369. continue;
  20370. }
  20371. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20372. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20373. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20374. if (ray.intersectsBoxMinMax(min, max)) {
  20375. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20376. if (distance > currentDistance) {
  20377. distance = currentDistance;
  20378. currentSprite = sprite;
  20379. if (fastCheck) {
  20380. break;
  20381. }
  20382. }
  20383. }
  20384. }
  20385. if (currentSprite) {
  20386. var result = new BABYLON.PickingInfo();
  20387. result.hit = true;
  20388. result.pickedSprite = currentSprite;
  20389. result.distance = distance;
  20390. return result;
  20391. }
  20392. return null;
  20393. };
  20394. SpriteManager.prototype.render = function () {
  20395. // Check
  20396. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20397. return;
  20398. var engine = this._scene.getEngine();
  20399. var baseSize = this._spriteTexture.getBaseSize();
  20400. // Sprites
  20401. var deltaTime = engine.getDeltaTime();
  20402. var max = Math.min(this._capacity, this.sprites.length);
  20403. var rowSize = baseSize.width / this.cellSize;
  20404. var offset = 0;
  20405. for (var index = 0; index < max; index++) {
  20406. var sprite = this.sprites[index];
  20407. if (!sprite) {
  20408. continue;
  20409. }
  20410. sprite._animate(deltaTime);
  20411. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20412. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20413. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20414. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20415. }
  20416. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20417. // Render
  20418. var effect = this._effectBase;
  20419. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20420. effect = this._effectFog;
  20421. }
  20422. engine.enableEffect(effect);
  20423. var viewMatrix = this._scene.getViewMatrix();
  20424. effect.setTexture("diffuseSampler", this._spriteTexture);
  20425. effect.setMatrix("view", viewMatrix);
  20426. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20427. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20428. // Fog
  20429. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20430. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20431. effect.setColor3("vFogColor", this._scene.fogColor);
  20432. }
  20433. // VBOs
  20434. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20435. // Draw order
  20436. engine.setDepthFunctionToLessOrEqual();
  20437. effect.setBool("alphaTest", true);
  20438. engine.setColorWrite(false);
  20439. engine.draw(true, 0, max * 6);
  20440. engine.setColorWrite(true);
  20441. effect.setBool("alphaTest", false);
  20442. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20443. engine.draw(true, 0, max * 6);
  20444. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20445. };
  20446. SpriteManager.prototype.dispose = function () {
  20447. if (this._vertexBuffer) {
  20448. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20449. this._vertexBuffer = null;
  20450. }
  20451. if (this._indexBuffer) {
  20452. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20453. this._indexBuffer = null;
  20454. }
  20455. if (this._spriteTexture) {
  20456. this._spriteTexture.dispose();
  20457. this._spriteTexture = null;
  20458. }
  20459. // Remove from scene
  20460. var index = this._scene.spriteManagers.indexOf(this);
  20461. this._scene.spriteManagers.splice(index, 1);
  20462. // Callback
  20463. if (this.onDispose) {
  20464. this.onDispose();
  20465. }
  20466. };
  20467. return SpriteManager;
  20468. })();
  20469. BABYLON.SpriteManager = SpriteManager;
  20470. })(BABYLON || (BABYLON = {}));
  20471. var BABYLON;
  20472. (function (BABYLON) {
  20473. var Sprite = (function () {
  20474. function Sprite(name, manager) {
  20475. this.name = name;
  20476. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20477. this.width = 1.0;
  20478. this.height = 1.0;
  20479. this.angle = 0;
  20480. this.cellIndex = 0;
  20481. this.invertU = 0;
  20482. this.invertV = 0;
  20483. this.animations = new Array();
  20484. this.isPickable = false;
  20485. this._animationStarted = false;
  20486. this._loopAnimation = false;
  20487. this._fromIndex = 0;
  20488. this._toIndex = 0;
  20489. this._delay = 0;
  20490. this._direction = 1;
  20491. this._frameCount = 0;
  20492. this._time = 0;
  20493. this._manager = manager;
  20494. this._manager.sprites.push(this);
  20495. this.position = BABYLON.Vector3.Zero();
  20496. }
  20497. Object.defineProperty(Sprite.prototype, "size", {
  20498. get: function () {
  20499. return this.width;
  20500. },
  20501. set: function (value) {
  20502. this.width = value;
  20503. this.height = value;
  20504. },
  20505. enumerable: true,
  20506. configurable: true
  20507. });
  20508. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20509. this._fromIndex = from;
  20510. this._toIndex = to;
  20511. this._loopAnimation = loop;
  20512. this._delay = delay;
  20513. this._animationStarted = true;
  20514. this._direction = from < to ? 1 : -1;
  20515. this.cellIndex = from;
  20516. this._time = 0;
  20517. };
  20518. Sprite.prototype.stopAnimation = function () {
  20519. this._animationStarted = false;
  20520. };
  20521. Sprite.prototype._animate = function (deltaTime) {
  20522. if (!this._animationStarted)
  20523. return;
  20524. this._time += deltaTime;
  20525. if (this._time > this._delay) {
  20526. this._time = this._time % this._delay;
  20527. this.cellIndex += this._direction;
  20528. if (this.cellIndex == this._toIndex) {
  20529. if (this._loopAnimation) {
  20530. this.cellIndex = this._fromIndex;
  20531. }
  20532. else {
  20533. this._animationStarted = false;
  20534. if (this.disposeWhenFinishedAnimating) {
  20535. this.dispose();
  20536. }
  20537. }
  20538. }
  20539. }
  20540. };
  20541. Sprite.prototype.dispose = function () {
  20542. for (var i = 0; i < this._manager.sprites.length; i++) {
  20543. if (this._manager.sprites[i] == this) {
  20544. this._manager.sprites.splice(i, 1);
  20545. }
  20546. }
  20547. };
  20548. return Sprite;
  20549. })();
  20550. BABYLON.Sprite = Sprite;
  20551. })(BABYLON || (BABYLON = {}));
  20552. var BABYLON;
  20553. (function (BABYLON) {
  20554. var Layer = (function () {
  20555. function Layer(name, imgUrl, scene, isBackground, color) {
  20556. this.name = name;
  20557. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20558. this._vertexDeclaration = [2];
  20559. this._vertexStrideSize = 2 * 4;
  20560. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20561. this.isBackground = isBackground === undefined ? true : isBackground;
  20562. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20563. this._scene = scene;
  20564. this._scene.layers.push(this);
  20565. // VBO
  20566. var vertices = [];
  20567. vertices.push(1, 1);
  20568. vertices.push(-1, 1);
  20569. vertices.push(-1, -1);
  20570. vertices.push(1, -1);
  20571. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20572. // Indices
  20573. var indices = [];
  20574. indices.push(0);
  20575. indices.push(1);
  20576. indices.push(2);
  20577. indices.push(0);
  20578. indices.push(2);
  20579. indices.push(3);
  20580. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20581. // Effects
  20582. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20583. }
  20584. Layer.prototype.render = function () {
  20585. // Check
  20586. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20587. return;
  20588. var engine = this._scene.getEngine();
  20589. // Render
  20590. engine.enableEffect(this._effect);
  20591. engine.setState(false);
  20592. // Texture
  20593. this._effect.setTexture("textureSampler", this.texture);
  20594. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20595. // Color
  20596. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20597. // VBOs
  20598. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20599. // Draw order
  20600. engine.setAlphaMode(this.alphaBlendingMode);
  20601. engine.draw(true, 0, 6);
  20602. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20603. };
  20604. Layer.prototype.dispose = function () {
  20605. if (this._vertexBuffer) {
  20606. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20607. this._vertexBuffer = null;
  20608. }
  20609. if (this._indexBuffer) {
  20610. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20611. this._indexBuffer = null;
  20612. }
  20613. if (this.texture) {
  20614. this.texture.dispose();
  20615. this.texture = null;
  20616. }
  20617. // Remove from scene
  20618. var index = this._scene.layers.indexOf(this);
  20619. this._scene.layers.splice(index, 1);
  20620. // Callback
  20621. if (this.onDispose) {
  20622. this.onDispose();
  20623. }
  20624. };
  20625. return Layer;
  20626. })();
  20627. BABYLON.Layer = Layer;
  20628. })(BABYLON || (BABYLON = {}));
  20629. var BABYLON;
  20630. (function (BABYLON) {
  20631. var Particle = (function () {
  20632. function Particle() {
  20633. this.position = BABYLON.Vector3.Zero();
  20634. this.direction = BABYLON.Vector3.Zero();
  20635. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20636. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20637. this.lifeTime = 1.0;
  20638. this.age = 0;
  20639. this.size = 0;
  20640. this.angle = 0;
  20641. this.angularSpeed = 0;
  20642. }
  20643. Particle.prototype.copyTo = function (other) {
  20644. other.position.copyFrom(this.position);
  20645. other.direction.copyFrom(this.direction);
  20646. other.color.copyFrom(this.color);
  20647. other.colorStep.copyFrom(this.colorStep);
  20648. other.lifeTime = this.lifeTime;
  20649. other.age = this.age;
  20650. other.size = this.size;
  20651. other.angle = this.angle;
  20652. other.angularSpeed = this.angularSpeed;
  20653. };
  20654. return Particle;
  20655. })();
  20656. BABYLON.Particle = Particle;
  20657. })(BABYLON || (BABYLON = {}));
  20658. var BABYLON;
  20659. (function (BABYLON) {
  20660. var randomNumber = function (min, max) {
  20661. if (min === max) {
  20662. return (min);
  20663. }
  20664. var random = Math.random();
  20665. return ((random * (max - min)) + min);
  20666. };
  20667. var ParticleSystem = (function () {
  20668. function ParticleSystem(name, capacity, scene, customEffect) {
  20669. var _this = this;
  20670. this.name = name;
  20671. this.renderingGroupId = 0;
  20672. this.emitter = null;
  20673. this.emitRate = 10;
  20674. this.manualEmitCount = -1;
  20675. this.updateSpeed = 0.01;
  20676. this.targetStopDuration = 0;
  20677. this.disposeOnStop = false;
  20678. this.minEmitPower = 1;
  20679. this.maxEmitPower = 1;
  20680. this.minLifeTime = 1;
  20681. this.maxLifeTime = 1;
  20682. this.minSize = 1;
  20683. this.maxSize = 1;
  20684. this.minAngularSpeed = 0;
  20685. this.maxAngularSpeed = 0;
  20686. this.layerMask = 0x0FFFFFFF;
  20687. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20688. this.forceDepthWrite = false;
  20689. this.gravity = BABYLON.Vector3.Zero();
  20690. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20691. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20692. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20693. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20694. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20695. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20696. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20697. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20698. this.particles = new Array();
  20699. this._vertexDeclaration = [3, 4, 4];
  20700. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20701. this._stockParticles = new Array();
  20702. this._newPartsExcess = 0;
  20703. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20704. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20705. this._scaledDirection = BABYLON.Vector3.Zero();
  20706. this._scaledGravity = BABYLON.Vector3.Zero();
  20707. this._currentRenderId = -1;
  20708. this._started = false;
  20709. this._stopped = false;
  20710. this._actualFrame = 0;
  20711. this.id = name;
  20712. this._capacity = capacity;
  20713. this._scene = scene;
  20714. this._customEffect = customEffect;
  20715. scene.particleSystems.push(this);
  20716. // VBO
  20717. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20718. var indices = [];
  20719. var index = 0;
  20720. for (var count = 0; count < capacity; count++) {
  20721. indices.push(index);
  20722. indices.push(index + 1);
  20723. indices.push(index + 2);
  20724. indices.push(index);
  20725. indices.push(index + 2);
  20726. indices.push(index + 3);
  20727. index += 4;
  20728. }
  20729. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20730. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20731. // Default behaviors
  20732. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20733. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20734. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20735. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20736. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20737. };
  20738. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20739. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20740. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20741. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20742. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20743. };
  20744. this.updateFunction = function (particles) {
  20745. for (var index = 0; index < particles.length; index++) {
  20746. var particle = particles[index];
  20747. particle.age += _this._scaledUpdateSpeed;
  20748. if (particle.age >= particle.lifeTime) {
  20749. _this.recycleParticle(particle);
  20750. index--;
  20751. continue;
  20752. }
  20753. else {
  20754. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20755. particle.color.addInPlace(_this._scaledColorStep);
  20756. if (particle.color.a < 0)
  20757. particle.color.a = 0;
  20758. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20759. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20760. particle.position.addInPlace(_this._scaledDirection);
  20761. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20762. particle.direction.addInPlace(_this._scaledGravity);
  20763. }
  20764. }
  20765. };
  20766. }
  20767. ParticleSystem.prototype.recycleParticle = function (particle) {
  20768. var lastParticle = this.particles.pop();
  20769. if (lastParticle !== particle) {
  20770. lastParticle.copyTo(particle);
  20771. this._stockParticles.push(lastParticle);
  20772. }
  20773. };
  20774. ParticleSystem.prototype.getCapacity = function () {
  20775. return this._capacity;
  20776. };
  20777. ParticleSystem.prototype.isAlive = function () {
  20778. return this._alive;
  20779. };
  20780. ParticleSystem.prototype.isStarted = function () {
  20781. return this._started;
  20782. };
  20783. ParticleSystem.prototype.start = function () {
  20784. this._started = true;
  20785. this._stopped = false;
  20786. this._actualFrame = 0;
  20787. };
  20788. ParticleSystem.prototype.stop = function () {
  20789. this._stopped = true;
  20790. };
  20791. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20792. var offset = index * 11;
  20793. this._vertices[offset] = particle.position.x;
  20794. this._vertices[offset + 1] = particle.position.y;
  20795. this._vertices[offset + 2] = particle.position.z;
  20796. this._vertices[offset + 3] = particle.color.r;
  20797. this._vertices[offset + 4] = particle.color.g;
  20798. this._vertices[offset + 5] = particle.color.b;
  20799. this._vertices[offset + 6] = particle.color.a;
  20800. this._vertices[offset + 7] = particle.angle;
  20801. this._vertices[offset + 8] = particle.size;
  20802. this._vertices[offset + 9] = offsetX;
  20803. this._vertices[offset + 10] = offsetY;
  20804. };
  20805. ParticleSystem.prototype._update = function (newParticles) {
  20806. // Update current
  20807. this._alive = this.particles.length > 0;
  20808. this.updateFunction(this.particles);
  20809. // Add new ones
  20810. var worldMatrix;
  20811. if (this.emitter.position) {
  20812. worldMatrix = this.emitter.getWorldMatrix();
  20813. }
  20814. else {
  20815. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20816. }
  20817. var particle;
  20818. for (var index = 0; index < newParticles; index++) {
  20819. if (this.particles.length === this._capacity) {
  20820. break;
  20821. }
  20822. if (this._stockParticles.length !== 0) {
  20823. particle = this._stockParticles.pop();
  20824. particle.age = 0;
  20825. }
  20826. else {
  20827. particle = new BABYLON.Particle();
  20828. }
  20829. this.particles.push(particle);
  20830. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20831. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  20832. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20833. particle.size = randomNumber(this.minSize, this.maxSize);
  20834. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20835. this.startPositionFunction(worldMatrix, particle.position, particle);
  20836. var step = randomNumber(0, 1.0);
  20837. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20838. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20839. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20840. }
  20841. };
  20842. ParticleSystem.prototype._getEffect = function () {
  20843. if (this._customEffect) {
  20844. return this._customEffect;
  20845. }
  20846. ;
  20847. var defines = [];
  20848. if (this._scene.clipPlane) {
  20849. defines.push("#define CLIPPLANE");
  20850. }
  20851. // Effect
  20852. var join = defines.join("\n");
  20853. if (this._cachedDefines !== join) {
  20854. this._cachedDefines = join;
  20855. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20856. }
  20857. return this._effect;
  20858. };
  20859. ParticleSystem.prototype.animate = function () {
  20860. if (!this._started)
  20861. return;
  20862. var effect = this._getEffect();
  20863. // Check
  20864. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20865. return;
  20866. if (this._currentRenderId === this._scene.getRenderId()) {
  20867. return;
  20868. }
  20869. this._currentRenderId = this._scene.getRenderId();
  20870. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20871. // determine the number of particles we need to create
  20872. var emitCout;
  20873. if (this.manualEmitCount > -1) {
  20874. emitCout = this.manualEmitCount;
  20875. this.manualEmitCount = 0;
  20876. }
  20877. else {
  20878. emitCout = this.emitRate;
  20879. }
  20880. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20881. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20882. if (this._newPartsExcess > 1.0) {
  20883. newParticles += this._newPartsExcess >> 0;
  20884. this._newPartsExcess -= this._newPartsExcess >> 0;
  20885. }
  20886. this._alive = false;
  20887. if (!this._stopped) {
  20888. this._actualFrame += this._scaledUpdateSpeed;
  20889. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20890. this.stop();
  20891. }
  20892. else {
  20893. newParticles = 0;
  20894. }
  20895. this._update(newParticles);
  20896. // Stopped?
  20897. if (this._stopped) {
  20898. if (!this._alive) {
  20899. this._started = false;
  20900. if (this.disposeOnStop) {
  20901. this._scene._toBeDisposed.push(this);
  20902. }
  20903. }
  20904. }
  20905. // Update VBO
  20906. var offset = 0;
  20907. for (var index = 0; index < this.particles.length; index++) {
  20908. var particle = this.particles[index];
  20909. this._appendParticleVertex(offset++, particle, 0, 0);
  20910. this._appendParticleVertex(offset++, particle, 1, 0);
  20911. this._appendParticleVertex(offset++, particle, 1, 1);
  20912. this._appendParticleVertex(offset++, particle, 0, 1);
  20913. }
  20914. var engine = this._scene.getEngine();
  20915. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20916. };
  20917. ParticleSystem.prototype.render = function () {
  20918. var effect = this._getEffect();
  20919. // Check
  20920. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20921. return 0;
  20922. var engine = this._scene.getEngine();
  20923. // Render
  20924. engine.enableEffect(effect);
  20925. engine.setState(false);
  20926. var viewMatrix = this._scene.getViewMatrix();
  20927. effect.setTexture("diffuseSampler", this.particleTexture);
  20928. effect.setMatrix("view", viewMatrix);
  20929. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20930. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20931. if (this._scene.clipPlane) {
  20932. var clipPlane = this._scene.clipPlane;
  20933. var invView = viewMatrix.clone();
  20934. invView.invert();
  20935. effect.setMatrix("invView", invView);
  20936. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20937. }
  20938. // VBOs
  20939. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20940. // Draw order
  20941. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20942. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  20943. }
  20944. else {
  20945. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20946. }
  20947. if (this.forceDepthWrite) {
  20948. engine.setDepthWrite(true);
  20949. }
  20950. engine.draw(true, 0, this.particles.length * 6);
  20951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20952. return this.particles.length;
  20953. };
  20954. ParticleSystem.prototype.dispose = function () {
  20955. if (this._vertexBuffer) {
  20956. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20957. this._vertexBuffer = null;
  20958. }
  20959. if (this._indexBuffer) {
  20960. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20961. this._indexBuffer = null;
  20962. }
  20963. if (this.particleTexture) {
  20964. this.particleTexture.dispose();
  20965. this.particleTexture = null;
  20966. }
  20967. // Remove from scene
  20968. var index = this._scene.particleSystems.indexOf(this);
  20969. this._scene.particleSystems.splice(index, 1);
  20970. // Callback
  20971. if (this.onDispose) {
  20972. this.onDispose();
  20973. }
  20974. };
  20975. // Clone
  20976. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20977. var result = new ParticleSystem(name, this._capacity, this._scene);
  20978. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20979. if (newEmitter === undefined) {
  20980. newEmitter = this.emitter;
  20981. }
  20982. result.emitter = newEmitter;
  20983. if (this.particleTexture) {
  20984. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20985. }
  20986. result.start();
  20987. return result;
  20988. };
  20989. ParticleSystem.prototype.serialize = function () {
  20990. var serializationObject = {};
  20991. serializationObject.emitterId = this.emitter.id;
  20992. serializationObject.capacity = this.getCapacity();
  20993. if (this.particleTexture) {
  20994. serializationObject.textureName = this.particleTexture.name;
  20995. }
  20996. serializationObject.minAngularSpeed = this.minAngularSpeed;
  20997. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  20998. serializationObject.minSize = this.minSize;
  20999. serializationObject.maxSize = this.maxSize;
  21000. serializationObject.minLifeTime = this.minLifeTime;
  21001. serializationObject.maxLifeTime = this.maxLifeTime;
  21002. serializationObject.emitRate = this.emitRate;
  21003. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21004. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21005. serializationObject.gravity = this.gravity.asArray();
  21006. serializationObject.direction1 = this.direction1.asArray();
  21007. serializationObject.direction2 = this.direction2.asArray();
  21008. serializationObject.color1 = this.color1.asArray();
  21009. serializationObject.color2 = this.color2.asArray();
  21010. serializationObject.colorDead = this.colorDead.asArray();
  21011. serializationObject.updateSpeed = this.updateSpeed;
  21012. serializationObject.targetStopDuration = this.targetStopDuration;
  21013. serializationObject.textureMask = this.textureMask.asArray();
  21014. serializationObject.blendMode = this.blendMode;
  21015. return serializationObject;
  21016. };
  21017. ParticleSystem.ParseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  21018. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21019. var particleSystem = new ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  21020. if (parsedParticleSystem.textureName) {
  21021. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21022. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21023. }
  21024. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21025. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21026. particleSystem.minSize = parsedParticleSystem.minSize;
  21027. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21028. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21029. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21030. particleSystem.emitter = emitter;
  21031. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21032. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21033. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21034. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21035. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21036. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21037. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21038. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21039. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21040. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21041. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  21042. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21043. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21044. particleSystem.start();
  21045. return particleSystem;
  21046. };
  21047. // Statics
  21048. ParticleSystem.BLENDMODE_ONEONE = 0;
  21049. ParticleSystem.BLENDMODE_STANDARD = 1;
  21050. return ParticleSystem;
  21051. })();
  21052. BABYLON.ParticleSystem = ParticleSystem;
  21053. })(BABYLON || (BABYLON = {}));
  21054. var BABYLON;
  21055. (function (BABYLON) {
  21056. var AnimationRange = (function () {
  21057. function AnimationRange(name, from, to) {
  21058. this.name = name;
  21059. this.from = from;
  21060. this.to = to;
  21061. }
  21062. return AnimationRange;
  21063. })();
  21064. BABYLON.AnimationRange = AnimationRange;
  21065. /**
  21066. * Composed of a frame, and an action function
  21067. */
  21068. var AnimationEvent = (function () {
  21069. function AnimationEvent(frame, action, onlyOnce) {
  21070. this.frame = frame;
  21071. this.action = action;
  21072. this.onlyOnce = onlyOnce;
  21073. this.isDone = false;
  21074. }
  21075. return AnimationEvent;
  21076. })();
  21077. BABYLON.AnimationEvent = AnimationEvent;
  21078. var Animation = (function () {
  21079. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21080. this.name = name;
  21081. this.targetProperty = targetProperty;
  21082. this.framePerSecond = framePerSecond;
  21083. this.dataType = dataType;
  21084. this.loopMode = loopMode;
  21085. this._offsetsCache = {};
  21086. this._highLimitsCache = {};
  21087. this._stopped = false;
  21088. // The set of event that will be linked to this animation
  21089. this._events = new Array();
  21090. this.allowMatricesInterpolation = false;
  21091. this._ranges = new Array();
  21092. this.targetPropertyPath = targetProperty.split(".");
  21093. this.dataType = dataType;
  21094. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21095. }
  21096. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21097. var dataType = undefined;
  21098. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21099. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21100. }
  21101. else if (from instanceof BABYLON.Quaternion) {
  21102. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21103. }
  21104. else if (from instanceof BABYLON.Vector3) {
  21105. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21106. }
  21107. else if (from instanceof BABYLON.Vector2) {
  21108. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21109. }
  21110. else if (from instanceof BABYLON.Color3) {
  21111. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21112. }
  21113. if (dataType == undefined) {
  21114. return null;
  21115. }
  21116. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21117. var keys = [];
  21118. keys.push({ frame: 0, value: from });
  21119. keys.push({ frame: totalFrame, value: to });
  21120. animation.setKeys(keys);
  21121. if (easingFunction !== undefined) {
  21122. animation.setEasingFunction(easingFunction);
  21123. }
  21124. return animation;
  21125. };
  21126. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21127. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21128. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21129. };
  21130. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21131. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21132. node.animations.push(animation);
  21133. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21134. };
  21135. // Methods
  21136. /**
  21137. * Add an event to this animation.
  21138. */
  21139. Animation.prototype.addEvent = function (event) {
  21140. this._events.push(event);
  21141. };
  21142. /**
  21143. * Remove all events found at the given frame
  21144. * @param frame
  21145. */
  21146. Animation.prototype.removeEvents = function (frame) {
  21147. for (var index = 0; index < this._events.length; index++) {
  21148. if (this._events[index].frame === frame) {
  21149. this._events.splice(index, 1);
  21150. index--;
  21151. }
  21152. }
  21153. };
  21154. Animation.prototype.createRange = function (name, from, to) {
  21155. this._ranges.push(new AnimationRange(name, from, to));
  21156. };
  21157. Animation.prototype.deleteRange = function (name) {
  21158. for (var index = 0; index < this._ranges.length; index++) {
  21159. if (this._ranges[index].name === name) {
  21160. this._ranges.splice(index, 1);
  21161. return;
  21162. }
  21163. }
  21164. };
  21165. Animation.prototype.getRange = function (name) {
  21166. for (var index = 0; index < this._ranges.length; index++) {
  21167. if (this._ranges[index].name === name) {
  21168. return this._ranges[index];
  21169. }
  21170. }
  21171. return null;
  21172. };
  21173. Animation.prototype.reset = function () {
  21174. this._offsetsCache = {};
  21175. this._highLimitsCache = {};
  21176. this.currentFrame = 0;
  21177. };
  21178. Animation.prototype.isStopped = function () {
  21179. return this._stopped;
  21180. };
  21181. Animation.prototype.getKeys = function () {
  21182. return this._keys;
  21183. };
  21184. Animation.prototype.getEasingFunction = function () {
  21185. return this._easingFunction;
  21186. };
  21187. Animation.prototype.setEasingFunction = function (easingFunction) {
  21188. this._easingFunction = easingFunction;
  21189. };
  21190. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21191. return startValue + (endValue - startValue) * gradient;
  21192. };
  21193. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21194. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21195. };
  21196. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21197. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21198. };
  21199. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21200. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21201. };
  21202. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21203. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21204. };
  21205. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21206. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21207. };
  21208. Animation.prototype.clone = function () {
  21209. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21210. if (this._keys) {
  21211. clone.setKeys(this._keys);
  21212. }
  21213. return clone;
  21214. };
  21215. Animation.prototype.setKeys = function (values) {
  21216. this._keys = values.slice(0);
  21217. this._offsetsCache = {};
  21218. this._highLimitsCache = {};
  21219. };
  21220. Animation.prototype._getKeyValue = function (value) {
  21221. if (typeof value === "function") {
  21222. return value();
  21223. }
  21224. return value;
  21225. };
  21226. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21227. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21228. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21229. }
  21230. this.currentFrame = currentFrame;
  21231. // Try to get a hash to find the right key
  21232. 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));
  21233. if (this._keys[startKey].frame >= currentFrame) {
  21234. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21235. startKey--;
  21236. }
  21237. }
  21238. for (var key = startKey; key < this._keys.length; key++) {
  21239. if (this._keys[key + 1].frame >= currentFrame) {
  21240. var startValue = this._getKeyValue(this._keys[key].value);
  21241. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21242. // gradient : percent of currentFrame between the frame inf and the frame sup
  21243. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21244. // check for easingFunction and correction of gradient
  21245. if (this._easingFunction != null) {
  21246. gradient = this._easingFunction.ease(gradient);
  21247. }
  21248. switch (this.dataType) {
  21249. // Float
  21250. case Animation.ANIMATIONTYPE_FLOAT:
  21251. switch (loopMode) {
  21252. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21253. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21254. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21255. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21256. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21257. }
  21258. break;
  21259. // Quaternion
  21260. case Animation.ANIMATIONTYPE_QUATERNION:
  21261. var quaternion = null;
  21262. switch (loopMode) {
  21263. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21264. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21265. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21266. break;
  21267. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21268. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21269. break;
  21270. }
  21271. return quaternion;
  21272. // Vector3
  21273. case Animation.ANIMATIONTYPE_VECTOR3:
  21274. switch (loopMode) {
  21275. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21276. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21277. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21278. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21279. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21280. }
  21281. // Vector2
  21282. case Animation.ANIMATIONTYPE_VECTOR2:
  21283. switch (loopMode) {
  21284. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21285. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21286. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21287. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21288. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21289. }
  21290. // Color3
  21291. case Animation.ANIMATIONTYPE_COLOR3:
  21292. switch (loopMode) {
  21293. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21294. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21295. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21296. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21297. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21298. }
  21299. // Matrix
  21300. case Animation.ANIMATIONTYPE_MATRIX:
  21301. switch (loopMode) {
  21302. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21303. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21304. if (this.allowMatricesInterpolation) {
  21305. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21306. }
  21307. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21308. return startValue;
  21309. }
  21310. default:
  21311. break;
  21312. }
  21313. break;
  21314. }
  21315. }
  21316. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21317. };
  21318. Animation.prototype.setValue = function (currentValue) {
  21319. // Set value
  21320. if (this.targetPropertyPath.length > 1) {
  21321. var property = this._target[this.targetPropertyPath[0]];
  21322. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21323. property = property[this.targetPropertyPath[index]];
  21324. }
  21325. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21326. }
  21327. else {
  21328. this._target[this.targetPropertyPath[0]] = currentValue;
  21329. }
  21330. if (this._target.markAsDirty) {
  21331. this._target.markAsDirty(this.targetProperty);
  21332. }
  21333. };
  21334. Animation.prototype.goToFrame = function (frame) {
  21335. if (frame < this._keys[0].frame) {
  21336. frame = this._keys[0].frame;
  21337. }
  21338. else if (frame > this._keys[this._keys.length - 1].frame) {
  21339. frame = this._keys[this._keys.length - 1].frame;
  21340. }
  21341. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21342. this.setValue(currentValue);
  21343. };
  21344. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21345. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21346. this._stopped = true;
  21347. return false;
  21348. }
  21349. var returnValue = true;
  21350. // Adding a start key at frame 0 if missing
  21351. if (this._keys[0].frame !== 0) {
  21352. var newKey = { frame: 0, value: this._keys[0].value };
  21353. this._keys.splice(0, 0, newKey);
  21354. }
  21355. // Check limits
  21356. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21357. from = this._keys[0].frame;
  21358. }
  21359. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21360. to = this._keys[this._keys.length - 1].frame;
  21361. }
  21362. // Compute ratio
  21363. var range = to - from;
  21364. var offsetValue;
  21365. // ratio represents the frame delta between from and to
  21366. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21367. var highLimitValue = 0;
  21368. if (ratio > range && !loop) {
  21369. returnValue = false;
  21370. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21371. }
  21372. else {
  21373. // Get max value if required
  21374. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21375. var keyOffset = to.toString() + from.toString();
  21376. if (!this._offsetsCache[keyOffset]) {
  21377. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21378. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21379. switch (this.dataType) {
  21380. // Float
  21381. case Animation.ANIMATIONTYPE_FLOAT:
  21382. this._offsetsCache[keyOffset] = toValue - fromValue;
  21383. break;
  21384. // Quaternion
  21385. case Animation.ANIMATIONTYPE_QUATERNION:
  21386. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21387. break;
  21388. // Vector3
  21389. case Animation.ANIMATIONTYPE_VECTOR3:
  21390. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21391. // Vector2
  21392. case Animation.ANIMATIONTYPE_VECTOR2:
  21393. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21394. // Color3
  21395. case Animation.ANIMATIONTYPE_COLOR3:
  21396. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21397. default:
  21398. break;
  21399. }
  21400. this._highLimitsCache[keyOffset] = toValue;
  21401. }
  21402. highLimitValue = this._highLimitsCache[keyOffset];
  21403. offsetValue = this._offsetsCache[keyOffset];
  21404. }
  21405. }
  21406. if (offsetValue === undefined) {
  21407. switch (this.dataType) {
  21408. // Float
  21409. case Animation.ANIMATIONTYPE_FLOAT:
  21410. offsetValue = 0;
  21411. break;
  21412. // Quaternion
  21413. case Animation.ANIMATIONTYPE_QUATERNION:
  21414. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21415. break;
  21416. // Vector3
  21417. case Animation.ANIMATIONTYPE_VECTOR3:
  21418. offsetValue = BABYLON.Vector3.Zero();
  21419. break;
  21420. // Vector2
  21421. case Animation.ANIMATIONTYPE_VECTOR2:
  21422. offsetValue = BABYLON.Vector2.Zero();
  21423. break;
  21424. // Color3
  21425. case Animation.ANIMATIONTYPE_COLOR3:
  21426. offsetValue = BABYLON.Color3.Black();
  21427. }
  21428. }
  21429. // Compute value
  21430. var repeatCount = (ratio / range) >> 0;
  21431. var currentFrame = returnValue ? from + ratio % range : to;
  21432. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21433. // Check events
  21434. for (var index = 0; index < this._events.length; index++) {
  21435. if (currentFrame >= this._events[index].frame) {
  21436. var event = this._events[index];
  21437. if (!event.isDone) {
  21438. // If event should be done only once, remove it.
  21439. if (event.onlyOnce) {
  21440. this._events.splice(index, 1);
  21441. index--;
  21442. }
  21443. event.isDone = true;
  21444. event.action();
  21445. } // Don't do anything if the event has already be done.
  21446. }
  21447. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21448. // reset event, the animation is looping
  21449. this._events[index].isDone = false;
  21450. }
  21451. }
  21452. // Set value
  21453. this.setValue(currentValue);
  21454. if (!returnValue) {
  21455. this._stopped = true;
  21456. }
  21457. return returnValue;
  21458. };
  21459. Animation.prototype.serialize = function () {
  21460. var serializationObject = {};
  21461. serializationObject.name = this.name;
  21462. serializationObject.property = this.targetProperty;
  21463. serializationObject.framePerSecond = this.framePerSecond;
  21464. serializationObject.dataType = this.dataType;
  21465. serializationObject.loopBehavior = this.loopMode;
  21466. var dataType = this.dataType;
  21467. serializationObject.keys = [];
  21468. var keys = this.getKeys();
  21469. for (var index = 0; index < keys.length; index++) {
  21470. var animationKey = keys[index];
  21471. var key = {};
  21472. key.frame = animationKey.frame;
  21473. switch (dataType) {
  21474. case Animation.ANIMATIONTYPE_FLOAT:
  21475. key.values = [animationKey.value];
  21476. break;
  21477. case Animation.ANIMATIONTYPE_QUATERNION:
  21478. case Animation.ANIMATIONTYPE_MATRIX:
  21479. case Animation.ANIMATIONTYPE_VECTOR3:
  21480. key.values = animationKey.value.asArray();
  21481. break;
  21482. }
  21483. serializationObject.keys.push(key);
  21484. }
  21485. return serializationObject;
  21486. };
  21487. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21488. get: function () {
  21489. return Animation._ANIMATIONTYPE_FLOAT;
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21495. get: function () {
  21496. return Animation._ANIMATIONTYPE_VECTOR3;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21502. get: function () {
  21503. return Animation._ANIMATIONTYPE_VECTOR2;
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21509. get: function () {
  21510. return Animation._ANIMATIONTYPE_QUATERNION;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21516. get: function () {
  21517. return Animation._ANIMATIONTYPE_MATRIX;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21523. get: function () {
  21524. return Animation._ANIMATIONTYPE_COLOR3;
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21530. get: function () {
  21531. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21537. get: function () {
  21538. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21544. get: function () {
  21545. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. Animation.ParseAnimation = function (parsedAnimation) {
  21551. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21552. var dataType = parsedAnimation.dataType;
  21553. var keys = [];
  21554. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21555. var key = parsedAnimation.keys[index];
  21556. var data;
  21557. switch (dataType) {
  21558. case Animation.ANIMATIONTYPE_FLOAT:
  21559. data = key.values[0];
  21560. break;
  21561. case Animation.ANIMATIONTYPE_QUATERNION:
  21562. data = BABYLON.Quaternion.FromArray(key.values);
  21563. break;
  21564. case Animation.ANIMATIONTYPE_MATRIX:
  21565. data = BABYLON.Matrix.FromArray(key.values);
  21566. break;
  21567. case Animation.ANIMATIONTYPE_VECTOR3:
  21568. default:
  21569. data = BABYLON.Vector3.FromArray(key.values);
  21570. break;
  21571. }
  21572. keys.push({
  21573. frame: key.frame,
  21574. value: data
  21575. });
  21576. }
  21577. animation.setKeys(keys);
  21578. return animation;
  21579. };
  21580. Animation.AppendSerializedAnimations = function (source, destination) {
  21581. if (source.animations) {
  21582. destination.animations = [];
  21583. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21584. var animation = source.animations[animationIndex];
  21585. destination.animations.push(animation.serialize());
  21586. }
  21587. }
  21588. };
  21589. // Statics
  21590. Animation._ANIMATIONTYPE_FLOAT = 0;
  21591. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21592. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21593. Animation._ANIMATIONTYPE_MATRIX = 3;
  21594. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21595. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21596. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21597. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21598. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21599. return Animation;
  21600. })();
  21601. BABYLON.Animation = Animation;
  21602. })(BABYLON || (BABYLON = {}));
  21603. var BABYLON;
  21604. (function (BABYLON) {
  21605. var Animatable = (function () {
  21606. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21607. if (fromFrame === void 0) { fromFrame = 0; }
  21608. if (toFrame === void 0) { toFrame = 100; }
  21609. if (loopAnimation === void 0) { loopAnimation = false; }
  21610. if (speedRatio === void 0) { speedRatio = 1.0; }
  21611. this.target = target;
  21612. this.fromFrame = fromFrame;
  21613. this.toFrame = toFrame;
  21614. this.loopAnimation = loopAnimation;
  21615. this.speedRatio = speedRatio;
  21616. this.onAnimationEnd = onAnimationEnd;
  21617. this._animations = new Array();
  21618. this._paused = false;
  21619. this.animationStarted = false;
  21620. if (animations) {
  21621. this.appendAnimations(target, animations);
  21622. }
  21623. this._scene = scene;
  21624. scene._activeAnimatables.push(this);
  21625. }
  21626. // Methods
  21627. Animatable.prototype.getAnimations = function () {
  21628. return this._animations;
  21629. };
  21630. Animatable.prototype.appendAnimations = function (target, animations) {
  21631. for (var index = 0; index < animations.length; index++) {
  21632. var animation = animations[index];
  21633. animation._target = target;
  21634. this._animations.push(animation);
  21635. }
  21636. };
  21637. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21638. var animations = this._animations;
  21639. for (var index = 0; index < animations.length; index++) {
  21640. if (animations[index].targetProperty === property) {
  21641. return animations[index];
  21642. }
  21643. }
  21644. return null;
  21645. };
  21646. Animatable.prototype.reset = function () {
  21647. var animations = this._animations;
  21648. for (var index = 0; index < animations.length; index++) {
  21649. animations[index].reset();
  21650. }
  21651. this._localDelayOffset = null;
  21652. this._pausedDelay = null;
  21653. };
  21654. Animatable.prototype.goToFrame = function (frame) {
  21655. var animations = this._animations;
  21656. for (var index = 0; index < animations.length; index++) {
  21657. animations[index].goToFrame(frame);
  21658. }
  21659. };
  21660. Animatable.prototype.pause = function () {
  21661. if (this._paused) {
  21662. return;
  21663. }
  21664. this._paused = true;
  21665. };
  21666. Animatable.prototype.restart = function () {
  21667. this._paused = false;
  21668. };
  21669. Animatable.prototype.stop = function () {
  21670. var index = this._scene._activeAnimatables.indexOf(this);
  21671. if (index > -1) {
  21672. this._scene._activeAnimatables.splice(index, 1);
  21673. }
  21674. if (this.onAnimationEnd) {
  21675. this.onAnimationEnd();
  21676. }
  21677. };
  21678. Animatable.prototype._animate = function (delay) {
  21679. if (this._paused) {
  21680. this.animationStarted = false;
  21681. if (!this._pausedDelay) {
  21682. this._pausedDelay = delay;
  21683. }
  21684. return true;
  21685. }
  21686. if (!this._localDelayOffset) {
  21687. this._localDelayOffset = delay;
  21688. }
  21689. else if (this._pausedDelay) {
  21690. this._localDelayOffset += delay - this._pausedDelay;
  21691. this._pausedDelay = null;
  21692. }
  21693. // Animating
  21694. var running = false;
  21695. var animations = this._animations;
  21696. var index;
  21697. for (index = 0; index < animations.length; index++) {
  21698. var animation = animations[index];
  21699. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21700. running = running || isRunning;
  21701. }
  21702. this.animationStarted = running;
  21703. if (!running) {
  21704. // Remove from active animatables
  21705. index = this._scene._activeAnimatables.indexOf(this);
  21706. this._scene._activeAnimatables.splice(index, 1);
  21707. }
  21708. if (!running && this.onAnimationEnd) {
  21709. this.onAnimationEnd();
  21710. }
  21711. return running;
  21712. };
  21713. return Animatable;
  21714. })();
  21715. BABYLON.Animatable = Animatable;
  21716. })(BABYLON || (BABYLON = {}));
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var EasingFunction = (function () {
  21720. function EasingFunction() {
  21721. // Properties
  21722. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21723. }
  21724. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21725. get: function () {
  21726. return EasingFunction._EASINGMODE_EASEIN;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21732. get: function () {
  21733. return EasingFunction._EASINGMODE_EASEOUT;
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21739. get: function () {
  21740. return EasingFunction._EASINGMODE_EASEINOUT;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21746. var n = Math.min(Math.max(easingMode, 0), 2);
  21747. this._easingMode = n;
  21748. };
  21749. EasingFunction.prototype.getEasingMode = function () {
  21750. return this._easingMode;
  21751. };
  21752. EasingFunction.prototype.easeInCore = function (gradient) {
  21753. throw new Error('You must implement this method');
  21754. };
  21755. EasingFunction.prototype.ease = function (gradient) {
  21756. switch (this._easingMode) {
  21757. case EasingFunction.EASINGMODE_EASEIN:
  21758. return this.easeInCore(gradient);
  21759. case EasingFunction.EASINGMODE_EASEOUT:
  21760. return (1 - this.easeInCore(1 - gradient));
  21761. }
  21762. if (gradient >= 0.5) {
  21763. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21764. }
  21765. return (this.easeInCore(gradient * 2) * 0.5);
  21766. };
  21767. //Statics
  21768. EasingFunction._EASINGMODE_EASEIN = 0;
  21769. EasingFunction._EASINGMODE_EASEOUT = 1;
  21770. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21771. return EasingFunction;
  21772. })();
  21773. BABYLON.EasingFunction = EasingFunction;
  21774. var CircleEase = (function (_super) {
  21775. __extends(CircleEase, _super);
  21776. function CircleEase() {
  21777. _super.apply(this, arguments);
  21778. }
  21779. CircleEase.prototype.easeInCore = function (gradient) {
  21780. gradient = Math.max(0, Math.min(1, gradient));
  21781. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21782. };
  21783. return CircleEase;
  21784. })(EasingFunction);
  21785. BABYLON.CircleEase = CircleEase;
  21786. var BackEase = (function (_super) {
  21787. __extends(BackEase, _super);
  21788. function BackEase(amplitude) {
  21789. if (amplitude === void 0) { amplitude = 1; }
  21790. _super.call(this);
  21791. this.amplitude = amplitude;
  21792. }
  21793. BackEase.prototype.easeInCore = function (gradient) {
  21794. var num = Math.max(0, this.amplitude);
  21795. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21796. };
  21797. return BackEase;
  21798. })(EasingFunction);
  21799. BABYLON.BackEase = BackEase;
  21800. var BounceEase = (function (_super) {
  21801. __extends(BounceEase, _super);
  21802. function BounceEase(bounces, bounciness) {
  21803. if (bounces === void 0) { bounces = 3; }
  21804. if (bounciness === void 0) { bounciness = 2; }
  21805. _super.call(this);
  21806. this.bounces = bounces;
  21807. this.bounciness = bounciness;
  21808. }
  21809. BounceEase.prototype.easeInCore = function (gradient) {
  21810. var y = Math.max(0.0, this.bounces);
  21811. var bounciness = this.bounciness;
  21812. if (bounciness <= 1.0) {
  21813. bounciness = 1.001;
  21814. }
  21815. var num9 = Math.pow(bounciness, y);
  21816. var num5 = 1.0 - bounciness;
  21817. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21818. var num15 = gradient * num4;
  21819. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21820. var num3 = Math.floor(num65);
  21821. var num13 = num3 + 1.0;
  21822. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21823. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21824. var num7 = (num8 + num12) * 0.5;
  21825. var num6 = gradient - num7;
  21826. var num2 = num7 - num8;
  21827. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21828. };
  21829. return BounceEase;
  21830. })(EasingFunction);
  21831. BABYLON.BounceEase = BounceEase;
  21832. var CubicEase = (function (_super) {
  21833. __extends(CubicEase, _super);
  21834. function CubicEase() {
  21835. _super.apply(this, arguments);
  21836. }
  21837. CubicEase.prototype.easeInCore = function (gradient) {
  21838. return (gradient * gradient * gradient);
  21839. };
  21840. return CubicEase;
  21841. })(EasingFunction);
  21842. BABYLON.CubicEase = CubicEase;
  21843. var ElasticEase = (function (_super) {
  21844. __extends(ElasticEase, _super);
  21845. function ElasticEase(oscillations, springiness) {
  21846. if (oscillations === void 0) { oscillations = 3; }
  21847. if (springiness === void 0) { springiness = 3; }
  21848. _super.call(this);
  21849. this.oscillations = oscillations;
  21850. this.springiness = springiness;
  21851. }
  21852. ElasticEase.prototype.easeInCore = function (gradient) {
  21853. var num2;
  21854. var num3 = Math.max(0.0, this.oscillations);
  21855. var num = Math.max(0.0, this.springiness);
  21856. if (num == 0) {
  21857. num2 = gradient;
  21858. }
  21859. else {
  21860. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21861. }
  21862. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21863. };
  21864. return ElasticEase;
  21865. })(EasingFunction);
  21866. BABYLON.ElasticEase = ElasticEase;
  21867. var ExponentialEase = (function (_super) {
  21868. __extends(ExponentialEase, _super);
  21869. function ExponentialEase(exponent) {
  21870. if (exponent === void 0) { exponent = 2; }
  21871. _super.call(this);
  21872. this.exponent = exponent;
  21873. }
  21874. ExponentialEase.prototype.easeInCore = function (gradient) {
  21875. if (this.exponent <= 0) {
  21876. return gradient;
  21877. }
  21878. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21879. };
  21880. return ExponentialEase;
  21881. })(EasingFunction);
  21882. BABYLON.ExponentialEase = ExponentialEase;
  21883. var PowerEase = (function (_super) {
  21884. __extends(PowerEase, _super);
  21885. function PowerEase(power) {
  21886. if (power === void 0) { power = 2; }
  21887. _super.call(this);
  21888. this.power = power;
  21889. }
  21890. PowerEase.prototype.easeInCore = function (gradient) {
  21891. var y = Math.max(0.0, this.power);
  21892. return Math.pow(gradient, y);
  21893. };
  21894. return PowerEase;
  21895. })(EasingFunction);
  21896. BABYLON.PowerEase = PowerEase;
  21897. var QuadraticEase = (function (_super) {
  21898. __extends(QuadraticEase, _super);
  21899. function QuadraticEase() {
  21900. _super.apply(this, arguments);
  21901. }
  21902. QuadraticEase.prototype.easeInCore = function (gradient) {
  21903. return (gradient * gradient);
  21904. };
  21905. return QuadraticEase;
  21906. })(EasingFunction);
  21907. BABYLON.QuadraticEase = QuadraticEase;
  21908. var QuarticEase = (function (_super) {
  21909. __extends(QuarticEase, _super);
  21910. function QuarticEase() {
  21911. _super.apply(this, arguments);
  21912. }
  21913. QuarticEase.prototype.easeInCore = function (gradient) {
  21914. return (gradient * gradient * gradient * gradient);
  21915. };
  21916. return QuarticEase;
  21917. })(EasingFunction);
  21918. BABYLON.QuarticEase = QuarticEase;
  21919. var QuinticEase = (function (_super) {
  21920. __extends(QuinticEase, _super);
  21921. function QuinticEase() {
  21922. _super.apply(this, arguments);
  21923. }
  21924. QuinticEase.prototype.easeInCore = function (gradient) {
  21925. return (gradient * gradient * gradient * gradient * gradient);
  21926. };
  21927. return QuinticEase;
  21928. })(EasingFunction);
  21929. BABYLON.QuinticEase = QuinticEase;
  21930. var SineEase = (function (_super) {
  21931. __extends(SineEase, _super);
  21932. function SineEase() {
  21933. _super.apply(this, arguments);
  21934. }
  21935. SineEase.prototype.easeInCore = function (gradient) {
  21936. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21937. };
  21938. return SineEase;
  21939. })(EasingFunction);
  21940. BABYLON.SineEase = SineEase;
  21941. var BezierCurveEase = (function (_super) {
  21942. __extends(BezierCurveEase, _super);
  21943. function BezierCurveEase(x1, y1, x2, y2) {
  21944. if (x1 === void 0) { x1 = 0; }
  21945. if (y1 === void 0) { y1 = 0; }
  21946. if (x2 === void 0) { x2 = 1; }
  21947. if (y2 === void 0) { y2 = 1; }
  21948. _super.call(this);
  21949. this.x1 = x1;
  21950. this.y1 = y1;
  21951. this.x2 = x2;
  21952. this.y2 = y2;
  21953. }
  21954. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21955. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21956. };
  21957. return BezierCurveEase;
  21958. })(EasingFunction);
  21959. BABYLON.BezierCurveEase = BezierCurveEase;
  21960. })(BABYLON || (BABYLON = {}));
  21961. var BABYLON;
  21962. (function (BABYLON) {
  21963. var Bone = (function (_super) {
  21964. __extends(Bone, _super);
  21965. function Bone(name, skeleton, parentBone, matrix) {
  21966. _super.call(this, name, skeleton.getScene());
  21967. this.name = name;
  21968. this.children = new Array();
  21969. this.animations = new Array();
  21970. this._worldTransform = new BABYLON.Matrix();
  21971. this._absoluteTransform = new BABYLON.Matrix();
  21972. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21973. this._skeleton = skeleton;
  21974. this._matrix = matrix;
  21975. this._baseMatrix = matrix;
  21976. skeleton.bones.push(this);
  21977. if (parentBone) {
  21978. this._parent = parentBone;
  21979. parentBone.children.push(this);
  21980. }
  21981. else {
  21982. this._parent = null;
  21983. }
  21984. this._updateDifferenceMatrix();
  21985. }
  21986. // Members
  21987. Bone.prototype.getParent = function () {
  21988. return this._parent;
  21989. };
  21990. Bone.prototype.getLocalMatrix = function () {
  21991. return this._matrix;
  21992. };
  21993. Bone.prototype.getBaseMatrix = function () {
  21994. return this._baseMatrix;
  21995. };
  21996. Bone.prototype.getWorldMatrix = function () {
  21997. return this._worldTransform;
  21998. };
  21999. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22000. return this._invertedAbsoluteTransform;
  22001. };
  22002. Bone.prototype.getAbsoluteMatrix = function () {
  22003. var matrix = this._matrix.clone();
  22004. var parent = this._parent;
  22005. while (parent) {
  22006. matrix = matrix.multiply(parent.getLocalMatrix());
  22007. parent = parent.getParent();
  22008. }
  22009. return matrix;
  22010. };
  22011. // Methods
  22012. Bone.prototype.updateMatrix = function (matrix) {
  22013. this._matrix = matrix;
  22014. this._skeleton._markAsDirty();
  22015. this._updateDifferenceMatrix();
  22016. };
  22017. Bone.prototype._updateDifferenceMatrix = function () {
  22018. if (this._parent) {
  22019. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22020. }
  22021. else {
  22022. this._absoluteTransform.copyFrom(this._matrix);
  22023. }
  22024. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22025. for (var index = 0; index < this.children.length; index++) {
  22026. this.children[index]._updateDifferenceMatrix();
  22027. }
  22028. };
  22029. Bone.prototype.markAsDirty = function () {
  22030. this._currentRenderId++;
  22031. this._skeleton._markAsDirty();
  22032. };
  22033. return Bone;
  22034. })(BABYLON.Node);
  22035. BABYLON.Bone = Bone;
  22036. })(BABYLON || (BABYLON = {}));
  22037. var BABYLON;
  22038. (function (BABYLON) {
  22039. var Skeleton = (function () {
  22040. function Skeleton(name, id, scene) {
  22041. this.name = name;
  22042. this.id = id;
  22043. this.bones = new Array();
  22044. this._isDirty = true;
  22045. this._identity = BABYLON.Matrix.Identity();
  22046. this._ranges = new Array();
  22047. this.bones = [];
  22048. this._scene = scene;
  22049. scene.skeletons.push(this);
  22050. this.prepare();
  22051. //make sure it will recalculate the matrix next time prepare is called.
  22052. this._isDirty = true;
  22053. }
  22054. // Members
  22055. Skeleton.prototype.getTransformMatrices = function () {
  22056. return this._transformMatrices;
  22057. };
  22058. Skeleton.prototype.getScene = function () {
  22059. return this._scene;
  22060. };
  22061. // Methods
  22062. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22063. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22064. };
  22065. Skeleton.prototype.deleteAnimationRange = function (name) {
  22066. for (var index = 0; index < this._ranges.length; index++) {
  22067. if (this._ranges[index].name === name) {
  22068. this._ranges.splice(index, 1);
  22069. return;
  22070. }
  22071. }
  22072. };
  22073. Skeleton.prototype.getAnimationRange = function (name) {
  22074. for (var index = 0; index < this._ranges.length; index++) {
  22075. if (this._ranges[index].name === name) {
  22076. return this._ranges[index];
  22077. }
  22078. }
  22079. return null;
  22080. };
  22081. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22082. var range = this.getAnimationRange(name);
  22083. if (!range) {
  22084. return null;
  22085. }
  22086. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22087. };
  22088. Skeleton.prototype._markAsDirty = function () {
  22089. this._isDirty = true;
  22090. };
  22091. Skeleton.prototype.prepare = function () {
  22092. if (!this._isDirty) {
  22093. return;
  22094. }
  22095. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22096. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22097. }
  22098. for (var index = 0; index < this.bones.length; index++) {
  22099. var bone = this.bones[index];
  22100. var parentBone = bone.getParent();
  22101. if (parentBone) {
  22102. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22103. }
  22104. else {
  22105. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22106. }
  22107. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22108. }
  22109. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22110. this._isDirty = false;
  22111. this._scene._activeBones += this.bones.length;
  22112. };
  22113. Skeleton.prototype.getAnimatables = function () {
  22114. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22115. this._animatables = [];
  22116. for (var index = 0; index < this.bones.length; index++) {
  22117. this._animatables.push(this.bones[index]);
  22118. }
  22119. }
  22120. return this._animatables;
  22121. };
  22122. Skeleton.prototype.clone = function (name, id) {
  22123. var result = new Skeleton(name, id || name, this._scene);
  22124. for (var index = 0; index < this.bones.length; index++) {
  22125. var source = this.bones[index];
  22126. var parentBone = null;
  22127. if (source.getParent()) {
  22128. var parentIndex = this.bones.indexOf(source.getParent());
  22129. parentBone = result.bones[parentIndex];
  22130. }
  22131. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22132. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22133. }
  22134. return result;
  22135. };
  22136. Skeleton.prototype.dispose = function () {
  22137. // Animations
  22138. this.getScene().stopAnimation(this);
  22139. // Remove from scene
  22140. this.getScene().removeSkeleton(this);
  22141. };
  22142. Skeleton.prototype.serialize = function () {
  22143. var serializationObject = {};
  22144. serializationObject.name = this.name;
  22145. serializationObject.id = this.id;
  22146. serializationObject.bones = [];
  22147. for (var index = 0; index < this.bones.length; index++) {
  22148. var bone = this.bones[index];
  22149. var serializedBone = {
  22150. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22151. name: bone.name,
  22152. matrix: bone.getLocalMatrix().toArray()
  22153. };
  22154. serializationObject.bones.push(serializedBone);
  22155. if (bone.animations && bone.animations.length > 0) {
  22156. serializedBone.animation = bone.animations[0].serialize();
  22157. }
  22158. }
  22159. return serializationObject;
  22160. };
  22161. Skeleton.ParseSkeleton = function (parsedSkeleton, scene) {
  22162. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22163. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22164. var parsedBone = parsedSkeleton.bones[index];
  22165. var parentBone = null;
  22166. if (parsedBone.parentBoneIndex > -1) {
  22167. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22168. }
  22169. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22170. if (parsedBone.animation) {
  22171. bone.animations.push(BABYLON.Animation.ParseAnimation(parsedBone.animation));
  22172. }
  22173. }
  22174. return skeleton;
  22175. };
  22176. return Skeleton;
  22177. })();
  22178. BABYLON.Skeleton = Skeleton;
  22179. })(BABYLON || (BABYLON = {}));
  22180. var BABYLON;
  22181. (function (BABYLON) {
  22182. var PostProcess = (function () {
  22183. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22185. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22186. this.name = name;
  22187. this.width = -1;
  22188. this.height = -1;
  22189. this._reusable = false;
  22190. this._textures = new BABYLON.SmartArray(2);
  22191. this._currentRenderTextureInd = 0;
  22192. if (camera != null) {
  22193. this._camera = camera;
  22194. this._scene = camera.getScene();
  22195. camera.attachPostProcess(this);
  22196. this._engine = this._scene.getEngine();
  22197. }
  22198. else {
  22199. this._engine = engine;
  22200. }
  22201. this._renderRatio = ratio;
  22202. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22203. this._reusable = reusable || false;
  22204. this._textureType = textureType;
  22205. this._samplers = samplers || [];
  22206. this._samplers.push("textureSampler");
  22207. this._fragmentUrl = fragmentUrl;
  22208. this._parameters = parameters || [];
  22209. this.updateEffect(defines);
  22210. }
  22211. PostProcess.prototype.updateEffect = function (defines) {
  22212. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22213. };
  22214. PostProcess.prototype.isReusable = function () {
  22215. return this._reusable;
  22216. };
  22217. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22218. camera = camera || this._camera;
  22219. var scene = camera.getScene();
  22220. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22221. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22222. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22223. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22224. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22225. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22226. if (this._textures.length > 0) {
  22227. for (var i = 0; i < this._textures.length; i++) {
  22228. this._engine._releaseTexture(this._textures.data[i]);
  22229. }
  22230. this._textures.reset();
  22231. }
  22232. this.width = desiredWidth;
  22233. this.height = desiredHeight;
  22234. 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 }));
  22235. if (this._reusable) {
  22236. 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 }));
  22237. }
  22238. if (this.onSizeChanged) {
  22239. this.onSizeChanged();
  22240. }
  22241. }
  22242. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22243. if (this.onActivate) {
  22244. this.onActivate(camera);
  22245. }
  22246. // Clear
  22247. if (this.clearColor) {
  22248. this._engine.clear(this.clearColor, true, true);
  22249. }
  22250. else {
  22251. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22252. }
  22253. if (this._reusable) {
  22254. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22255. }
  22256. };
  22257. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22258. get: function () {
  22259. return this._effect.isSupported;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. PostProcess.prototype.apply = function () {
  22265. // Check
  22266. if (!this._effect.isReady())
  22267. return null;
  22268. // States
  22269. this._engine.enableEffect(this._effect);
  22270. this._engine.setState(false);
  22271. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22272. this._engine.setDepthBuffer(false);
  22273. this._engine.setDepthWrite(false);
  22274. // Texture
  22275. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22276. // Parameters
  22277. if (this.onApply) {
  22278. this.onApply(this._effect);
  22279. }
  22280. return this._effect;
  22281. };
  22282. PostProcess.prototype.dispose = function (camera) {
  22283. camera = camera || this._camera;
  22284. if (this._textures.length > 0) {
  22285. for (var i = 0; i < this._textures.length; i++) {
  22286. this._engine._releaseTexture(this._textures.data[i]);
  22287. }
  22288. this._textures.reset();
  22289. }
  22290. if (!camera) {
  22291. return;
  22292. }
  22293. camera.detachPostProcess(this);
  22294. var index = camera._postProcesses.indexOf(this);
  22295. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22296. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22297. }
  22298. };
  22299. return PostProcess;
  22300. })();
  22301. BABYLON.PostProcess = PostProcess;
  22302. })(BABYLON || (BABYLON = {}));
  22303. var BABYLON;
  22304. (function (BABYLON) {
  22305. var PostProcessManager = (function () {
  22306. function PostProcessManager(scene) {
  22307. this._vertexDeclaration = [2];
  22308. this._vertexStrideSize = 2 * 4;
  22309. this._scene = scene;
  22310. }
  22311. PostProcessManager.prototype._prepareBuffers = function () {
  22312. if (this._vertexBuffer) {
  22313. return;
  22314. }
  22315. // VBO
  22316. var vertices = [];
  22317. vertices.push(1, 1);
  22318. vertices.push(-1, 1);
  22319. vertices.push(-1, -1);
  22320. vertices.push(1, -1);
  22321. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22322. // Indices
  22323. var indices = [];
  22324. indices.push(0);
  22325. indices.push(1);
  22326. indices.push(2);
  22327. indices.push(0);
  22328. indices.push(2);
  22329. indices.push(3);
  22330. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22331. };
  22332. // Methods
  22333. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22334. var postProcesses = this._scene.activeCamera._postProcesses;
  22335. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22336. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22337. return false;
  22338. }
  22339. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22340. return true;
  22341. };
  22342. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22343. var engine = this._scene.getEngine();
  22344. for (var index = 0; index < postProcesses.length; index++) {
  22345. if (index < postProcesses.length - 1) {
  22346. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22347. }
  22348. else {
  22349. if (targetTexture) {
  22350. engine.bindFramebuffer(targetTexture);
  22351. }
  22352. else {
  22353. engine.restoreDefaultFramebuffer();
  22354. }
  22355. }
  22356. var pp = postProcesses[index];
  22357. var effect = pp.apply();
  22358. if (effect) {
  22359. if (pp.onBeforeRender) {
  22360. pp.onBeforeRender(effect);
  22361. }
  22362. // VBOs
  22363. this._prepareBuffers();
  22364. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22365. // Draw order
  22366. engine.draw(true, 0, 6);
  22367. if (pp.onAfterRender) {
  22368. pp.onAfterRender(effect);
  22369. }
  22370. }
  22371. }
  22372. // Restore depth buffer
  22373. engine.setDepthBuffer(true);
  22374. engine.setDepthWrite(true);
  22375. };
  22376. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22377. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22378. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22379. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22380. return;
  22381. }
  22382. var engine = this._scene.getEngine();
  22383. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22384. if (index < postProcessesTakenIndices.length - 1) {
  22385. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22386. }
  22387. else {
  22388. if (targetTexture) {
  22389. engine.bindFramebuffer(targetTexture, faceIndex);
  22390. }
  22391. else {
  22392. engine.restoreDefaultFramebuffer();
  22393. }
  22394. }
  22395. if (doNotPresent) {
  22396. break;
  22397. }
  22398. var pp = postProcesses[postProcessesTakenIndices[index]];
  22399. var effect = pp.apply();
  22400. if (effect) {
  22401. if (pp.onBeforeRender) {
  22402. pp.onBeforeRender(effect);
  22403. }
  22404. // VBOs
  22405. this._prepareBuffers();
  22406. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22407. // Draw order
  22408. engine.draw(true, 0, 6);
  22409. if (pp.onAfterRender) {
  22410. pp.onAfterRender(effect);
  22411. }
  22412. }
  22413. }
  22414. // Restore depth buffer
  22415. engine.setDepthBuffer(true);
  22416. engine.setDepthWrite(true);
  22417. };
  22418. PostProcessManager.prototype.dispose = function () {
  22419. if (this._vertexBuffer) {
  22420. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22421. this._vertexBuffer = null;
  22422. }
  22423. if (this._indexBuffer) {
  22424. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22425. this._indexBuffer = null;
  22426. }
  22427. };
  22428. return PostProcessManager;
  22429. })();
  22430. BABYLON.PostProcessManager = PostProcessManager;
  22431. })(BABYLON || (BABYLON = {}));
  22432. var BABYLON;
  22433. (function (BABYLON) {
  22434. var PassPostProcess = (function (_super) {
  22435. __extends(PassPostProcess, _super);
  22436. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22437. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22438. }
  22439. return PassPostProcess;
  22440. })(BABYLON.PostProcess);
  22441. BABYLON.PassPostProcess = PassPostProcess;
  22442. })(BABYLON || (BABYLON = {}));
  22443. var BABYLON;
  22444. (function (BABYLON) {
  22445. var PhysicsEngine = (function () {
  22446. function PhysicsEngine(plugin) {
  22447. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22448. }
  22449. PhysicsEngine.prototype._initialize = function (gravity) {
  22450. this._currentPlugin.initialize();
  22451. this._setGravity(gravity);
  22452. };
  22453. PhysicsEngine.prototype._runOneStep = function (delta) {
  22454. if (delta > 0.1) {
  22455. delta = 0.1;
  22456. }
  22457. else if (delta <= 0) {
  22458. delta = 1.0 / 60.0;
  22459. }
  22460. this._currentPlugin.runOneStep(delta);
  22461. };
  22462. PhysicsEngine.prototype._setGravity = function (gravity) {
  22463. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22464. this._currentPlugin.setGravity(this.gravity);
  22465. };
  22466. PhysicsEngine.prototype._getGravity = function () {
  22467. return this._currentPlugin.getGravity();
  22468. };
  22469. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22470. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22471. };
  22472. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22473. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22474. };
  22475. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22476. this._currentPlugin.unregisterMesh(mesh);
  22477. };
  22478. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22479. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22480. };
  22481. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22482. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22483. };
  22484. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22485. this._currentPlugin.updateBodyPosition(mesh);
  22486. };
  22487. PhysicsEngine.prototype.dispose = function () {
  22488. this._currentPlugin.dispose();
  22489. };
  22490. PhysicsEngine.prototype.isSupported = function () {
  22491. return this._currentPlugin.isSupported();
  22492. };
  22493. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22494. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22495. };
  22496. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22497. return this._currentPlugin.name;
  22498. };
  22499. // Statics
  22500. PhysicsEngine.NoImpostor = 0;
  22501. PhysicsEngine.SphereImpostor = 1;
  22502. PhysicsEngine.BoxImpostor = 2;
  22503. PhysicsEngine.PlaneImpostor = 3;
  22504. PhysicsEngine.MeshImpostor = 4;
  22505. PhysicsEngine.CapsuleImpostor = 5;
  22506. PhysicsEngine.ConeImpostor = 6;
  22507. PhysicsEngine.CylinderImpostor = 7;
  22508. PhysicsEngine.ConvexHullImpostor = 8;
  22509. PhysicsEngine.HeightmapImpostor = 9;
  22510. PhysicsEngine.Epsilon = 0.001;
  22511. return PhysicsEngine;
  22512. })();
  22513. BABYLON.PhysicsEngine = PhysicsEngine;
  22514. })(BABYLON || (BABYLON = {}));
  22515. var BABYLON;
  22516. (function (BABYLON) {
  22517. var VertexData = (function () {
  22518. function VertexData() {
  22519. }
  22520. VertexData.prototype.set = function (data, kind) {
  22521. switch (kind) {
  22522. case BABYLON.VertexBuffer.PositionKind:
  22523. this.positions = data;
  22524. break;
  22525. case BABYLON.VertexBuffer.NormalKind:
  22526. this.normals = data;
  22527. break;
  22528. case BABYLON.VertexBuffer.UVKind:
  22529. this.uvs = data;
  22530. break;
  22531. case BABYLON.VertexBuffer.UV2Kind:
  22532. this.uvs2 = data;
  22533. break;
  22534. case BABYLON.VertexBuffer.UV3Kind:
  22535. this.uvs3 = data;
  22536. break;
  22537. case BABYLON.VertexBuffer.UV4Kind:
  22538. this.uvs4 = data;
  22539. break;
  22540. case BABYLON.VertexBuffer.UV5Kind:
  22541. this.uvs5 = data;
  22542. break;
  22543. case BABYLON.VertexBuffer.UV6Kind:
  22544. this.uvs6 = data;
  22545. break;
  22546. case BABYLON.VertexBuffer.ColorKind:
  22547. this.colors = data;
  22548. break;
  22549. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22550. this.matricesIndices = data;
  22551. break;
  22552. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22553. this.matricesWeights = data;
  22554. break;
  22555. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22556. this.matricesIndicesExtra = data;
  22557. break;
  22558. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22559. this.matricesWeightsExtra = data;
  22560. break;
  22561. }
  22562. };
  22563. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22564. this._applyTo(mesh, updatable);
  22565. };
  22566. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22567. this._applyTo(geometry, updatable);
  22568. };
  22569. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22570. this._update(mesh);
  22571. };
  22572. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22573. this._update(geometry);
  22574. };
  22575. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22576. if (this.positions) {
  22577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22578. }
  22579. if (this.normals) {
  22580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22581. }
  22582. if (this.uvs) {
  22583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22584. }
  22585. if (this.uvs2) {
  22586. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22587. }
  22588. if (this.uvs3) {
  22589. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22590. }
  22591. if (this.uvs4) {
  22592. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22593. }
  22594. if (this.uvs5) {
  22595. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22596. }
  22597. if (this.uvs6) {
  22598. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22599. }
  22600. if (this.colors) {
  22601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22602. }
  22603. if (this.matricesIndices) {
  22604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22605. }
  22606. if (this.matricesWeights) {
  22607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22608. }
  22609. if (this.matricesIndicesExtra) {
  22610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22611. }
  22612. if (this.matricesWeightsExtra) {
  22613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22614. }
  22615. if (this.indices) {
  22616. meshOrGeometry.setIndices(this.indices);
  22617. }
  22618. };
  22619. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22620. if (this.positions) {
  22621. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22622. }
  22623. if (this.normals) {
  22624. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22625. }
  22626. if (this.uvs) {
  22627. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22628. }
  22629. if (this.uvs2) {
  22630. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22631. }
  22632. if (this.uvs3) {
  22633. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22634. }
  22635. if (this.uvs4) {
  22636. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22637. }
  22638. if (this.uvs5) {
  22639. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22640. }
  22641. if (this.uvs6) {
  22642. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22643. }
  22644. if (this.colors) {
  22645. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22646. }
  22647. if (this.matricesIndices) {
  22648. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22649. }
  22650. if (this.matricesWeights) {
  22651. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22652. }
  22653. if (this.matricesIndicesExtra) {
  22654. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22655. }
  22656. if (this.matricesWeightsExtra) {
  22657. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22658. }
  22659. if (this.indices) {
  22660. meshOrGeometry.setIndices(this.indices);
  22661. }
  22662. };
  22663. VertexData.prototype.transform = function (matrix) {
  22664. var transformed = BABYLON.Vector3.Zero();
  22665. var index;
  22666. if (this.positions) {
  22667. var position = BABYLON.Vector3.Zero();
  22668. for (index = 0; index < this.positions.length; index += 3) {
  22669. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22670. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22671. this.positions[index] = transformed.x;
  22672. this.positions[index + 1] = transformed.y;
  22673. this.positions[index + 2] = transformed.z;
  22674. }
  22675. }
  22676. if (this.normals) {
  22677. var normal = BABYLON.Vector3.Zero();
  22678. for (index = 0; index < this.normals.length; index += 3) {
  22679. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22680. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22681. this.normals[index] = transformed.x;
  22682. this.normals[index + 1] = transformed.y;
  22683. this.normals[index + 2] = transformed.z;
  22684. }
  22685. }
  22686. };
  22687. VertexData.prototype.merge = function (other) {
  22688. var index;
  22689. if (other.indices) {
  22690. if (!this.indices) {
  22691. this.indices = [];
  22692. }
  22693. var offset = this.positions ? this.positions.length / 3 : 0;
  22694. for (index = 0; index < other.indices.length; index++) {
  22695. //TODO check type - if Int32Array!
  22696. this.indices.push(other.indices[index] + offset);
  22697. }
  22698. }
  22699. if (other.positions) {
  22700. if (!this.positions) {
  22701. this.positions = [];
  22702. }
  22703. for (index = 0; index < other.positions.length; index++) {
  22704. this.positions.push(other.positions[index]);
  22705. }
  22706. }
  22707. if (other.normals) {
  22708. if (!this.normals) {
  22709. this.normals = [];
  22710. }
  22711. for (index = 0; index < other.normals.length; index++) {
  22712. this.normals.push(other.normals[index]);
  22713. }
  22714. }
  22715. if (other.uvs) {
  22716. if (!this.uvs) {
  22717. this.uvs = [];
  22718. }
  22719. for (index = 0; index < other.uvs.length; index++) {
  22720. this.uvs.push(other.uvs[index]);
  22721. }
  22722. }
  22723. if (other.uvs2) {
  22724. if (!this.uvs2) {
  22725. this.uvs2 = [];
  22726. }
  22727. for (index = 0; index < other.uvs2.length; index++) {
  22728. this.uvs2.push(other.uvs2[index]);
  22729. }
  22730. }
  22731. if (other.uvs3) {
  22732. if (!this.uvs3) {
  22733. this.uvs3 = [];
  22734. }
  22735. for (index = 0; index < other.uvs3.length; index++) {
  22736. this.uvs3.push(other.uvs3[index]);
  22737. }
  22738. }
  22739. if (other.uvs4) {
  22740. if (!this.uvs4) {
  22741. this.uvs4 = [];
  22742. }
  22743. for (index = 0; index < other.uvs4.length; index++) {
  22744. this.uvs4.push(other.uvs4[index]);
  22745. }
  22746. }
  22747. if (other.uvs5) {
  22748. if (!this.uvs5) {
  22749. this.uvs5 = [];
  22750. }
  22751. for (index = 0; index < other.uvs5.length; index++) {
  22752. this.uvs5.push(other.uvs5[index]);
  22753. }
  22754. }
  22755. if (other.uvs6) {
  22756. if (!this.uvs6) {
  22757. this.uvs6 = [];
  22758. }
  22759. for (index = 0; index < other.uvs6.length; index++) {
  22760. this.uvs6.push(other.uvs6[index]);
  22761. }
  22762. }
  22763. if (other.matricesIndices) {
  22764. if (!this.matricesIndices) {
  22765. this.matricesIndices = [];
  22766. }
  22767. for (index = 0; index < other.matricesIndices.length; index++) {
  22768. this.matricesIndices.push(other.matricesIndices[index]);
  22769. }
  22770. }
  22771. if (other.matricesWeights) {
  22772. if (!this.matricesWeights) {
  22773. this.matricesWeights = [];
  22774. }
  22775. for (index = 0; index < other.matricesWeights.length; index++) {
  22776. this.matricesWeights.push(other.matricesWeights[index]);
  22777. }
  22778. }
  22779. if (other.matricesIndicesExtra) {
  22780. if (!this.matricesIndicesExtra) {
  22781. this.matricesIndicesExtra = [];
  22782. }
  22783. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  22784. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  22785. }
  22786. }
  22787. if (other.matricesWeightsExtra) {
  22788. if (!this.matricesWeightsExtra) {
  22789. this.matricesWeightsExtra = [];
  22790. }
  22791. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  22792. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  22793. }
  22794. }
  22795. if (other.colors) {
  22796. if (!this.colors) {
  22797. this.colors = [];
  22798. }
  22799. for (index = 0; index < other.colors.length; index++) {
  22800. this.colors.push(other.colors[index]);
  22801. }
  22802. }
  22803. };
  22804. // Statics
  22805. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22806. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22807. };
  22808. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22809. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22810. };
  22811. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22812. var result = new VertexData();
  22813. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22814. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22815. }
  22816. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22817. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22818. }
  22819. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22820. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22821. }
  22822. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22823. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22824. }
  22825. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22826. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22827. }
  22828. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22829. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22830. }
  22831. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22832. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22833. }
  22834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22835. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22836. }
  22837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22838. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22839. }
  22840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22841. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22842. }
  22843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22844. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22845. }
  22846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22847. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22848. }
  22849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22850. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22851. }
  22852. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22853. return result;
  22854. };
  22855. VertexData.CreateRibbon = function (options) {
  22856. var pathArray = options.pathArray;
  22857. var closeArray = options.closeArray || false;
  22858. var closePath = options.closePath || false;
  22859. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22860. var offset = options.offset || defaultOffset;
  22861. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22863. var positions = [];
  22864. var indices = [];
  22865. var normals = [];
  22866. var uvs = [];
  22867. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22868. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22869. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22870. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22871. var minlg; // minimal length among all paths from pathArray
  22872. var lg = []; // array of path lengths : nb of vertex per path
  22873. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22874. var p; // path iterator
  22875. var i; // point iterator
  22876. var j; // point iterator
  22877. // if single path in pathArray
  22878. if (pathArray.length < 2) {
  22879. var ar1 = [];
  22880. var ar2 = [];
  22881. for (i = 0; i < pathArray[0].length - offset; i++) {
  22882. ar1.push(pathArray[0][i]);
  22883. ar2.push(pathArray[0][i + offset]);
  22884. }
  22885. pathArray = [ar1, ar2];
  22886. }
  22887. // positions and horizontal distances (u)
  22888. var idc = 0;
  22889. var closePathCorr = (closePath) ? 1 : 0;
  22890. var path;
  22891. var l;
  22892. minlg = pathArray[0].length;
  22893. var vectlg;
  22894. var dist;
  22895. for (p = 0; p < pathArray.length; p++) {
  22896. uTotalDistance[p] = 0;
  22897. us[p] = [0];
  22898. path = pathArray[p];
  22899. l = path.length;
  22900. minlg = (minlg < l) ? minlg : l;
  22901. j = 0;
  22902. while (j < l) {
  22903. positions.push(path[j].x, path[j].y, path[j].z);
  22904. if (j > 0) {
  22905. vectlg = path[j].subtract(path[j - 1]).length();
  22906. dist = vectlg + uTotalDistance[p];
  22907. us[p].push(dist);
  22908. uTotalDistance[p] = dist;
  22909. }
  22910. j++;
  22911. }
  22912. if (closePath) {
  22913. j--;
  22914. positions.push(path[0].x, path[0].y, path[0].z);
  22915. vectlg = path[j].subtract(path[0]).length();
  22916. dist = vectlg + uTotalDistance[p];
  22917. us[p].push(dist);
  22918. uTotalDistance[p] = dist;
  22919. }
  22920. lg[p] = l + closePathCorr;
  22921. idx[p] = idc;
  22922. idc += (l + closePathCorr);
  22923. }
  22924. // vertical distances (v)
  22925. var path1;
  22926. var path2;
  22927. var vertex1;
  22928. var vertex2;
  22929. for (i = 0; i < minlg + closePathCorr; i++) {
  22930. vTotalDistance[i] = 0;
  22931. vs[i] = [0];
  22932. for (p = 0; p < pathArray.length - 1; p++) {
  22933. path1 = pathArray[p];
  22934. path2 = pathArray[p + 1];
  22935. if (i === minlg) {
  22936. vertex1 = path1[0];
  22937. vertex2 = path2[0];
  22938. }
  22939. else {
  22940. vertex1 = path1[i];
  22941. vertex2 = path2[i];
  22942. }
  22943. vectlg = vertex2.subtract(vertex1).length();
  22944. dist = vectlg + vTotalDistance[i];
  22945. vs[i].push(dist);
  22946. vTotalDistance[i] = dist;
  22947. }
  22948. if (closeArray) {
  22949. path1 = pathArray[p];
  22950. path2 = pathArray[0];
  22951. if (i === minlg) {
  22952. vertex2 = path2[0];
  22953. }
  22954. vectlg = vertex2.subtract(vertex1).length();
  22955. dist = vectlg + vTotalDistance[i];
  22956. vTotalDistance[i] = dist;
  22957. }
  22958. }
  22959. // uvs
  22960. var u;
  22961. var v;
  22962. for (p = 0; p < pathArray.length; p++) {
  22963. for (i = 0; i < minlg + closePathCorr; i++) {
  22964. u = us[p][i] / uTotalDistance[p];
  22965. v = vs[i][p] / vTotalDistance[i];
  22966. uvs.push(u, v);
  22967. }
  22968. }
  22969. // indices
  22970. p = 0; // path index
  22971. var pi = 0; // positions array index
  22972. var l1 = lg[p] - 1; // path1 length
  22973. var l2 = lg[p + 1] - 1; // path2 length
  22974. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22975. var shft = idx[1] - idx[0]; // shift
  22976. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  22977. while (pi <= min && p < path1nb) {
  22978. // 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
  22979. indices.push(pi, pi + shft, pi + 1);
  22980. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22981. pi += 1;
  22982. if (pi === min) {
  22983. p++;
  22984. if (p === lg.length - 1) {
  22985. shft = idx[0] - idx[p];
  22986. l1 = lg[p] - 1;
  22987. l2 = lg[0] - 1;
  22988. }
  22989. else {
  22990. shft = idx[p + 1] - idx[p];
  22991. l1 = lg[p] - 1;
  22992. l2 = lg[p + 1] - 1;
  22993. }
  22994. pi = idx[p];
  22995. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22996. }
  22997. }
  22998. // normals
  22999. VertexData.ComputeNormals(positions, indices, normals);
  23000. if (closePath) {
  23001. var indexFirst = 0;
  23002. var indexLast = 0;
  23003. for (p = 0; p < pathArray.length; p++) {
  23004. indexFirst = idx[p] * 3;
  23005. if (p + 1 < pathArray.length) {
  23006. indexLast = (idx[p + 1] - 1) * 3;
  23007. }
  23008. else {
  23009. indexLast = normals.length - 3;
  23010. }
  23011. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23012. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23013. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23014. normals[indexLast] = normals[indexFirst];
  23015. normals[indexLast + 1] = normals[indexFirst + 1];
  23016. normals[indexLast + 2] = normals[indexFirst + 2];
  23017. }
  23018. }
  23019. // sides
  23020. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23021. // Result
  23022. var vertexData = new VertexData();
  23023. vertexData.indices = indices;
  23024. vertexData.positions = positions;
  23025. vertexData.normals = normals;
  23026. vertexData.uvs = uvs;
  23027. if (closePath) {
  23028. vertexData._idx = idx;
  23029. }
  23030. return vertexData;
  23031. };
  23032. VertexData.CreateBox = function (options) {
  23033. var normalsSource = [
  23034. new BABYLON.Vector3(0, 0, 1),
  23035. new BABYLON.Vector3(0, 0, -1),
  23036. new BABYLON.Vector3(1, 0, 0),
  23037. new BABYLON.Vector3(-1, 0, 0),
  23038. new BABYLON.Vector3(0, 1, 0),
  23039. new BABYLON.Vector3(0, -1, 0)
  23040. ];
  23041. var indices = [];
  23042. var positions = [];
  23043. var normals = [];
  23044. var uvs = [];
  23045. var width = options.width || options.size || 1;
  23046. var height = options.height || options.size || 1;
  23047. var depth = options.depth || options.size || 1;
  23048. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23049. var faceUV = options.faceUV || new Array(6);
  23050. var faceColors = options.faceColors;
  23051. var colors = [];
  23052. // default face colors and UV if undefined
  23053. for (var f = 0; f < 6; f++) {
  23054. if (faceUV[f] === undefined) {
  23055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23056. }
  23057. if (faceColors && faceColors[f] === undefined) {
  23058. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23059. }
  23060. }
  23061. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23062. // Create each face in turn.
  23063. for (var index = 0; index < normalsSource.length; index++) {
  23064. var normal = normalsSource[index];
  23065. // Get two vectors perpendicular to the face normal and to each other.
  23066. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23067. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23068. // Six indices (two triangles) per face.
  23069. var verticesLength = positions.length / 3;
  23070. indices.push(verticesLength);
  23071. indices.push(verticesLength + 1);
  23072. indices.push(verticesLength + 2);
  23073. indices.push(verticesLength);
  23074. indices.push(verticesLength + 2);
  23075. indices.push(verticesLength + 3);
  23076. // Four vertices per face.
  23077. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23078. positions.push(vertex.x, vertex.y, vertex.z);
  23079. normals.push(normal.x, normal.y, normal.z);
  23080. uvs.push(faceUV[index].z, faceUV[index].w);
  23081. if (faceColors) {
  23082. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23083. }
  23084. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23085. positions.push(vertex.x, vertex.y, vertex.z);
  23086. normals.push(normal.x, normal.y, normal.z);
  23087. uvs.push(faceUV[index].x, faceUV[index].w);
  23088. if (faceColors) {
  23089. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23090. }
  23091. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23092. positions.push(vertex.x, vertex.y, vertex.z);
  23093. normals.push(normal.x, normal.y, normal.z);
  23094. uvs.push(faceUV[index].x, faceUV[index].y);
  23095. if (faceColors) {
  23096. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23097. }
  23098. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23099. positions.push(vertex.x, vertex.y, vertex.z);
  23100. normals.push(normal.x, normal.y, normal.z);
  23101. uvs.push(faceUV[index].z, faceUV[index].y);
  23102. if (faceColors) {
  23103. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23104. }
  23105. }
  23106. // sides
  23107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23108. // Result
  23109. var vertexData = new VertexData();
  23110. vertexData.indices = indices;
  23111. vertexData.positions = positions;
  23112. vertexData.normals = normals;
  23113. vertexData.uvs = uvs;
  23114. if (faceColors) {
  23115. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23116. vertexData.colors = totalColors;
  23117. }
  23118. return vertexData;
  23119. };
  23120. VertexData.CreateSphere = function (options) {
  23121. var segments = options.segments || 32;
  23122. var diameterX = options.diameterX || options.diameter || 1;
  23123. var diameterY = options.diameterY || options.diameter || 1;
  23124. var diameterZ = options.diameterZ || options.diameter || 1;
  23125. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23126. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23127. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23128. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23129. var totalZRotationSteps = 2 + segments;
  23130. var totalYRotationSteps = 2 * totalZRotationSteps;
  23131. var indices = [];
  23132. var positions = [];
  23133. var normals = [];
  23134. var uvs = [];
  23135. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23136. var normalizedZ = zRotationStep / totalZRotationSteps;
  23137. var angleZ = normalizedZ * Math.PI * slice;
  23138. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23139. var normalizedY = yRotationStep / totalYRotationSteps;
  23140. var angleY = normalizedY * Math.PI * 2 * arc;
  23141. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23142. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23143. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23144. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23145. var vertex = complete.multiply(radius);
  23146. var normal = complete.divide(radius).normalize();
  23147. positions.push(vertex.x, vertex.y, vertex.z);
  23148. normals.push(normal.x, normal.y, normal.z);
  23149. uvs.push(normalizedY, normalizedZ);
  23150. }
  23151. if (zRotationStep > 0) {
  23152. var verticesCount = positions.length / 3;
  23153. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23154. indices.push((firstIndex));
  23155. indices.push((firstIndex + 1));
  23156. indices.push(firstIndex + totalYRotationSteps + 1);
  23157. indices.push((firstIndex + totalYRotationSteps + 1));
  23158. indices.push((firstIndex + 1));
  23159. indices.push((firstIndex + totalYRotationSteps + 2));
  23160. }
  23161. }
  23162. }
  23163. // Sides
  23164. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23165. // Result
  23166. var vertexData = new VertexData();
  23167. vertexData.indices = indices;
  23168. vertexData.positions = positions;
  23169. vertexData.normals = normals;
  23170. vertexData.uvs = uvs;
  23171. return vertexData;
  23172. };
  23173. // Cylinder and cone
  23174. VertexData.CreateCylinder = function (options) {
  23175. var height = options.height || 2;
  23176. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23177. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23178. var tessellation = options.tessellation || 24;
  23179. var subdivisions = options.subdivisions || 1;
  23180. var hasRings = options.hasRings;
  23181. var enclose = options.enclose;
  23182. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23183. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23184. var faceUV = options.faceUV || new Array(3);
  23185. var faceColors = options.faceColors;
  23186. // default face colors and UV if undefined
  23187. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23188. var ringNb = (hasRings) ? subdivisions : 1;
  23189. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23190. var f;
  23191. for (f = 0; f < surfaceNb; f++) {
  23192. if (faceColors && faceColors[f] === undefined) {
  23193. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23194. }
  23195. }
  23196. for (f = 0; f < surfaceNb; f++) {
  23197. if (faceUV && faceUV[f] === undefined) {
  23198. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23199. }
  23200. }
  23201. var indices = [];
  23202. var positions = [];
  23203. var normals = [];
  23204. var uvs = [];
  23205. var colors = [];
  23206. var angle_step = Math.PI * 2 * arc / tessellation;
  23207. var angle;
  23208. var h;
  23209. var radius;
  23210. var tan = (diameterBottom - diameterTop) / 2 / height;
  23211. var ringVertex = BABYLON.Vector3.Zero();
  23212. var ringNormal = BABYLON.Vector3.Zero();
  23213. var ringFirstVertex = BABYLON.Vector3.Zero();
  23214. var ringFirstNormal = BABYLON.Vector3.Zero();
  23215. var quadNormal = BABYLON.Vector3.Zero();
  23216. var Y = BABYLON.Axis.Y;
  23217. // positions, normals, uvs
  23218. var i;
  23219. var j;
  23220. var r;
  23221. var ringIdx = 1;
  23222. var s = 1; // surface index
  23223. var cs = 0;
  23224. var v = 0;
  23225. for (i = 0; i <= subdivisions; i++) {
  23226. h = i / subdivisions;
  23227. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23228. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23229. for (r = 0; r < ringIdx; r++) {
  23230. if (hasRings) {
  23231. s += r;
  23232. }
  23233. if (enclose) {
  23234. s += 2 * r;
  23235. }
  23236. for (j = 0; j <= tessellation; j++) {
  23237. angle = j * angle_step;
  23238. // position
  23239. ringVertex.x = Math.cos(-angle) * radius;
  23240. ringVertex.y = -height / 2 + h * height;
  23241. ringVertex.z = Math.sin(-angle) * radius;
  23242. // normal
  23243. if (diameterTop === 0 && i === subdivisions) {
  23244. // if no top cap, reuse former normals
  23245. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23246. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23247. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23248. }
  23249. else {
  23250. ringNormal.x = ringVertex.x;
  23251. ringNormal.z = ringVertex.z;
  23252. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23253. ringNormal.normalize();
  23254. }
  23255. // keep first ring vertex values for enclose
  23256. if (j === 0) {
  23257. ringFirstVertex.copyFrom(ringVertex);
  23258. ringFirstNormal.copyFrom(ringNormal);
  23259. }
  23260. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23261. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23262. if (hasRings) {
  23263. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23264. }
  23265. else {
  23266. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23267. }
  23268. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23269. if (faceColors) {
  23270. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23271. }
  23272. }
  23273. // if enclose, add four vertices and their dedicated normals
  23274. if (arc !== 1 && enclose) {
  23275. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23276. positions.push(0, ringVertex.y, 0);
  23277. positions.push(0, ringVertex.y, 0);
  23278. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23279. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23280. quadNormal.normalize();
  23281. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23282. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23283. quadNormal.normalize();
  23284. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23285. if (hasRings) {
  23286. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23287. }
  23288. else {
  23289. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23290. }
  23291. uvs.push(faceUV[s + 1].x, v);
  23292. uvs.push(faceUV[s + 1].z, v);
  23293. if (hasRings) {
  23294. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23295. }
  23296. else {
  23297. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23298. }
  23299. uvs.push(faceUV[s + 2].x, v);
  23300. uvs.push(faceUV[s + 2].z, v);
  23301. if (faceColors) {
  23302. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23303. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23304. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23305. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23306. }
  23307. }
  23308. if (cs !== s) {
  23309. cs = s;
  23310. }
  23311. }
  23312. }
  23313. // indices
  23314. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23315. var s;
  23316. i = 0;
  23317. for (s = 0; s < subdivisions; s++) {
  23318. for (j = 0; j < tessellation; j++) {
  23319. var i0 = i * (e + 1) + j;
  23320. var i1 = (i + 1) * (e + 1) + j;
  23321. var i2 = i * (e + 1) + (j + 1);
  23322. var i3 = (i + 1) * (e + 1) + (j + 1);
  23323. indices.push(i0, i1, i2);
  23324. indices.push(i3, i2, i1);
  23325. }
  23326. if (arc !== 1 && enclose) {
  23327. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23328. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23329. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23330. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23331. }
  23332. i = (hasRings) ? (i + 2) : (i + 1);
  23333. }
  23334. // Caps
  23335. var createCylinderCap = function (isTop) {
  23336. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23337. if (radius === 0) {
  23338. return;
  23339. }
  23340. // Cap positions, normals & uvs
  23341. var angle;
  23342. var circleVector;
  23343. var i;
  23344. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23345. var c;
  23346. if (faceColors) {
  23347. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23348. }
  23349. // cap center
  23350. var vbase = positions.length / 3;
  23351. var offset = isTop ? height / 2 : -height / 2;
  23352. var center = new BABYLON.Vector3(0, offset, 0);
  23353. positions.push(center.x, center.y, center.z);
  23354. normals.push(0, isTop ? 1 : -1, 0);
  23355. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23356. if (faceColors) {
  23357. colors.push(c.r, c.g, c.b, c.a);
  23358. }
  23359. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23360. for (i = 0; i <= tessellation; i++) {
  23361. angle = Math.PI * 2 * i * arc / tessellation;
  23362. var cos = Math.cos(-angle);
  23363. var sin = Math.sin(-angle);
  23364. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23365. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23366. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23367. normals.push(0, isTop ? 1 : -1, 0);
  23368. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23369. if (faceColors) {
  23370. colors.push(c.r, c.g, c.b, c.a);
  23371. }
  23372. }
  23373. // Cap indices
  23374. for (i = 0; i < tessellation; i++) {
  23375. if (!isTop) {
  23376. indices.push(vbase);
  23377. indices.push(vbase + (i + 1));
  23378. indices.push(vbase + (i + 2));
  23379. }
  23380. else {
  23381. indices.push(vbase);
  23382. indices.push(vbase + (i + 2));
  23383. indices.push(vbase + (i + 1));
  23384. }
  23385. }
  23386. };
  23387. // add caps to geometry
  23388. createCylinderCap(false);
  23389. createCylinderCap(true);
  23390. // Sides
  23391. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23392. var vertexData = new VertexData();
  23393. vertexData.indices = indices;
  23394. vertexData.positions = positions;
  23395. vertexData.normals = normals;
  23396. vertexData.uvs = uvs;
  23397. if (faceColors) {
  23398. vertexData.colors = colors;
  23399. }
  23400. return vertexData;
  23401. };
  23402. VertexData.CreateTorus = function (options) {
  23403. var indices = [];
  23404. var positions = [];
  23405. var normals = [];
  23406. var uvs = [];
  23407. var diameter = options.diameter || 1;
  23408. var thickness = options.thickness || 0.5;
  23409. var tessellation = options.tessellation || 16;
  23410. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23411. var stride = tessellation + 1;
  23412. for (var i = 0; i <= tessellation; i++) {
  23413. var u = i / tessellation;
  23414. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23415. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23416. for (var j = 0; j <= tessellation; j++) {
  23417. var v = 1 - j / tessellation;
  23418. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23419. var dx = Math.cos(innerAngle);
  23420. var dy = Math.sin(innerAngle);
  23421. // Create a vertex.
  23422. var normal = new BABYLON.Vector3(dx, dy, 0);
  23423. var position = normal.scale(thickness / 2);
  23424. var textureCoordinate = new BABYLON.Vector2(u, v);
  23425. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23426. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23427. positions.push(position.x, position.y, position.z);
  23428. normals.push(normal.x, normal.y, normal.z);
  23429. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23430. // And create indices for two triangles.
  23431. var nextI = (i + 1) % stride;
  23432. var nextJ = (j + 1) % stride;
  23433. indices.push(i * stride + j);
  23434. indices.push(i * stride + nextJ);
  23435. indices.push(nextI * stride + j);
  23436. indices.push(i * stride + nextJ);
  23437. indices.push(nextI * stride + nextJ);
  23438. indices.push(nextI * stride + j);
  23439. }
  23440. }
  23441. // Sides
  23442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23443. // Result
  23444. var vertexData = new VertexData();
  23445. vertexData.indices = indices;
  23446. vertexData.positions = positions;
  23447. vertexData.normals = normals;
  23448. vertexData.uvs = uvs;
  23449. return vertexData;
  23450. };
  23451. VertexData.CreateLines = function (options) {
  23452. var indices = [];
  23453. var positions = [];
  23454. var points = options.points;
  23455. for (var index = 0; index < points.length; index++) {
  23456. positions.push(points[index].x, points[index].y, points[index].z);
  23457. if (index > 0) {
  23458. indices.push(index - 1);
  23459. indices.push(index);
  23460. }
  23461. }
  23462. // Result
  23463. var vertexData = new VertexData();
  23464. vertexData.indices = indices;
  23465. vertexData.positions = positions;
  23466. return vertexData;
  23467. };
  23468. VertexData.CreateDashedLines = function (options) {
  23469. var dashSize = options.dashSize || 3;
  23470. var gapSize = options.gapSize || 1;
  23471. var dashNb = options.dashNb || 200;
  23472. var points = options.points;
  23473. var positions = new Array();
  23474. var indices = new Array();
  23475. var curvect = BABYLON.Vector3.Zero();
  23476. var lg = 0;
  23477. var nb = 0;
  23478. var shft = 0;
  23479. var dashshft = 0;
  23480. var curshft = 0;
  23481. var idx = 0;
  23482. var i = 0;
  23483. for (i = 0; i < points.length - 1; i++) {
  23484. points[i + 1].subtractToRef(points[i], curvect);
  23485. lg += curvect.length();
  23486. }
  23487. shft = lg / dashNb;
  23488. dashshft = dashSize * shft / (dashSize + gapSize);
  23489. for (i = 0; i < points.length - 1; i++) {
  23490. points[i + 1].subtractToRef(points[i], curvect);
  23491. nb = Math.floor(curvect.length() / shft);
  23492. curvect.normalize();
  23493. for (var j = 0; j < nb; j++) {
  23494. curshft = shft * j;
  23495. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23496. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23497. indices.push(idx, idx + 1);
  23498. idx += 2;
  23499. }
  23500. }
  23501. // Result
  23502. var vertexData = new VertexData();
  23503. vertexData.positions = positions;
  23504. vertexData.indices = indices;
  23505. return vertexData;
  23506. };
  23507. VertexData.CreateGround = function (options) {
  23508. var indices = [];
  23509. var positions = [];
  23510. var normals = [];
  23511. var uvs = [];
  23512. var row, col;
  23513. var width = options.width || 1;
  23514. var height = options.height || 1;
  23515. var subdivisions = options.subdivisions || 1;
  23516. for (row = 0; row <= subdivisions; row++) {
  23517. for (col = 0; col <= subdivisions; col++) {
  23518. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23519. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23520. positions.push(position.x, position.y, position.z);
  23521. normals.push(normal.x, normal.y, normal.z);
  23522. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23523. }
  23524. }
  23525. for (row = 0; row < subdivisions; row++) {
  23526. for (col = 0; col < subdivisions; col++) {
  23527. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23528. indices.push(col + 1 + row * (subdivisions + 1));
  23529. indices.push(col + row * (subdivisions + 1));
  23530. indices.push(col + (row + 1) * (subdivisions + 1));
  23531. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23532. indices.push(col + row * (subdivisions + 1));
  23533. }
  23534. }
  23535. // Result
  23536. var vertexData = new VertexData();
  23537. vertexData.indices = indices;
  23538. vertexData.positions = positions;
  23539. vertexData.normals = normals;
  23540. vertexData.uvs = uvs;
  23541. return vertexData;
  23542. };
  23543. VertexData.CreateTiledGround = function (options) {
  23544. var xmin = options.xmin;
  23545. var zmin = options.zmin;
  23546. var xmax = options.xmax;
  23547. var zmax = options.zmax;
  23548. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23549. var precision = options.precision || { w: 1, h: 1 };
  23550. var indices = [];
  23551. var positions = [];
  23552. var normals = [];
  23553. var uvs = [];
  23554. var row, col, tileRow, tileCol;
  23555. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23556. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23557. precision.w = (precision.w < 1) ? 1 : precision.w;
  23558. precision.h = (precision.h < 1) ? 1 : precision.h;
  23559. var tileSize = {
  23560. 'w': (xmax - xmin) / subdivisions.w,
  23561. 'h': (zmax - zmin) / subdivisions.h
  23562. };
  23563. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23564. // Indices
  23565. var base = positions.length / 3;
  23566. var rowLength = precision.w + 1;
  23567. for (row = 0; row < precision.h; row++) {
  23568. for (col = 0; col < precision.w; col++) {
  23569. var square = [
  23570. base + col + row * rowLength,
  23571. base + (col + 1) + row * rowLength,
  23572. base + (col + 1) + (row + 1) * rowLength,
  23573. base + col + (row + 1) * rowLength
  23574. ];
  23575. indices.push(square[1]);
  23576. indices.push(square[2]);
  23577. indices.push(square[3]);
  23578. indices.push(square[0]);
  23579. indices.push(square[1]);
  23580. indices.push(square[3]);
  23581. }
  23582. }
  23583. // Position, normals and uvs
  23584. var position = BABYLON.Vector3.Zero();
  23585. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23586. for (row = 0; row <= precision.h; row++) {
  23587. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23588. for (col = 0; col <= precision.w; col++) {
  23589. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23590. position.y = 0;
  23591. positions.push(position.x, position.y, position.z);
  23592. normals.push(normal.x, normal.y, normal.z);
  23593. uvs.push(col / precision.w, row / precision.h);
  23594. }
  23595. }
  23596. }
  23597. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23598. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23599. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23600. }
  23601. }
  23602. // Result
  23603. var vertexData = new VertexData();
  23604. vertexData.indices = indices;
  23605. vertexData.positions = positions;
  23606. vertexData.normals = normals;
  23607. vertexData.uvs = uvs;
  23608. return vertexData;
  23609. };
  23610. VertexData.CreateGroundFromHeightMap = function (options) {
  23611. var indices = [];
  23612. var positions = [];
  23613. var normals = [];
  23614. var uvs = [];
  23615. var row, col;
  23616. // Vertices
  23617. for (row = 0; row <= options.subdivisions; row++) {
  23618. for (col = 0; col <= options.subdivisions; col++) {
  23619. 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));
  23620. // Compute height
  23621. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23622. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23623. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23624. var r = options.buffer[pos] / 255.0;
  23625. var g = options.buffer[pos + 1] / 255.0;
  23626. var b = options.buffer[pos + 2] / 255.0;
  23627. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23628. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23629. // Add vertex
  23630. positions.push(position.x, position.y, position.z);
  23631. normals.push(0, 0, 0);
  23632. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23633. }
  23634. }
  23635. // Indices
  23636. for (row = 0; row < options.subdivisions; row++) {
  23637. for (col = 0; col < options.subdivisions; col++) {
  23638. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23639. indices.push(col + 1 + row * (options.subdivisions + 1));
  23640. indices.push(col + row * (options.subdivisions + 1));
  23641. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23642. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23643. indices.push(col + row * (options.subdivisions + 1));
  23644. }
  23645. }
  23646. // Normals
  23647. VertexData.ComputeNormals(positions, indices, normals);
  23648. // Result
  23649. var vertexData = new VertexData();
  23650. vertexData.indices = indices;
  23651. vertexData.positions = positions;
  23652. vertexData.normals = normals;
  23653. vertexData.uvs = uvs;
  23654. return vertexData;
  23655. };
  23656. VertexData.CreatePlane = function (options) {
  23657. var indices = [];
  23658. var positions = [];
  23659. var normals = [];
  23660. var uvs = [];
  23661. var width = options.width || options.size || 1;
  23662. var height = options.height || options.size || 1;
  23663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23664. // Vertices
  23665. var halfWidth = width / 2.0;
  23666. var halfHeight = height / 2.0;
  23667. positions.push(-halfWidth, -halfHeight, 0);
  23668. normals.push(0, 0, -1.0);
  23669. uvs.push(0.0, 0.0);
  23670. positions.push(halfWidth, -halfHeight, 0);
  23671. normals.push(0, 0, -1.0);
  23672. uvs.push(1.0, 0.0);
  23673. positions.push(halfWidth, halfHeight, 0);
  23674. normals.push(0, 0, -1.0);
  23675. uvs.push(1.0, 1.0);
  23676. positions.push(-halfWidth, halfHeight, 0);
  23677. normals.push(0, 0, -1.0);
  23678. uvs.push(0.0, 1.0);
  23679. // Indices
  23680. indices.push(0);
  23681. indices.push(1);
  23682. indices.push(2);
  23683. indices.push(0);
  23684. indices.push(2);
  23685. indices.push(3);
  23686. // Sides
  23687. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23688. // Result
  23689. var vertexData = new VertexData();
  23690. vertexData.indices = indices;
  23691. vertexData.positions = positions;
  23692. vertexData.normals = normals;
  23693. vertexData.uvs = uvs;
  23694. return vertexData;
  23695. };
  23696. VertexData.CreateDisc = function (options) {
  23697. var positions = [];
  23698. var indices = [];
  23699. var normals = [];
  23700. var uvs = [];
  23701. var radius = options.radius || 0.5;
  23702. var tessellation = options.tessellation || 64;
  23703. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23705. // positions and uvs
  23706. positions.push(0, 0, 0); // disc center first
  23707. uvs.push(0.5, 0.5);
  23708. var theta = Math.PI * 2 * arc;
  23709. var step = theta / tessellation;
  23710. for (var a = 0; a < theta; a += step) {
  23711. var x = Math.cos(a);
  23712. var y = Math.sin(a);
  23713. var u = (x + 1) / 2;
  23714. var v = (1 - y) / 2;
  23715. positions.push(radius * x, radius * y, 0);
  23716. uvs.push(u, v);
  23717. }
  23718. if (arc === 1) {
  23719. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23720. uvs.push(uvs[2], uvs[3]);
  23721. }
  23722. //indices
  23723. var vertexNb = positions.length / 3;
  23724. for (var i = 1; i < vertexNb - 1; i++) {
  23725. indices.push(i + 1, 0, i);
  23726. }
  23727. // result
  23728. VertexData.ComputeNormals(positions, indices, normals);
  23729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23730. var vertexData = new VertexData();
  23731. vertexData.indices = indices;
  23732. vertexData.positions = positions;
  23733. vertexData.normals = normals;
  23734. vertexData.uvs = uvs;
  23735. return vertexData;
  23736. };
  23737. VertexData.CreateIcoSphere = function (options) {
  23738. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23739. var radius = options.radius || 1;
  23740. var flat = (options.flat === undefined) ? true : options.flat;
  23741. var subdivisions = options.subdivisions || 4;
  23742. var radiusX = options.radiusX || radius;
  23743. var radiusY = options.radiusY || radius;
  23744. var radiusZ = options.radiusZ || radius;
  23745. var t = (1 + Math.sqrt(5)) / 2;
  23746. // 12 vertex x,y,z
  23747. var ico_vertices = [
  23748. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23749. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23750. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23751. ];
  23752. // index of 3 vertex makes a face of icopshere
  23753. var ico_indices = [
  23754. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23755. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23756. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23757. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23758. ];
  23759. // vertex for uv have aliased position, not for UV
  23760. var vertices_unalias_id = [
  23761. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23762. // vertex alias
  23763. 0,
  23764. 2,
  23765. 3,
  23766. 3,
  23767. 3,
  23768. 4,
  23769. 7,
  23770. 8,
  23771. 9,
  23772. 9,
  23773. 10,
  23774. 11 // 23: B + 12
  23775. ];
  23776. // uv as integer step (not pixels !)
  23777. var ico_vertexuv = [
  23778. 5, 1, 3, 1, 6, 4, 0, 0,
  23779. 5, 3, 4, 2, 2, 2, 4, 0,
  23780. 2, 0, 1, 1, 6, 0, 6, 2,
  23781. // vertex alias (for same vertex on different faces)
  23782. 0, 4,
  23783. 3, 3,
  23784. 4, 4,
  23785. 3, 1,
  23786. 4, 2,
  23787. 4, 4,
  23788. 0, 2,
  23789. 1, 1,
  23790. 2, 2,
  23791. 3, 3,
  23792. 1, 3,
  23793. 2, 4 // 23: B + 12
  23794. ];
  23795. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23796. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23797. // First island of uv mapping
  23798. // v = 4h 3+ 2
  23799. // v = 3h 9+ 4
  23800. // v = 2h 9+ 5 B
  23801. // v = 1h 9 1 0
  23802. // v = 0h 3 8 7 A
  23803. // u = 0 1 2 3 4 5 6 *a
  23804. // Second island of uv mapping
  23805. // v = 4h 0+ B+ 4+
  23806. // v = 3h A+ 2+
  23807. // v = 2h 7+ 6 3+
  23808. // v = 1h 8+ 3+
  23809. // v = 0h
  23810. // u = 0 1 2 3 4 5 6 *a
  23811. // Face layout on texture UV mapping
  23812. // ============
  23813. // \ 4 /\ 16 / ======
  23814. // \ / \ / /\ 11 /
  23815. // \/ 7 \/ / \ /
  23816. // ======= / 10 \/
  23817. // /\ 17 /\ =======
  23818. // / \ / \ \ 15 /\
  23819. // / 8 \/ 12 \ \ / \
  23820. // ============ \/ 6 \
  23821. // \ 18 /\ ============
  23822. // \ / \ \ 5 /\ 0 /
  23823. // \/ 13 \ \ / \ /
  23824. // ======= \/ 1 \/
  23825. // =============
  23826. // /\ 19 /\ 2 /\
  23827. // / \ / \ / \
  23828. // / 14 \/ 9 \/ 3 \
  23829. // ===================
  23830. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23831. var ustep = 138 / 1024;
  23832. var vstep = 239 / 1024;
  23833. var uoffset = 60 / 1024;
  23834. var voffset = 26 / 1024;
  23835. // Second island should have margin, not to touch the first island
  23836. // avoid any borderline artefact in pixel rounding
  23837. var island_u_offset = -40 / 1024;
  23838. var island_v_offset = +20 / 1024;
  23839. // face is either island 0 or 1 :
  23840. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23841. var island = [
  23842. 0, 0, 0, 0, 1,
  23843. 0, 0, 1, 1, 0,
  23844. 0, 0, 1, 1, 0,
  23845. 0, 1, 1, 1, 0 // 15 - 19
  23846. ];
  23847. var indices = [];
  23848. var positions = [];
  23849. var normals = [];
  23850. var uvs = [];
  23851. var current_indice = 0;
  23852. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23853. var face_vertex_pos = new Array(3);
  23854. var face_vertex_uv = new Array(3);
  23855. var v012;
  23856. for (v012 = 0; v012 < 3; v012++) {
  23857. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23858. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23859. }
  23860. // create all with normals
  23861. for (var face = 0; face < 20; face++) {
  23862. // 3 vertex per face
  23863. for (v012 = 0; v012 < 3; v012++) {
  23864. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23865. var v_id = ico_indices[3 * face + v012];
  23866. // vertex have 3D position (x,y,z)
  23867. 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]);
  23868. // Normalize to get normal, then scale to radius
  23869. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23870. // uv Coordinates from vertex ID
  23871. 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);
  23872. }
  23873. // Subdivide the face (interpolate pos, norm, uv)
  23874. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23875. // - norm is linear interpolation of vertex corner normal
  23876. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23877. // - uv is linear interpolation
  23878. //
  23879. // Topology is as below for sub-divide by 2
  23880. // vertex shown as v0,v1,v2
  23881. // interp index is i1 to progress in range [v0,v1[
  23882. // interp index is i2 to progress in range [v0,v2[
  23883. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23884. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23885. //
  23886. //
  23887. // i2 v2
  23888. // ^ ^
  23889. // / / \
  23890. // / / \
  23891. // / / \
  23892. // / / (0,1) \
  23893. // / #---------\
  23894. // / / \ (0,0)'/ \
  23895. // / / \ / \
  23896. // / / \ / \
  23897. // / / (0,0) \ / (1,0) \
  23898. // / #---------#---------\
  23899. // v0 v1
  23900. //
  23901. // --------------------> i1
  23902. //
  23903. // interp of (i1,i2):
  23904. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23905. // along i1 : lerp(x0,x1, i1/(S-i2))
  23906. //
  23907. // centroid of triangle is needed to get help normal computation
  23908. // (c1,c2) are used for centroid location
  23909. var interp_vertex = function (i1, i2, c1, c2) {
  23910. // vertex is interpolated from
  23911. // - face_vertex_pos[0..2]
  23912. // - face_vertex_uv[0..2]
  23913. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  23914. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  23915. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  23916. pos_interp.normalize();
  23917. var vertex_normal;
  23918. if (flat) {
  23919. // in flat mode, recalculate normal as face centroid normal
  23920. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  23921. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  23922. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  23923. }
  23924. else {
  23925. // in smooth mode, recalculate normal from each single vertex position
  23926. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  23927. }
  23928. // Vertex normal need correction due to X,Y,Z radius scaling
  23929. vertex_normal.x /= radiusX;
  23930. vertex_normal.y /= radiusY;
  23931. vertex_normal.z /= radiusZ;
  23932. vertex_normal.normalize();
  23933. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  23934. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  23935. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  23936. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  23937. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  23938. uvs.push(uv_interp.x, uv_interp.y);
  23939. // push each vertex has member of a face
  23940. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  23941. indices.push(current_indice);
  23942. current_indice++;
  23943. };
  23944. for (var i2 = 0; i2 < subdivisions; i2++) {
  23945. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  23946. // face : (i1,i2) for /\ :
  23947. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  23948. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23949. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23950. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  23951. if (i1 + i2 + 1 < subdivisions) {
  23952. // face : (i1,i2)' for \/ :
  23953. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23954. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23955. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23956. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  23957. }
  23958. }
  23959. }
  23960. }
  23961. // Sides
  23962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23963. // Result
  23964. var vertexData = new VertexData();
  23965. vertexData.indices = indices;
  23966. vertexData.positions = positions;
  23967. vertexData.normals = normals;
  23968. vertexData.uvs = uvs;
  23969. return vertexData;
  23970. };
  23971. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23972. VertexData.CreatePolyhedron = function (options) {
  23973. // provided polyhedron types :
  23974. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23975. // 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)
  23976. var polyhedra = [];
  23977. 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]] };
  23978. 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]] };
  23979. polyhedra[2] = {
  23980. 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]],
  23981. 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]]
  23982. };
  23983. polyhedra[3] = {
  23984. 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]],
  23985. 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]]
  23986. };
  23987. polyhedra[4] = {
  23988. 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]],
  23989. 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]]
  23990. };
  23991. 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]] };
  23992. 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]] };
  23993. 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]] };
  23994. 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]] };
  23995. 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]] };
  23996. 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]] };
  23997. 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]] };
  23998. 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]] };
  23999. 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]] };
  24000. polyhedra[14] = {
  24001. 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]],
  24002. 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]]
  24003. };
  24004. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24005. var size = options.size;
  24006. var sizeX = options.sizeX || size || 1;
  24007. var sizeY = options.sizeY || size || 1;
  24008. var sizeZ = options.sizeZ || size || 1;
  24009. var data = options.custom || polyhedra[type];
  24010. var nbfaces = data.face.length;
  24011. var faceUV = options.faceUV || new Array(nbfaces);
  24012. var faceColors = options.faceColors;
  24013. var flat = (options.flat === undefined) ? true : options.flat;
  24014. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24015. var positions = [];
  24016. var indices = [];
  24017. var normals = [];
  24018. var uvs = [];
  24019. var colors = [];
  24020. var index = 0;
  24021. var faceIdx = 0; // face cursor in the array "indexes"
  24022. var indexes = [];
  24023. var i = 0;
  24024. var f = 0;
  24025. var u, v, ang, x, y, tmp;
  24026. // default face colors and UV if undefined
  24027. if (flat) {
  24028. for (f = 0; f < nbfaces; f++) {
  24029. if (faceColors && faceColors[f] === undefined) {
  24030. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24031. }
  24032. if (faceUV && faceUV[f] === undefined) {
  24033. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24034. }
  24035. }
  24036. }
  24037. if (!flat) {
  24038. for (i = 0; i < data.vertex.length; i++) {
  24039. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24040. uvs.push(0, 0);
  24041. }
  24042. for (f = 0; f < nbfaces; f++) {
  24043. for (i = 0; i < data.face[f].length - 2; i++) {
  24044. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24045. }
  24046. }
  24047. }
  24048. else {
  24049. for (f = 0; f < nbfaces; f++) {
  24050. var fl = data.face[f].length; // number of vertices of the current face
  24051. ang = 2 * Math.PI / fl;
  24052. x = 0.5 * Math.tan(ang / 2);
  24053. y = 0.5;
  24054. // positions, uvs, colors
  24055. for (i = 0; i < fl; i++) {
  24056. // positions
  24057. 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);
  24058. indexes.push(index);
  24059. index++;
  24060. // uvs
  24061. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24062. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24063. uvs.push(u, v);
  24064. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24065. y = x * Math.sin(ang) + y * Math.cos(ang);
  24066. x = tmp;
  24067. // colors
  24068. if (faceColors) {
  24069. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24070. }
  24071. }
  24072. // indices from indexes
  24073. for (i = 0; i < fl - 2; i++) {
  24074. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24075. }
  24076. faceIdx += fl;
  24077. }
  24078. }
  24079. VertexData.ComputeNormals(positions, indices, normals);
  24080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24081. var vertexData = new VertexData();
  24082. vertexData.positions = positions;
  24083. vertexData.indices = indices;
  24084. vertexData.normals = normals;
  24085. vertexData.uvs = uvs;
  24086. if (faceColors && flat) {
  24087. vertexData.colors = colors;
  24088. }
  24089. return vertexData;
  24090. };
  24091. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24092. VertexData.CreateTorusKnot = function (options) {
  24093. var indices = [];
  24094. var positions = [];
  24095. var normals = [];
  24096. var uvs = [];
  24097. var radius = options.radius || 2;
  24098. var tube = options.tube || 0.5;
  24099. var radialSegments = options.radialSegments || 32;
  24100. var tubularSegments = options.tubularSegments || 32;
  24101. var p = options.p || 2;
  24102. var q = options.q || 3;
  24103. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24104. // Helper
  24105. var getPos = function (angle) {
  24106. var cu = Math.cos(angle);
  24107. var su = Math.sin(angle);
  24108. var quOverP = q / p * angle;
  24109. var cs = Math.cos(quOverP);
  24110. var tx = radius * (2 + cs) * 0.5 * cu;
  24111. var ty = radius * (2 + cs) * su * 0.5;
  24112. var tz = radius * Math.sin(quOverP) * 0.5;
  24113. return new BABYLON.Vector3(tx, ty, tz);
  24114. };
  24115. // Vertices
  24116. var i;
  24117. var j;
  24118. for (i = 0; i <= radialSegments; i++) {
  24119. var modI = i % radialSegments;
  24120. var u = modI / radialSegments * 2 * p * Math.PI;
  24121. var p1 = getPos(u);
  24122. var p2 = getPos(u + 0.01);
  24123. var tang = p2.subtract(p1);
  24124. var n = p2.add(p1);
  24125. var bitan = BABYLON.Vector3.Cross(tang, n);
  24126. n = BABYLON.Vector3.Cross(bitan, tang);
  24127. bitan.normalize();
  24128. n.normalize();
  24129. for (j = 0; j < tubularSegments; j++) {
  24130. var modJ = j % tubularSegments;
  24131. var v = modJ / tubularSegments * 2 * Math.PI;
  24132. var cx = -tube * Math.cos(v);
  24133. var cy = tube * Math.sin(v);
  24134. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24135. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24136. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24137. uvs.push(i / radialSegments);
  24138. uvs.push(j / tubularSegments);
  24139. }
  24140. }
  24141. for (i = 0; i < radialSegments; i++) {
  24142. for (j = 0; j < tubularSegments; j++) {
  24143. var jNext = (j + 1) % tubularSegments;
  24144. var a = i * tubularSegments + j;
  24145. var b = (i + 1) * tubularSegments + j;
  24146. var c = (i + 1) * tubularSegments + jNext;
  24147. var d = i * tubularSegments + jNext;
  24148. indices.push(d);
  24149. indices.push(b);
  24150. indices.push(a);
  24151. indices.push(d);
  24152. indices.push(c);
  24153. indices.push(b);
  24154. }
  24155. }
  24156. // Normals
  24157. VertexData.ComputeNormals(positions, indices, normals);
  24158. // Sides
  24159. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24160. // Result
  24161. var vertexData = new VertexData();
  24162. vertexData.indices = indices;
  24163. vertexData.positions = positions;
  24164. vertexData.normals = normals;
  24165. vertexData.uvs = uvs;
  24166. return vertexData;
  24167. };
  24168. // Tools
  24169. /**
  24170. * @param {any} - positions (number[] or Float32Array)
  24171. * @param {any} - indices (number[] or Uint16Array)
  24172. * @param {any} - normals (number[] or Float32Array)
  24173. */
  24174. VertexData.ComputeNormals = function (positions, indices, normals) {
  24175. var index = 0;
  24176. var p1p2x = 0.0;
  24177. var p1p2y = 0.0;
  24178. var p1p2z = 0.0;
  24179. var p3p2x = 0.0;
  24180. var p3p2y = 0.0;
  24181. var p3p2z = 0.0;
  24182. var faceNormalx = 0.0;
  24183. var faceNormaly = 0.0;
  24184. var faceNormalz = 0.0;
  24185. var length = 0.0;
  24186. var i1 = 0;
  24187. var i2 = 0;
  24188. var i3 = 0;
  24189. for (index = 0; index < positions.length; index++) {
  24190. normals[index] = 0.0;
  24191. }
  24192. // indice triplet = 1 face
  24193. var nbFaces = indices.length / 3;
  24194. for (index = 0; index < nbFaces; index++) {
  24195. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24196. i2 = indices[index * 3 + 1];
  24197. i3 = indices[index * 3 + 2];
  24198. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24199. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24200. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24201. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24202. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24203. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24204. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24205. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24206. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24207. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24208. length = (length === 0) ? 1.0 : length;
  24209. faceNormalx /= length; // normalize this normal
  24210. faceNormaly /= length;
  24211. faceNormalz /= length;
  24212. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24213. normals[i1 * 3 + 1] += faceNormaly;
  24214. normals[i1 * 3 + 2] += faceNormalz;
  24215. normals[i2 * 3] += faceNormalx;
  24216. normals[i2 * 3 + 1] += faceNormaly;
  24217. normals[i2 * 3 + 2] += faceNormalz;
  24218. normals[i3 * 3] += faceNormalx;
  24219. normals[i3 * 3 + 1] += faceNormaly;
  24220. normals[i3 * 3 + 2] += faceNormalz;
  24221. }
  24222. // last normalization of each normal
  24223. for (index = 0; index < normals.length / 3; index++) {
  24224. faceNormalx = normals[index * 3];
  24225. faceNormaly = normals[index * 3 + 1];
  24226. faceNormalz = normals[index * 3 + 2];
  24227. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24228. length = (length === 0) ? 1.0 : length;
  24229. faceNormalx /= length;
  24230. faceNormaly /= length;
  24231. faceNormalz /= length;
  24232. normals[index * 3] = faceNormalx;
  24233. normals[index * 3 + 1] = faceNormaly;
  24234. normals[index * 3 + 2] = faceNormalz;
  24235. }
  24236. };
  24237. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24238. var li = indices.length;
  24239. var ln = normals.length;
  24240. var i;
  24241. var n;
  24242. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24243. switch (sideOrientation) {
  24244. case BABYLON.Mesh.FRONTSIDE:
  24245. // nothing changed
  24246. break;
  24247. case BABYLON.Mesh.BACKSIDE:
  24248. var tmp;
  24249. // indices
  24250. for (i = 0; i < li; i += 3) {
  24251. tmp = indices[i];
  24252. indices[i] = indices[i + 2];
  24253. indices[i + 2] = tmp;
  24254. }
  24255. // normals
  24256. for (n = 0; n < ln; n++) {
  24257. normals[n] = -normals[n];
  24258. }
  24259. break;
  24260. case BABYLON.Mesh.DOUBLESIDE:
  24261. // positions
  24262. var lp = positions.length;
  24263. var l = lp / 3;
  24264. for (var p = 0; p < lp; p++) {
  24265. positions[lp + p] = positions[p];
  24266. }
  24267. // indices
  24268. for (i = 0; i < li; i += 3) {
  24269. indices[i + li] = indices[i + 2] + l;
  24270. indices[i + 1 + li] = indices[i + 1] + l;
  24271. indices[i + 2 + li] = indices[i] + l;
  24272. }
  24273. // normals
  24274. for (n = 0; n < ln; n++) {
  24275. normals[ln + n] = -normals[n];
  24276. }
  24277. // uvs
  24278. var lu = uvs.length;
  24279. for (var u = 0; u < lu; u++) {
  24280. uvs[u + lu] = uvs[u];
  24281. }
  24282. break;
  24283. }
  24284. };
  24285. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24286. var vertexData = new VertexData();
  24287. // positions
  24288. var positions = parsedVertexData.positions;
  24289. if (positions) {
  24290. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24291. }
  24292. // normals
  24293. var normals = parsedVertexData.normals;
  24294. if (normals) {
  24295. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24296. }
  24297. // uvs
  24298. var uvs = parsedVertexData.uvs;
  24299. if (uvs) {
  24300. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24301. }
  24302. // uv2s
  24303. var uv2s = parsedVertexData.uv2s;
  24304. if (uv2s) {
  24305. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24306. }
  24307. // uv3s
  24308. var uv3s = parsedVertexData.uv3s;
  24309. if (uv3s) {
  24310. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24311. }
  24312. // uv4s
  24313. var uv4s = parsedVertexData.uv4s;
  24314. if (uv4s) {
  24315. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24316. }
  24317. // uv5s
  24318. var uv5s = parsedVertexData.uv5s;
  24319. if (uv5s) {
  24320. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24321. }
  24322. // uv6s
  24323. var uv6s = parsedVertexData.uv6s;
  24324. if (uv6s) {
  24325. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24326. }
  24327. // colors
  24328. var colors = parsedVertexData.colors;
  24329. if (colors) {
  24330. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24331. }
  24332. // matricesIndices
  24333. var matricesIndices = parsedVertexData.matricesIndices;
  24334. if (matricesIndices) {
  24335. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24336. }
  24337. // matricesWeights
  24338. var matricesWeights = parsedVertexData.matricesWeights;
  24339. if (matricesWeights) {
  24340. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24341. }
  24342. // indices
  24343. var indices = parsedVertexData.indices;
  24344. if (indices) {
  24345. vertexData.indices = indices;
  24346. }
  24347. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24348. };
  24349. return VertexData;
  24350. })();
  24351. BABYLON.VertexData = VertexData;
  24352. })(BABYLON || (BABYLON = {}));
  24353. var BABYLON;
  24354. (function (BABYLON) {
  24355. var Tags = (function () {
  24356. function Tags() {
  24357. }
  24358. Tags.EnableFor = function (obj) {
  24359. obj._tags = obj._tags || {};
  24360. obj.hasTags = function () {
  24361. return Tags.HasTags(obj);
  24362. };
  24363. obj.addTags = function (tagsString) {
  24364. return Tags.AddTagsTo(obj, tagsString);
  24365. };
  24366. obj.removeTags = function (tagsString) {
  24367. return Tags.RemoveTagsFrom(obj, tagsString);
  24368. };
  24369. obj.matchesTagsQuery = function (tagsQuery) {
  24370. return Tags.MatchesQuery(obj, tagsQuery);
  24371. };
  24372. };
  24373. Tags.DisableFor = function (obj) {
  24374. delete obj._tags;
  24375. delete obj.hasTags;
  24376. delete obj.addTags;
  24377. delete obj.removeTags;
  24378. delete obj.matchesTagsQuery;
  24379. };
  24380. Tags.HasTags = function (obj) {
  24381. if (!obj._tags) {
  24382. return false;
  24383. }
  24384. return !BABYLON.Tools.IsEmpty(obj._tags);
  24385. };
  24386. Tags.GetTags = function (obj) {
  24387. if (!obj._tags) {
  24388. return null;
  24389. }
  24390. return obj._tags;
  24391. };
  24392. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24393. // a tag cannot start with '||', '&&', and '!'
  24394. // it cannot contain whitespaces
  24395. Tags.AddTagsTo = function (obj, tagsString) {
  24396. if (!tagsString) {
  24397. return;
  24398. }
  24399. if (typeof tagsString !== "string") {
  24400. return;
  24401. }
  24402. var tags = tagsString.split(" ");
  24403. for (var t in tags) {
  24404. Tags._AddTagTo(obj, tags[t]);
  24405. }
  24406. };
  24407. Tags._AddTagTo = function (obj, tag) {
  24408. tag = tag.trim();
  24409. if (tag === "" || tag === "true" || tag === "false") {
  24410. return;
  24411. }
  24412. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24413. return;
  24414. }
  24415. Tags.EnableFor(obj);
  24416. obj._tags[tag] = true;
  24417. };
  24418. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24419. if (!Tags.HasTags(obj)) {
  24420. return;
  24421. }
  24422. var tags = tagsString.split(" ");
  24423. for (var t in tags) {
  24424. Tags._RemoveTagFrom(obj, tags[t]);
  24425. }
  24426. };
  24427. Tags._RemoveTagFrom = function (obj, tag) {
  24428. delete obj._tags[tag];
  24429. };
  24430. Tags.MatchesQuery = function (obj, tagsQuery) {
  24431. if (tagsQuery === undefined) {
  24432. return true;
  24433. }
  24434. if (tagsQuery === "") {
  24435. return Tags.HasTags(obj);
  24436. }
  24437. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24438. };
  24439. return Tags;
  24440. })();
  24441. BABYLON.Tags = Tags;
  24442. })(BABYLON || (BABYLON = {}));
  24443. var BABYLON;
  24444. (function (BABYLON) {
  24445. var Internals;
  24446. (function (Internals) {
  24447. var AndOrNotEvaluator = (function () {
  24448. function AndOrNotEvaluator() {
  24449. }
  24450. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24451. if (!query.match(/\([^\(\)]*\)/g)) {
  24452. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24453. }
  24454. else {
  24455. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24456. // remove parenthesis
  24457. r = r.slice(1, r.length - 1);
  24458. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24459. });
  24460. }
  24461. if (query === "true") {
  24462. return true;
  24463. }
  24464. if (query === "false") {
  24465. return false;
  24466. }
  24467. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24468. };
  24469. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24470. evaluateCallback = evaluateCallback || (function (r) {
  24471. return r === "true" ? true : false;
  24472. });
  24473. var result;
  24474. var or = parenthesisContent.split("||");
  24475. for (var i in or) {
  24476. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24477. var and = ori.split("&&");
  24478. if (and.length > 1) {
  24479. for (var j = 0; j < and.length; ++j) {
  24480. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24481. if (andj !== "true" && andj !== "false") {
  24482. if (andj[0] === "!") {
  24483. result = !evaluateCallback(andj.substring(1));
  24484. }
  24485. else {
  24486. result = evaluateCallback(andj);
  24487. }
  24488. }
  24489. else {
  24490. result = andj === "true" ? true : false;
  24491. }
  24492. if (!result) {
  24493. ori = "false";
  24494. break;
  24495. }
  24496. }
  24497. }
  24498. if (result || ori === "true") {
  24499. result = true;
  24500. break;
  24501. }
  24502. // result equals false (or undefined)
  24503. if (ori !== "true" && ori !== "false") {
  24504. if (ori[0] === "!") {
  24505. result = !evaluateCallback(ori.substring(1));
  24506. }
  24507. else {
  24508. result = evaluateCallback(ori);
  24509. }
  24510. }
  24511. else {
  24512. result = ori === "true" ? true : false;
  24513. }
  24514. }
  24515. // the whole parenthesis scope is replaced by 'true' or 'false'
  24516. return result ? "true" : "false";
  24517. };
  24518. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24519. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24520. // remove whitespaces
  24521. r = r.replace(/[\s]/g, function () { return ""; });
  24522. return r.length % 2 ? "!" : "";
  24523. });
  24524. booleanString = booleanString.trim();
  24525. if (booleanString === "!true") {
  24526. booleanString = "false";
  24527. }
  24528. else if (booleanString === "!false") {
  24529. booleanString = "true";
  24530. }
  24531. return booleanString;
  24532. };
  24533. return AndOrNotEvaluator;
  24534. })();
  24535. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24536. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24537. })(BABYLON || (BABYLON = {}));
  24538. var BABYLON;
  24539. (function (BABYLON) {
  24540. var PostProcessRenderPass = (function () {
  24541. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24542. this._enabled = true;
  24543. this._refCount = 0;
  24544. this._name = name;
  24545. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24546. this.setRenderList(renderList);
  24547. this._renderTexture.onBeforeRender = beforeRender;
  24548. this._renderTexture.onAfterRender = afterRender;
  24549. this._scene = scene;
  24550. this._renderList = renderList;
  24551. }
  24552. // private
  24553. PostProcessRenderPass.prototype._incRefCount = function () {
  24554. if (this._refCount === 0) {
  24555. this._scene.customRenderTargets.push(this._renderTexture);
  24556. }
  24557. return ++this._refCount;
  24558. };
  24559. PostProcessRenderPass.prototype._decRefCount = function () {
  24560. this._refCount--;
  24561. if (this._refCount <= 0) {
  24562. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24563. }
  24564. return this._refCount;
  24565. };
  24566. PostProcessRenderPass.prototype._update = function () {
  24567. this.setRenderList(this._renderList);
  24568. };
  24569. // public
  24570. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24571. this._renderTexture.renderList = renderList;
  24572. };
  24573. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24574. return this._renderTexture;
  24575. };
  24576. return PostProcessRenderPass;
  24577. })();
  24578. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24579. })(BABYLON || (BABYLON = {}));
  24580. var BABYLON;
  24581. (function (BABYLON) {
  24582. var PostProcessRenderEffect = (function () {
  24583. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24584. this._engine = engine;
  24585. this._name = name;
  24586. this._singleInstance = singleInstance || true;
  24587. this._getPostProcess = getPostProcess;
  24588. this._cameras = [];
  24589. this._indicesForCamera = [];
  24590. this._postProcesses = {};
  24591. this._renderPasses = {};
  24592. this._renderEffectAsPasses = {};
  24593. }
  24594. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24595. get: function () {
  24596. for (var index in this._postProcesses) {
  24597. if (!this._postProcesses[index].isSupported) {
  24598. return false;
  24599. }
  24600. }
  24601. return true;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. PostProcessRenderEffect.prototype._update = function () {
  24607. for (var renderPassName in this._renderPasses) {
  24608. this._renderPasses[renderPassName]._update();
  24609. }
  24610. };
  24611. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24612. this._renderPasses[renderPass._name] = renderPass;
  24613. this._linkParameters();
  24614. };
  24615. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24616. delete this._renderPasses[renderPass._name];
  24617. this._linkParameters();
  24618. };
  24619. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24620. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24621. this._linkParameters();
  24622. };
  24623. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24624. for (var renderPassName in this._renderPasses) {
  24625. if (renderPassName === passName) {
  24626. return this._renderPasses[passName];
  24627. }
  24628. }
  24629. };
  24630. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24631. this._renderPasses = {};
  24632. this._linkParameters();
  24633. };
  24634. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24635. var cameraKey;
  24636. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24637. for (var i = 0; i < _cam.length; i++) {
  24638. var camera = _cam[i];
  24639. var cameraName = camera.name;
  24640. if (this._singleInstance) {
  24641. cameraKey = 0;
  24642. }
  24643. else {
  24644. cameraKey = cameraName;
  24645. }
  24646. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24647. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24648. if (!this._indicesForCamera[cameraName]) {
  24649. this._indicesForCamera[cameraName] = [];
  24650. }
  24651. this._indicesForCamera[cameraName].push(index);
  24652. if (this._cameras.indexOf(camera) === -1) {
  24653. this._cameras[cameraName] = camera;
  24654. }
  24655. for (var passName in this._renderPasses) {
  24656. this._renderPasses[passName]._incRefCount();
  24657. }
  24658. }
  24659. this._linkParameters();
  24660. };
  24661. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24663. for (var i = 0; i < _cam.length; i++) {
  24664. var camera = _cam[i];
  24665. var cameraName = camera.name;
  24666. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24667. var index = this._cameras.indexOf(cameraName);
  24668. this._indicesForCamera.splice(index, 1);
  24669. this._cameras.splice(index, 1);
  24670. for (var passName in this._renderPasses) {
  24671. this._renderPasses[passName]._decRefCount();
  24672. }
  24673. }
  24674. };
  24675. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24676. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24677. for (var i = 0; i < _cam.length; i++) {
  24678. var camera = _cam[i];
  24679. var cameraName = camera.name;
  24680. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24681. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24682. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24683. }
  24684. }
  24685. for (var passName in this._renderPasses) {
  24686. this._renderPasses[passName]._incRefCount();
  24687. }
  24688. }
  24689. };
  24690. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24691. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24692. for (var i = 0; i < _cam.length; i++) {
  24693. var camera = _cam[i];
  24694. var cameraName = camera.Name;
  24695. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24696. for (var passName in this._renderPasses) {
  24697. this._renderPasses[passName]._decRefCount();
  24698. }
  24699. }
  24700. };
  24701. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24702. if (this._singleInstance) {
  24703. return this._postProcesses[0];
  24704. }
  24705. else {
  24706. return this._postProcesses[camera.name];
  24707. }
  24708. };
  24709. PostProcessRenderEffect.prototype._linkParameters = function () {
  24710. var _this = this;
  24711. for (var index in this._postProcesses) {
  24712. if (this.applyParameters) {
  24713. this.applyParameters(this._postProcesses[index]);
  24714. }
  24715. this._postProcesses[index].onBeforeRender = function (effect) {
  24716. _this._linkTextures(effect);
  24717. };
  24718. }
  24719. };
  24720. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24721. for (var renderPassName in this._renderPasses) {
  24722. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24723. }
  24724. for (var renderEffectName in this._renderEffectAsPasses) {
  24725. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24726. }
  24727. };
  24728. return PostProcessRenderEffect;
  24729. })();
  24730. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24731. })(BABYLON || (BABYLON = {}));
  24732. var BABYLON;
  24733. (function (BABYLON) {
  24734. var PostProcessRenderPipeline = (function () {
  24735. function PostProcessRenderPipeline(engine, name) {
  24736. this._engine = engine;
  24737. this._name = name;
  24738. this._renderEffects = {};
  24739. this._renderEffectsForIsolatedPass = {};
  24740. this._cameras = [];
  24741. }
  24742. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24743. get: function () {
  24744. for (var renderEffectName in this._renderEffects) {
  24745. if (!this._renderEffects[renderEffectName].isSupported) {
  24746. return false;
  24747. }
  24748. }
  24749. return true;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24755. this._renderEffects[renderEffect._name] = renderEffect;
  24756. };
  24757. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24758. var renderEffects = this._renderEffects[renderEffectName];
  24759. if (!renderEffects) {
  24760. return;
  24761. }
  24762. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24763. };
  24764. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24765. var renderEffects = this._renderEffects[renderEffectName];
  24766. if (!renderEffects) {
  24767. return;
  24768. }
  24769. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24770. };
  24771. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24772. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24773. var indicesToDelete = [];
  24774. var i;
  24775. for (i = 0; i < _cam.length; i++) {
  24776. var camera = _cam[i];
  24777. var cameraName = camera.name;
  24778. if (this._cameras.indexOf(camera) === -1) {
  24779. this._cameras[cameraName] = camera;
  24780. }
  24781. else if (unique) {
  24782. indicesToDelete.push(i);
  24783. }
  24784. }
  24785. for (i = 0; i < indicesToDelete.length; i++) {
  24786. cameras.splice(indicesToDelete[i], 1);
  24787. }
  24788. for (var renderEffectName in this._renderEffects) {
  24789. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24790. }
  24791. };
  24792. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24793. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24794. for (var renderEffectName in this._renderEffects) {
  24795. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24796. }
  24797. for (var i = 0; i < _cam.length; i++) {
  24798. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24799. }
  24800. };
  24801. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24802. var _this = this;
  24803. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24804. var pass = null;
  24805. var renderEffectName;
  24806. for (renderEffectName in this._renderEffects) {
  24807. pass = this._renderEffects[renderEffectName].getPass(passName);
  24808. if (pass != null) {
  24809. break;
  24810. }
  24811. }
  24812. if (pass === null) {
  24813. return;
  24814. }
  24815. for (renderEffectName in this._renderEffects) {
  24816. this._renderEffects[renderEffectName]._disable(_cam);
  24817. }
  24818. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24819. for (var i = 0; i < _cam.length; i++) {
  24820. var camera = _cam[i];
  24821. var cameraName = camera.name;
  24822. 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); });
  24823. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24824. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24825. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24826. }
  24827. };
  24828. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24829. var _this = this;
  24830. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24831. for (var i = 0; i < _cam.length; i++) {
  24832. var camera = _cam[i];
  24833. var cameraName = camera.name;
  24834. 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); });
  24835. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24836. }
  24837. for (var renderEffectName in this._renderEffects) {
  24838. this._renderEffects[renderEffectName]._enable(_cam);
  24839. }
  24840. };
  24841. PostProcessRenderPipeline.prototype._update = function () {
  24842. for (var renderEffectName in this._renderEffects) {
  24843. this._renderEffects[renderEffectName]._update();
  24844. }
  24845. for (var i = 0; i < this._cameras.length; i++) {
  24846. var cameraName = this._cameras[i].name;
  24847. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24848. this._renderEffectsForIsolatedPass[cameraName]._update();
  24849. }
  24850. }
  24851. };
  24852. PostProcessRenderPipeline.prototype.dispose = function () {
  24853. // Must be implemented by children
  24854. };
  24855. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24856. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24857. return PostProcessRenderPipeline;
  24858. })();
  24859. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24860. })(BABYLON || (BABYLON = {}));
  24861. var BABYLON;
  24862. (function (BABYLON) {
  24863. var PostProcessRenderPipelineManager = (function () {
  24864. function PostProcessRenderPipelineManager() {
  24865. this._renderPipelines = {};
  24866. }
  24867. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24868. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24869. };
  24870. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24871. var renderPipeline = this._renderPipelines[renderPipelineName];
  24872. if (!renderPipeline) {
  24873. return;
  24874. }
  24875. renderPipeline._attachCameras(cameras, unique);
  24876. };
  24877. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24878. var renderPipeline = this._renderPipelines[renderPipelineName];
  24879. if (!renderPipeline) {
  24880. return;
  24881. }
  24882. renderPipeline._detachCameras(cameras);
  24883. };
  24884. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24885. var renderPipeline = this._renderPipelines[renderPipelineName];
  24886. if (!renderPipeline) {
  24887. return;
  24888. }
  24889. renderPipeline._enableEffect(renderEffectName, cameras);
  24890. };
  24891. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24892. var renderPipeline = this._renderPipelines[renderPipelineName];
  24893. if (!renderPipeline) {
  24894. return;
  24895. }
  24896. renderPipeline._disableEffect(renderEffectName, cameras);
  24897. };
  24898. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24899. var renderPipeline = this._renderPipelines[renderPipelineName];
  24900. if (!renderPipeline) {
  24901. return;
  24902. }
  24903. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24904. };
  24905. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24906. var renderPipeline = this._renderPipelines[renderPipelineName];
  24907. if (!renderPipeline) {
  24908. return;
  24909. }
  24910. renderPipeline._disableDisplayOnlyPass(cameras);
  24911. };
  24912. PostProcessRenderPipelineManager.prototype.update = function () {
  24913. for (var renderPipelineName in this._renderPipelines) {
  24914. var pipeline = this._renderPipelines[renderPipelineName];
  24915. if (!pipeline.isSupported) {
  24916. pipeline.dispose();
  24917. delete this._renderPipelines[renderPipelineName];
  24918. }
  24919. else {
  24920. pipeline._update();
  24921. }
  24922. }
  24923. };
  24924. return PostProcessRenderPipelineManager;
  24925. })();
  24926. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24927. })(BABYLON || (BABYLON = {}));
  24928. var BABYLON;
  24929. (function (BABYLON) {
  24930. var BoundingBoxRenderer = (function () {
  24931. function BoundingBoxRenderer(scene) {
  24932. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24933. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24934. this.showBackLines = true;
  24935. this.renderList = new BABYLON.SmartArray(32);
  24936. this._scene = scene;
  24937. }
  24938. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24939. if (this._colorShader) {
  24940. return;
  24941. }
  24942. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24943. attributes: ["position"],
  24944. uniforms: ["worldViewProjection", "color"]
  24945. });
  24946. var engine = this._scene.getEngine();
  24947. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24948. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24949. 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]);
  24950. };
  24951. BoundingBoxRenderer.prototype.reset = function () {
  24952. this.renderList.reset();
  24953. };
  24954. BoundingBoxRenderer.prototype.render = function () {
  24955. if (this.renderList.length === 0) {
  24956. return;
  24957. }
  24958. this._prepareRessources();
  24959. if (!this._colorShader.isReady()) {
  24960. return;
  24961. }
  24962. var engine = this._scene.getEngine();
  24963. engine.setDepthWrite(false);
  24964. this._colorShader._preBind();
  24965. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24966. var boundingBox = this.renderList.data[boundingBoxIndex];
  24967. var min = boundingBox.minimum;
  24968. var max = boundingBox.maximum;
  24969. var diff = max.subtract(min);
  24970. var median = min.add(diff.scale(0.5));
  24971. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24972. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24973. .multiply(boundingBox.getWorldMatrix());
  24974. // VBOs
  24975. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24976. if (this.showBackLines) {
  24977. // Back
  24978. engine.setDepthFunctionToGreaterOrEqual();
  24979. this._scene.resetCachedMaterial();
  24980. this._colorShader.setColor4("color", this.backColor.toColor4());
  24981. this._colorShader.bind(worldMatrix);
  24982. // Draw order
  24983. engine.draw(false, 0, 24);
  24984. }
  24985. // Front
  24986. engine.setDepthFunctionToLess();
  24987. this._scene.resetCachedMaterial();
  24988. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24989. this._colorShader.bind(worldMatrix);
  24990. // Draw order
  24991. engine.draw(false, 0, 24);
  24992. }
  24993. this._colorShader.unbind();
  24994. engine.setDepthFunctionToLessOrEqual();
  24995. engine.setDepthWrite(true);
  24996. };
  24997. BoundingBoxRenderer.prototype.dispose = function () {
  24998. if (!this._colorShader) {
  24999. return;
  25000. }
  25001. this._colorShader.dispose();
  25002. this._vb.dispose();
  25003. this._scene.getEngine()._releaseBuffer(this._ib);
  25004. };
  25005. return BoundingBoxRenderer;
  25006. })();
  25007. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25008. })(BABYLON || (BABYLON = {}));
  25009. var BABYLON;
  25010. (function (BABYLON) {
  25011. var Condition = (function () {
  25012. function Condition(actionManager) {
  25013. this._actionManager = actionManager;
  25014. }
  25015. Condition.prototype.isValid = function () {
  25016. return true;
  25017. };
  25018. Condition.prototype._getProperty = function (propertyPath) {
  25019. return this._actionManager._getProperty(propertyPath);
  25020. };
  25021. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25022. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25023. };
  25024. return Condition;
  25025. })();
  25026. BABYLON.Condition = Condition;
  25027. var ValueCondition = (function (_super) {
  25028. __extends(ValueCondition, _super);
  25029. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25030. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25031. _super.call(this, actionManager);
  25032. this.propertyPath = propertyPath;
  25033. this.value = value;
  25034. this.operator = operator;
  25035. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25036. this._property = this._getProperty(this.propertyPath);
  25037. }
  25038. Object.defineProperty(ValueCondition, "IsEqual", {
  25039. get: function () {
  25040. return ValueCondition._IsEqual;
  25041. },
  25042. enumerable: true,
  25043. configurable: true
  25044. });
  25045. Object.defineProperty(ValueCondition, "IsDifferent", {
  25046. get: function () {
  25047. return ValueCondition._IsDifferent;
  25048. },
  25049. enumerable: true,
  25050. configurable: true
  25051. });
  25052. Object.defineProperty(ValueCondition, "IsGreater", {
  25053. get: function () {
  25054. return ValueCondition._IsGreater;
  25055. },
  25056. enumerable: true,
  25057. configurable: true
  25058. });
  25059. Object.defineProperty(ValueCondition, "IsLesser", {
  25060. get: function () {
  25061. return ValueCondition._IsLesser;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. // Methods
  25067. ValueCondition.prototype.isValid = function () {
  25068. switch (this.operator) {
  25069. case ValueCondition.IsGreater:
  25070. return this._target[this._property] > this.value;
  25071. case ValueCondition.IsLesser:
  25072. return this._target[this._property] < this.value;
  25073. case ValueCondition.IsEqual:
  25074. case ValueCondition.IsDifferent:
  25075. var check;
  25076. if (this.value.equals) {
  25077. check = this.value.equals(this._target[this._property]);
  25078. }
  25079. else {
  25080. check = this.value === this._target[this._property];
  25081. }
  25082. return this.operator === ValueCondition.IsEqual ? check : !check;
  25083. }
  25084. return false;
  25085. };
  25086. // Statics
  25087. ValueCondition._IsEqual = 0;
  25088. ValueCondition._IsDifferent = 1;
  25089. ValueCondition._IsGreater = 2;
  25090. ValueCondition._IsLesser = 3;
  25091. return ValueCondition;
  25092. })(Condition);
  25093. BABYLON.ValueCondition = ValueCondition;
  25094. var PredicateCondition = (function (_super) {
  25095. __extends(PredicateCondition, _super);
  25096. function PredicateCondition(actionManager, predicate) {
  25097. _super.call(this, actionManager);
  25098. this.predicate = predicate;
  25099. }
  25100. PredicateCondition.prototype.isValid = function () {
  25101. return this.predicate();
  25102. };
  25103. return PredicateCondition;
  25104. })(Condition);
  25105. BABYLON.PredicateCondition = PredicateCondition;
  25106. var StateCondition = (function (_super) {
  25107. __extends(StateCondition, _super);
  25108. function StateCondition(actionManager, target, value) {
  25109. _super.call(this, actionManager);
  25110. this.value = value;
  25111. this._target = target;
  25112. }
  25113. // Methods
  25114. StateCondition.prototype.isValid = function () {
  25115. return this._target.state === this.value;
  25116. };
  25117. return StateCondition;
  25118. })(Condition);
  25119. BABYLON.StateCondition = StateCondition;
  25120. })(BABYLON || (BABYLON = {}));
  25121. var BABYLON;
  25122. (function (BABYLON) {
  25123. var Action = (function () {
  25124. function Action(triggerOptions, condition) {
  25125. this.triggerOptions = triggerOptions;
  25126. if (triggerOptions.parameter) {
  25127. this.trigger = triggerOptions.trigger;
  25128. this._triggerParameter = triggerOptions.parameter;
  25129. }
  25130. else {
  25131. this.trigger = triggerOptions;
  25132. }
  25133. this._nextActiveAction = this;
  25134. this._condition = condition;
  25135. }
  25136. // Methods
  25137. Action.prototype._prepare = function () {
  25138. };
  25139. Action.prototype.getTriggerParameter = function () {
  25140. return this._triggerParameter;
  25141. };
  25142. Action.prototype._executeCurrent = function (evt) {
  25143. if (this._nextActiveAction._condition) {
  25144. var condition = this._nextActiveAction._condition;
  25145. var currentRenderId = this._actionManager.getScene().getRenderId();
  25146. // We cache the current evaluation for the current frame
  25147. if (condition._evaluationId === currentRenderId) {
  25148. if (!condition._currentResult) {
  25149. return;
  25150. }
  25151. }
  25152. else {
  25153. condition._evaluationId = currentRenderId;
  25154. if (!condition.isValid()) {
  25155. condition._currentResult = false;
  25156. return;
  25157. }
  25158. condition._currentResult = true;
  25159. }
  25160. }
  25161. this._nextActiveAction.execute(evt);
  25162. if (this._nextActiveAction._child) {
  25163. if (!this._nextActiveAction._child._actionManager) {
  25164. this._nextActiveAction._child._actionManager = this._actionManager;
  25165. }
  25166. this._nextActiveAction = this._nextActiveAction._child;
  25167. }
  25168. else {
  25169. this._nextActiveAction = this;
  25170. }
  25171. };
  25172. Action.prototype.execute = function (evt) {
  25173. };
  25174. Action.prototype.then = function (action) {
  25175. this._child = action;
  25176. action._actionManager = this._actionManager;
  25177. action._prepare();
  25178. return action;
  25179. };
  25180. Action.prototype._getProperty = function (propertyPath) {
  25181. return this._actionManager._getProperty(propertyPath);
  25182. };
  25183. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25184. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25185. };
  25186. return Action;
  25187. })();
  25188. BABYLON.Action = Action;
  25189. })(BABYLON || (BABYLON = {}));
  25190. var BABYLON;
  25191. (function (BABYLON) {
  25192. /**
  25193. * ActionEvent is the event beint sent when an action is triggered.
  25194. */
  25195. var ActionEvent = (function () {
  25196. /**
  25197. * @constructor
  25198. * @param source The mesh or sprite that triggered the action.
  25199. * @param pointerX The X mouse cursor position at the time of the event
  25200. * @param pointerY The Y mouse cursor position at the time of the event
  25201. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25202. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25203. */
  25204. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25205. this.source = source;
  25206. this.pointerX = pointerX;
  25207. this.pointerY = pointerY;
  25208. this.meshUnderPointer = meshUnderPointer;
  25209. this.sourceEvent = sourceEvent;
  25210. this.additionalData = additionalData;
  25211. }
  25212. /**
  25213. * Helper function to auto-create an ActionEvent from a source mesh.
  25214. * @param source The source mesh that triggered the event
  25215. * @param evt {Event} The original (browser) event
  25216. */
  25217. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25218. var scene = source.getScene();
  25219. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25220. };
  25221. /**
  25222. * Helper function to auto-create an ActionEvent from a source mesh.
  25223. * @param source The source sprite that triggered the event
  25224. * @param scene Scene associated with the sprite
  25225. * @param evt {Event} The original (browser) event
  25226. */
  25227. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25228. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25229. };
  25230. /**
  25231. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25232. * @param scene the scene where the event occurred
  25233. * @param evt {Event} The original (browser) event
  25234. */
  25235. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25236. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25237. };
  25238. return ActionEvent;
  25239. })();
  25240. BABYLON.ActionEvent = ActionEvent;
  25241. /**
  25242. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25243. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25244. */
  25245. var ActionManager = (function () {
  25246. function ActionManager(scene) {
  25247. // Members
  25248. this.actions = new Array();
  25249. this._scene = scene;
  25250. scene._actionManagers.push(this);
  25251. }
  25252. Object.defineProperty(ActionManager, "NothingTrigger", {
  25253. get: function () {
  25254. return ActionManager._NothingTrigger;
  25255. },
  25256. enumerable: true,
  25257. configurable: true
  25258. });
  25259. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25260. get: function () {
  25261. return ActionManager._OnPickTrigger;
  25262. },
  25263. enumerable: true,
  25264. configurable: true
  25265. });
  25266. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25267. get: function () {
  25268. return ActionManager._OnLeftPickTrigger;
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25274. get: function () {
  25275. return ActionManager._OnRightPickTrigger;
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25281. get: function () {
  25282. return ActionManager._OnCenterPickTrigger;
  25283. },
  25284. enumerable: true,
  25285. configurable: true
  25286. });
  25287. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25288. get: function () {
  25289. return ActionManager._OnPointerOverTrigger;
  25290. },
  25291. enumerable: true,
  25292. configurable: true
  25293. });
  25294. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25295. get: function () {
  25296. return ActionManager._OnPointerOutTrigger;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25302. get: function () {
  25303. return ActionManager._OnEveryFrameTrigger;
  25304. },
  25305. enumerable: true,
  25306. configurable: true
  25307. });
  25308. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25309. get: function () {
  25310. return ActionManager._OnIntersectionEnterTrigger;
  25311. },
  25312. enumerable: true,
  25313. configurable: true
  25314. });
  25315. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25316. get: function () {
  25317. return ActionManager._OnIntersectionExitTrigger;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25323. get: function () {
  25324. return ActionManager._OnKeyDownTrigger;
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25330. get: function () {
  25331. return ActionManager._OnKeyUpTrigger;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25337. get: function () {
  25338. return ActionManager._OnPickUpTrigger;
  25339. },
  25340. enumerable: true,
  25341. configurable: true
  25342. });
  25343. // Methods
  25344. ActionManager.prototype.dispose = function () {
  25345. var index = this._scene._actionManagers.indexOf(this);
  25346. if (index > -1) {
  25347. this._scene._actionManagers.splice(index, 1);
  25348. }
  25349. };
  25350. ActionManager.prototype.getScene = function () {
  25351. return this._scene;
  25352. };
  25353. /**
  25354. * Does this action manager handles actions of any of the given triggers
  25355. * @param {number[]} triggers - the triggers to be tested
  25356. * @return {boolean} whether one (or more) of the triggers is handeled
  25357. */
  25358. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25359. for (var index = 0; index < this.actions.length; index++) {
  25360. var action = this.actions[index];
  25361. if (triggers.indexOf(action.trigger) > -1) {
  25362. return true;
  25363. }
  25364. }
  25365. return false;
  25366. };
  25367. /**
  25368. * Does this action manager handles actions of a given trigger
  25369. * @param {number} trigger - the trigger to be tested
  25370. * @return {boolean} whether the trigger is handeled
  25371. */
  25372. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25373. for (var index = 0; index < this.actions.length; index++) {
  25374. var action = this.actions[index];
  25375. if (action.trigger === trigger) {
  25376. return true;
  25377. }
  25378. }
  25379. return false;
  25380. };
  25381. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25382. /**
  25383. * Does this action manager has pointer triggers
  25384. * @return {boolean} whether or not it has pointer triggers
  25385. */
  25386. get: function () {
  25387. for (var index = 0; index < this.actions.length; index++) {
  25388. var action = this.actions[index];
  25389. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25390. return true;
  25391. }
  25392. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25393. return true;
  25394. }
  25395. }
  25396. return false;
  25397. },
  25398. enumerable: true,
  25399. configurable: true
  25400. });
  25401. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25402. /**
  25403. * Does this action manager has pick triggers
  25404. * @return {boolean} whether or not it has pick triggers
  25405. */
  25406. get: function () {
  25407. for (var index = 0; index < this.actions.length; index++) {
  25408. var action = this.actions[index];
  25409. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25410. return true;
  25411. }
  25412. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25413. return true;
  25414. }
  25415. }
  25416. return false;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. /**
  25422. * Registers an action to this action manager
  25423. * @param {BABYLON.Action} action - the action to be registered
  25424. * @return {BABYLON.Action} the action amended (prepared) after registration
  25425. */
  25426. ActionManager.prototype.registerAction = function (action) {
  25427. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25428. if (this.getScene().actionManager !== this) {
  25429. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25430. return null;
  25431. }
  25432. }
  25433. this.actions.push(action);
  25434. action._actionManager = this;
  25435. action._prepare();
  25436. return action;
  25437. };
  25438. /**
  25439. * Process a specific trigger
  25440. * @param {number} trigger - the trigger to process
  25441. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25442. */
  25443. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25444. for (var index = 0; index < this.actions.length; index++) {
  25445. var action = this.actions[index];
  25446. if (action.trigger === trigger) {
  25447. if (trigger === ActionManager.OnKeyUpTrigger
  25448. || trigger === ActionManager.OnKeyDownTrigger) {
  25449. var parameter = action.getTriggerParameter();
  25450. if (parameter) {
  25451. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25452. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25453. if (actualkey !== parameter.toLowerCase()) {
  25454. continue;
  25455. }
  25456. }
  25457. }
  25458. action._executeCurrent(evt);
  25459. }
  25460. }
  25461. };
  25462. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25463. var properties = propertyPath.split(".");
  25464. for (var index = 0; index < properties.length - 1; index++) {
  25465. target = target[properties[index]];
  25466. }
  25467. return target;
  25468. };
  25469. ActionManager.prototype._getProperty = function (propertyPath) {
  25470. var properties = propertyPath.split(".");
  25471. return properties[properties.length - 1];
  25472. };
  25473. ActionManager.ParseActions = function (parsedActions, object, scene) {
  25474. var actionManager = new BABYLON.ActionManager(scene);
  25475. if (object === null)
  25476. scene.actionManager = actionManager;
  25477. else
  25478. object.actionManager = actionManager;
  25479. // instanciate a new object
  25480. var instanciate = function (name, params) {
  25481. var newInstance = Object.create(BABYLON[name].prototype);
  25482. newInstance.constructor.apply(newInstance, params);
  25483. return newInstance;
  25484. };
  25485. var parseParameter = function (name, value, target, propertyPath) {
  25486. if (propertyPath === null) {
  25487. // String, boolean or float
  25488. var floatValue = parseFloat(value);
  25489. if (value === "true" || value === "false")
  25490. return value === "true";
  25491. else
  25492. return isNaN(floatValue) ? value : floatValue;
  25493. }
  25494. var effectiveTarget = propertyPath.split(".");
  25495. var values = value.split(",");
  25496. // Get effective Target
  25497. for (var i = 0; i < effectiveTarget.length; i++) {
  25498. target = target[effectiveTarget[i]];
  25499. }
  25500. // Return appropriate value with its type
  25501. if (typeof (target) === "boolean")
  25502. return values[0] === "true";
  25503. if (typeof (target) === "string")
  25504. return values[0];
  25505. // Parameters with multiple values such as Vector3 etc.
  25506. var split = new Array();
  25507. for (var i = 0; i < values.length; i++)
  25508. split.push(parseFloat(values[i]));
  25509. if (target instanceof BABYLON.Vector3)
  25510. return BABYLON.Vector3.FromArray(split);
  25511. if (target instanceof BABYLON.Vector4)
  25512. return BABYLON.Vector4.FromArray(split);
  25513. if (target instanceof BABYLON.Color3)
  25514. return BABYLON.Color3.FromArray(split);
  25515. if (target instanceof BABYLON.Color4)
  25516. return BABYLON.Color4.FromArray(split);
  25517. return parseFloat(values[0]);
  25518. };
  25519. // traverse graph per trigger
  25520. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25521. if (combineArray === void 0) { combineArray = null; }
  25522. if (parsedAction.detached)
  25523. return;
  25524. var parameters = new Array();
  25525. var target = null;
  25526. var propertyPath = null;
  25527. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25528. // Parameters
  25529. if (parsedAction.type === 2)
  25530. parameters.push(actionManager);
  25531. else
  25532. parameters.push(trigger);
  25533. if (combine) {
  25534. var actions = new Array();
  25535. for (var j = 0; j < parsedAction.combine.length; j++) {
  25536. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25537. }
  25538. parameters.push(actions);
  25539. }
  25540. else {
  25541. for (var i = 0; i < parsedAction.properties.length; i++) {
  25542. var value = parsedAction.properties[i].value;
  25543. var name = parsedAction.properties[i].name;
  25544. var targetType = parsedAction.properties[i].targetType;
  25545. if (name === "target")
  25546. if (targetType !== null && targetType === "SceneProperties")
  25547. value = target = scene;
  25548. else
  25549. value = target = scene.getNodeByName(value);
  25550. else if (name === "parent")
  25551. value = scene.getNodeByName(value);
  25552. else if (name === "sound")
  25553. value = scene.getSoundByName(value);
  25554. else if (name !== "propertyPath") {
  25555. if (parsedAction.type === 2 && name === "operator")
  25556. value = BABYLON.ValueCondition[value];
  25557. else
  25558. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25559. }
  25560. else {
  25561. propertyPath = value;
  25562. }
  25563. parameters.push(value);
  25564. }
  25565. }
  25566. if (combineArray === null) {
  25567. parameters.push(condition);
  25568. }
  25569. else {
  25570. parameters.push(null);
  25571. }
  25572. // If interpolate value action
  25573. if (parsedAction.name === "InterpolateValueAction") {
  25574. var param = parameters[parameters.length - 2];
  25575. parameters[parameters.length - 1] = param;
  25576. parameters[parameters.length - 2] = condition;
  25577. }
  25578. // Action or condition(s) and not CombineAction
  25579. var newAction = instanciate(parsedAction.name, parameters);
  25580. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25581. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25582. if (action)
  25583. action.then(nothing);
  25584. else
  25585. actionManager.registerAction(nothing);
  25586. action = nothing;
  25587. }
  25588. if (combineArray === null) {
  25589. if (newAction instanceof BABYLON.Condition) {
  25590. condition = newAction;
  25591. newAction = action;
  25592. }
  25593. else {
  25594. condition = null;
  25595. if (action)
  25596. action.then(newAction);
  25597. else
  25598. actionManager.registerAction(newAction);
  25599. }
  25600. }
  25601. else {
  25602. combineArray.push(newAction);
  25603. }
  25604. for (var i = 0; i < parsedAction.children.length; i++)
  25605. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25606. };
  25607. // triggers
  25608. for (var i = 0; i < parsedActions.children.length; i++) {
  25609. var triggerParams;
  25610. var trigger = parsedActions.children[i];
  25611. if (trigger.properties.length > 0) {
  25612. var param = trigger.properties[0].value;
  25613. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25614. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25615. }
  25616. else
  25617. triggerParams = BABYLON.ActionManager[trigger.name];
  25618. for (var j = 0; j < trigger.children.length; j++) {
  25619. if (!trigger.detached)
  25620. traverse(trigger.children[j], triggerParams, null, null);
  25621. }
  25622. }
  25623. };
  25624. // Statics
  25625. ActionManager._NothingTrigger = 0;
  25626. ActionManager._OnPickTrigger = 1;
  25627. ActionManager._OnLeftPickTrigger = 2;
  25628. ActionManager._OnRightPickTrigger = 3;
  25629. ActionManager._OnCenterPickTrigger = 4;
  25630. ActionManager._OnPointerOverTrigger = 5;
  25631. ActionManager._OnPointerOutTrigger = 6;
  25632. ActionManager._OnEveryFrameTrigger = 7;
  25633. ActionManager._OnIntersectionEnterTrigger = 8;
  25634. ActionManager._OnIntersectionExitTrigger = 9;
  25635. ActionManager._OnKeyDownTrigger = 10;
  25636. ActionManager._OnKeyUpTrigger = 11;
  25637. ActionManager._OnPickUpTrigger = 12;
  25638. return ActionManager;
  25639. })();
  25640. BABYLON.ActionManager = ActionManager;
  25641. })(BABYLON || (BABYLON = {}));
  25642. var BABYLON;
  25643. (function (BABYLON) {
  25644. var InterpolateValueAction = (function (_super) {
  25645. __extends(InterpolateValueAction, _super);
  25646. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25647. if (duration === void 0) { duration = 1000; }
  25648. _super.call(this, triggerOptions, condition);
  25649. this.propertyPath = propertyPath;
  25650. this.value = value;
  25651. this.duration = duration;
  25652. this.stopOtherAnimations = stopOtherAnimations;
  25653. this.onInterpolationDone = onInterpolationDone;
  25654. this._target = target;
  25655. }
  25656. InterpolateValueAction.prototype._prepare = function () {
  25657. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25658. this._property = this._getProperty(this.propertyPath);
  25659. };
  25660. InterpolateValueAction.prototype.execute = function () {
  25661. var scene = this._actionManager.getScene();
  25662. var keys = [
  25663. {
  25664. frame: 0,
  25665. value: this._target[this._property]
  25666. }, {
  25667. frame: 100,
  25668. value: this.value
  25669. }
  25670. ];
  25671. var dataType;
  25672. if (typeof this.value === "number") {
  25673. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25674. }
  25675. else if (this.value instanceof BABYLON.Color3) {
  25676. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25677. }
  25678. else if (this.value instanceof BABYLON.Vector3) {
  25679. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25680. }
  25681. else if (this.value instanceof BABYLON.Matrix) {
  25682. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25683. }
  25684. else if (this.value instanceof BABYLON.Quaternion) {
  25685. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25686. }
  25687. else {
  25688. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25689. return;
  25690. }
  25691. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25692. animation.setKeys(keys);
  25693. if (this.stopOtherAnimations) {
  25694. scene.stopAnimation(this._target);
  25695. }
  25696. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25697. };
  25698. return InterpolateValueAction;
  25699. })(BABYLON.Action);
  25700. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25701. })(BABYLON || (BABYLON = {}));
  25702. var BABYLON;
  25703. (function (BABYLON) {
  25704. var SwitchBooleanAction = (function (_super) {
  25705. __extends(SwitchBooleanAction, _super);
  25706. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25707. _super.call(this, triggerOptions, condition);
  25708. this.propertyPath = propertyPath;
  25709. this._target = target;
  25710. }
  25711. SwitchBooleanAction.prototype._prepare = function () {
  25712. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25713. this._property = this._getProperty(this.propertyPath);
  25714. };
  25715. SwitchBooleanAction.prototype.execute = function () {
  25716. this._target[this._property] = !this._target[this._property];
  25717. };
  25718. return SwitchBooleanAction;
  25719. })(BABYLON.Action);
  25720. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25721. var SetStateAction = (function (_super) {
  25722. __extends(SetStateAction, _super);
  25723. function SetStateAction(triggerOptions, target, value, condition) {
  25724. _super.call(this, triggerOptions, condition);
  25725. this.value = value;
  25726. this._target = target;
  25727. }
  25728. SetStateAction.prototype.execute = function () {
  25729. this._target.state = this.value;
  25730. };
  25731. return SetStateAction;
  25732. })(BABYLON.Action);
  25733. BABYLON.SetStateAction = SetStateAction;
  25734. var SetValueAction = (function (_super) {
  25735. __extends(SetValueAction, _super);
  25736. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25737. _super.call(this, triggerOptions, condition);
  25738. this.propertyPath = propertyPath;
  25739. this.value = value;
  25740. this._target = target;
  25741. }
  25742. SetValueAction.prototype._prepare = function () {
  25743. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25744. this._property = this._getProperty(this.propertyPath);
  25745. };
  25746. SetValueAction.prototype.execute = function () {
  25747. this._target[this._property] = this.value;
  25748. };
  25749. return SetValueAction;
  25750. })(BABYLON.Action);
  25751. BABYLON.SetValueAction = SetValueAction;
  25752. var IncrementValueAction = (function (_super) {
  25753. __extends(IncrementValueAction, _super);
  25754. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25755. _super.call(this, triggerOptions, condition);
  25756. this.propertyPath = propertyPath;
  25757. this.value = value;
  25758. this._target = target;
  25759. }
  25760. IncrementValueAction.prototype._prepare = function () {
  25761. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25762. this._property = this._getProperty(this.propertyPath);
  25763. if (typeof this._target[this._property] !== "number") {
  25764. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25765. }
  25766. };
  25767. IncrementValueAction.prototype.execute = function () {
  25768. this._target[this._property] += this.value;
  25769. };
  25770. return IncrementValueAction;
  25771. })(BABYLON.Action);
  25772. BABYLON.IncrementValueAction = IncrementValueAction;
  25773. var PlayAnimationAction = (function (_super) {
  25774. __extends(PlayAnimationAction, _super);
  25775. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25776. _super.call(this, triggerOptions, condition);
  25777. this.from = from;
  25778. this.to = to;
  25779. this.loop = loop;
  25780. this._target = target;
  25781. }
  25782. PlayAnimationAction.prototype._prepare = function () {
  25783. };
  25784. PlayAnimationAction.prototype.execute = function () {
  25785. var scene = this._actionManager.getScene();
  25786. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25787. };
  25788. return PlayAnimationAction;
  25789. })(BABYLON.Action);
  25790. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25791. var StopAnimationAction = (function (_super) {
  25792. __extends(StopAnimationAction, _super);
  25793. function StopAnimationAction(triggerOptions, target, condition) {
  25794. _super.call(this, triggerOptions, condition);
  25795. this._target = target;
  25796. }
  25797. StopAnimationAction.prototype._prepare = function () {
  25798. };
  25799. StopAnimationAction.prototype.execute = function () {
  25800. var scene = this._actionManager.getScene();
  25801. scene.stopAnimation(this._target);
  25802. };
  25803. return StopAnimationAction;
  25804. })(BABYLON.Action);
  25805. BABYLON.StopAnimationAction = StopAnimationAction;
  25806. var DoNothingAction = (function (_super) {
  25807. __extends(DoNothingAction, _super);
  25808. function DoNothingAction(triggerOptions, condition) {
  25809. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25810. _super.call(this, triggerOptions, condition);
  25811. }
  25812. DoNothingAction.prototype.execute = function () {
  25813. };
  25814. return DoNothingAction;
  25815. })(BABYLON.Action);
  25816. BABYLON.DoNothingAction = DoNothingAction;
  25817. var CombineAction = (function (_super) {
  25818. __extends(CombineAction, _super);
  25819. function CombineAction(triggerOptions, children, condition) {
  25820. _super.call(this, triggerOptions, condition);
  25821. this.children = children;
  25822. }
  25823. CombineAction.prototype._prepare = function () {
  25824. for (var index = 0; index < this.children.length; index++) {
  25825. this.children[index]._actionManager = this._actionManager;
  25826. this.children[index]._prepare();
  25827. }
  25828. };
  25829. CombineAction.prototype.execute = function (evt) {
  25830. for (var index = 0; index < this.children.length; index++) {
  25831. this.children[index].execute(evt);
  25832. }
  25833. };
  25834. return CombineAction;
  25835. })(BABYLON.Action);
  25836. BABYLON.CombineAction = CombineAction;
  25837. var ExecuteCodeAction = (function (_super) {
  25838. __extends(ExecuteCodeAction, _super);
  25839. function ExecuteCodeAction(triggerOptions, func, condition) {
  25840. _super.call(this, triggerOptions, condition);
  25841. this.func = func;
  25842. }
  25843. ExecuteCodeAction.prototype.execute = function (evt) {
  25844. this.func(evt);
  25845. };
  25846. return ExecuteCodeAction;
  25847. })(BABYLON.Action);
  25848. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25849. var SetParentAction = (function (_super) {
  25850. __extends(SetParentAction, _super);
  25851. function SetParentAction(triggerOptions, target, parent, condition) {
  25852. _super.call(this, triggerOptions, condition);
  25853. this._target = target;
  25854. this._parent = parent;
  25855. }
  25856. SetParentAction.prototype._prepare = function () {
  25857. };
  25858. SetParentAction.prototype.execute = function () {
  25859. if (this._target.parent === this._parent) {
  25860. return;
  25861. }
  25862. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25863. invertParentWorldMatrix.invert();
  25864. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25865. this._target.parent = this._parent;
  25866. };
  25867. return SetParentAction;
  25868. })(BABYLON.Action);
  25869. BABYLON.SetParentAction = SetParentAction;
  25870. var PlaySoundAction = (function (_super) {
  25871. __extends(PlaySoundAction, _super);
  25872. function PlaySoundAction(triggerOptions, sound, condition) {
  25873. _super.call(this, triggerOptions, condition);
  25874. this._sound = sound;
  25875. }
  25876. PlaySoundAction.prototype._prepare = function () {
  25877. };
  25878. PlaySoundAction.prototype.execute = function () {
  25879. if (this._sound !== undefined)
  25880. this._sound.play();
  25881. };
  25882. return PlaySoundAction;
  25883. })(BABYLON.Action);
  25884. BABYLON.PlaySoundAction = PlaySoundAction;
  25885. var StopSoundAction = (function (_super) {
  25886. __extends(StopSoundAction, _super);
  25887. function StopSoundAction(triggerOptions, sound, condition) {
  25888. _super.call(this, triggerOptions, condition);
  25889. this._sound = sound;
  25890. }
  25891. StopSoundAction.prototype._prepare = function () {
  25892. };
  25893. StopSoundAction.prototype.execute = function () {
  25894. if (this._sound !== undefined)
  25895. this._sound.stop();
  25896. };
  25897. return StopSoundAction;
  25898. })(BABYLON.Action);
  25899. BABYLON.StopSoundAction = StopSoundAction;
  25900. })(BABYLON || (BABYLON = {}));
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. var Geometry = (function () {
  25904. function Geometry(id, scene, vertexData, updatable, mesh) {
  25905. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25906. this._totalVertices = 0;
  25907. this._isDisposed = false;
  25908. this.id = id;
  25909. this._engine = scene.getEngine();
  25910. this._meshes = [];
  25911. this._scene = scene;
  25912. //Init vertex buffer cache
  25913. this._vertexBuffers = {};
  25914. this._indices = [];
  25915. // vertexData
  25916. if (vertexData) {
  25917. this.setAllVerticesData(vertexData, updatable);
  25918. }
  25919. else {
  25920. this._totalVertices = 0;
  25921. this._indices = [];
  25922. }
  25923. // applyToMesh
  25924. if (mesh) {
  25925. this.applyToMesh(mesh);
  25926. mesh.computeWorldMatrix(true);
  25927. }
  25928. }
  25929. Object.defineProperty(Geometry.prototype, "extend", {
  25930. get: function () {
  25931. return this._extend;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Geometry.prototype.getScene = function () {
  25937. return this._scene;
  25938. };
  25939. Geometry.prototype.getEngine = function () {
  25940. return this._engine;
  25941. };
  25942. Geometry.prototype.isReady = function () {
  25943. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25944. };
  25945. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25946. vertexData.applyToGeometry(this, updatable);
  25947. this.notifyUpdate();
  25948. };
  25949. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25950. if (this._vertexBuffers[kind]) {
  25951. this._vertexBuffers[kind].dispose();
  25952. }
  25953. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25954. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25955. stride = this._vertexBuffers[kind].getStrideSize();
  25956. this._totalVertices = data.length / stride;
  25957. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25958. var meshes = this._meshes;
  25959. var numOfMeshes = meshes.length;
  25960. for (var index = 0; index < numOfMeshes; index++) {
  25961. var mesh = meshes[index];
  25962. mesh._resetPointsArrayCache();
  25963. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25964. mesh._createGlobalSubMesh();
  25965. mesh.computeWorldMatrix(true);
  25966. }
  25967. }
  25968. this.notifyUpdate(kind);
  25969. };
  25970. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25971. var vertexBuffer = this.getVertexBuffer(kind);
  25972. if (!vertexBuffer) {
  25973. return;
  25974. }
  25975. vertexBuffer.updateDirectly(data, offset);
  25976. this.notifyUpdate(kind);
  25977. };
  25978. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25979. var vertexBuffer = this.getVertexBuffer(kind);
  25980. if (!vertexBuffer) {
  25981. return;
  25982. }
  25983. vertexBuffer.update(data);
  25984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25985. var stride = vertexBuffer.getStrideSize();
  25986. this._totalVertices = data.length / stride;
  25987. if (updateExtends) {
  25988. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25989. }
  25990. var meshes = this._meshes;
  25991. var numOfMeshes = meshes.length;
  25992. for (var index = 0; index < numOfMeshes; index++) {
  25993. var mesh = meshes[index];
  25994. mesh._resetPointsArrayCache();
  25995. if (updateExtends) {
  25996. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25997. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25998. var subMesh = mesh.subMeshes[subIndex];
  25999. subMesh.refreshBoundingInfo();
  26000. }
  26001. }
  26002. }
  26003. }
  26004. this.notifyUpdate(kind);
  26005. };
  26006. Geometry.prototype.getTotalVertices = function () {
  26007. if (!this.isReady()) {
  26008. return 0;
  26009. }
  26010. return this._totalVertices;
  26011. };
  26012. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26013. var vertexBuffer = this.getVertexBuffer(kind);
  26014. if (!vertexBuffer) {
  26015. return null;
  26016. }
  26017. var orig = vertexBuffer.getData();
  26018. if (!copyWhenShared || this._meshes.length === 1) {
  26019. return orig;
  26020. }
  26021. else {
  26022. var len = orig.length;
  26023. var copy = [];
  26024. for (var i = 0; i < len; i++) {
  26025. copy.push(orig[i]);
  26026. }
  26027. return copy;
  26028. }
  26029. };
  26030. Geometry.prototype.getVertexBuffer = function (kind) {
  26031. if (!this.isReady()) {
  26032. return null;
  26033. }
  26034. return this._vertexBuffers[kind];
  26035. };
  26036. Geometry.prototype.getVertexBuffers = function () {
  26037. if (!this.isReady()) {
  26038. return null;
  26039. }
  26040. return this._vertexBuffers;
  26041. };
  26042. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26043. if (!this._vertexBuffers) {
  26044. if (this._delayInfo) {
  26045. return this._delayInfo.indexOf(kind) !== -1;
  26046. }
  26047. return false;
  26048. }
  26049. return this._vertexBuffers[kind] !== undefined;
  26050. };
  26051. Geometry.prototype.getVerticesDataKinds = function () {
  26052. var result = [];
  26053. var kind;
  26054. if (!this._vertexBuffers && this._delayInfo) {
  26055. for (kind in this._delayInfo) {
  26056. result.push(kind);
  26057. }
  26058. }
  26059. else {
  26060. for (kind in this._vertexBuffers) {
  26061. result.push(kind);
  26062. }
  26063. }
  26064. return result;
  26065. };
  26066. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26067. if (this._indexBuffer) {
  26068. this._engine._releaseBuffer(this._indexBuffer);
  26069. }
  26070. this._indices = indices;
  26071. if (this._meshes.length !== 0 && this._indices) {
  26072. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26073. }
  26074. if (totalVertices !== undefined) {
  26075. this._totalVertices = totalVertices;
  26076. }
  26077. var meshes = this._meshes;
  26078. var numOfMeshes = meshes.length;
  26079. for (var index = 0; index < numOfMeshes; index++) {
  26080. meshes[index]._createGlobalSubMesh();
  26081. }
  26082. this.notifyUpdate();
  26083. };
  26084. Geometry.prototype.getTotalIndices = function () {
  26085. if (!this.isReady()) {
  26086. return 0;
  26087. }
  26088. return this._indices.length;
  26089. };
  26090. Geometry.prototype.getIndices = function (copyWhenShared) {
  26091. if (!this.isReady()) {
  26092. return null;
  26093. }
  26094. var orig = this._indices;
  26095. if (!copyWhenShared || this._meshes.length === 1) {
  26096. return orig;
  26097. }
  26098. else {
  26099. var len = orig.length;
  26100. var copy = [];
  26101. for (var i = 0; i < len; i++) {
  26102. copy.push(orig[i]);
  26103. }
  26104. return copy;
  26105. }
  26106. };
  26107. Geometry.prototype.getIndexBuffer = function () {
  26108. if (!this.isReady()) {
  26109. return null;
  26110. }
  26111. return this._indexBuffer;
  26112. };
  26113. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26114. var meshes = this._meshes;
  26115. var index = meshes.indexOf(mesh);
  26116. if (index === -1) {
  26117. return;
  26118. }
  26119. for (var kind in this._vertexBuffers) {
  26120. this._vertexBuffers[kind].dispose();
  26121. }
  26122. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26123. this._indexBuffer = null;
  26124. }
  26125. meshes.splice(index, 1);
  26126. mesh._geometry = null;
  26127. if (meshes.length === 0 && shouldDispose) {
  26128. this.dispose();
  26129. }
  26130. };
  26131. Geometry.prototype.applyToMesh = function (mesh) {
  26132. if (mesh._geometry === this) {
  26133. return;
  26134. }
  26135. var previousGeometry = mesh._geometry;
  26136. if (previousGeometry) {
  26137. previousGeometry.releaseForMesh(mesh);
  26138. }
  26139. var meshes = this._meshes;
  26140. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26141. mesh._geometry = this;
  26142. this._scene.pushGeometry(this);
  26143. meshes.push(mesh);
  26144. if (this.isReady()) {
  26145. this._applyToMesh(mesh);
  26146. }
  26147. else {
  26148. mesh._boundingInfo = this._boundingInfo;
  26149. }
  26150. };
  26151. Geometry.prototype._applyToMesh = function (mesh) {
  26152. var numOfMeshes = this._meshes.length;
  26153. // vertexBuffers
  26154. for (var kind in this._vertexBuffers) {
  26155. if (numOfMeshes === 1) {
  26156. this._vertexBuffers[kind].create();
  26157. }
  26158. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26159. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26160. mesh._resetPointsArrayCache();
  26161. if (!this._extend) {
  26162. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26163. }
  26164. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26165. mesh._createGlobalSubMesh();
  26166. //bounding info was just created again, world matrix should be applied again.
  26167. mesh._updateBoundingInfo();
  26168. }
  26169. }
  26170. // indexBuffer
  26171. if (numOfMeshes === 1 && this._indices) {
  26172. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26173. }
  26174. if (this._indexBuffer) {
  26175. this._indexBuffer.references = numOfMeshes;
  26176. }
  26177. };
  26178. Geometry.prototype.notifyUpdate = function (kind) {
  26179. if (this.onGeometryUpdated) {
  26180. this.onGeometryUpdated(this, kind);
  26181. }
  26182. };
  26183. Geometry.prototype.load = function (scene, onLoaded) {
  26184. var _this = this;
  26185. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26186. return;
  26187. }
  26188. if (this.isReady()) {
  26189. if (onLoaded) {
  26190. onLoaded();
  26191. }
  26192. return;
  26193. }
  26194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26195. scene._addPendingData(this);
  26196. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26197. _this._delayLoadingFunction(JSON.parse(data), _this);
  26198. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26199. _this._delayInfo = [];
  26200. scene._removePendingData(_this);
  26201. var meshes = _this._meshes;
  26202. var numOfMeshes = meshes.length;
  26203. for (var index = 0; index < numOfMeshes; index++) {
  26204. _this._applyToMesh(meshes[index]);
  26205. }
  26206. if (onLoaded) {
  26207. onLoaded();
  26208. }
  26209. }, function () { }, scene.database);
  26210. };
  26211. Geometry.prototype.isDisposed = function () {
  26212. return this._isDisposed;
  26213. };
  26214. Geometry.prototype.dispose = function () {
  26215. var meshes = this._meshes;
  26216. var numOfMeshes = meshes.length;
  26217. var index;
  26218. for (index = 0; index < numOfMeshes; index++) {
  26219. this.releaseForMesh(meshes[index]);
  26220. }
  26221. this._meshes = [];
  26222. for (var kind in this._vertexBuffers) {
  26223. this._vertexBuffers[kind].dispose();
  26224. }
  26225. this._vertexBuffers = [];
  26226. this._totalVertices = 0;
  26227. if (this._indexBuffer) {
  26228. this._engine._releaseBuffer(this._indexBuffer);
  26229. }
  26230. this._indexBuffer = null;
  26231. this._indices = [];
  26232. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26233. this.delayLoadingFile = null;
  26234. this._delayLoadingFunction = null;
  26235. this._delayInfo = [];
  26236. this._boundingInfo = null;
  26237. this._scene.removeGeometry(this);
  26238. this._isDisposed = true;
  26239. };
  26240. Geometry.prototype.copy = function (id) {
  26241. var vertexData = new BABYLON.VertexData();
  26242. vertexData.indices = [];
  26243. var indices = this.getIndices();
  26244. for (var index = 0; index < indices.length; index++) {
  26245. vertexData.indices.push(indices[index]);
  26246. }
  26247. var updatable = false;
  26248. var stopChecking = false;
  26249. var kind;
  26250. for (kind in this._vertexBuffers) {
  26251. // using slice() to make a copy of the array and not just reference it
  26252. var data = this.getVerticesData(kind);
  26253. if (data instanceof Float32Array) {
  26254. vertexData.set(new Float32Array(data), kind);
  26255. }
  26256. else {
  26257. vertexData.set(data.slice(0), kind);
  26258. }
  26259. if (!stopChecking) {
  26260. updatable = this.getVertexBuffer(kind).isUpdatable();
  26261. stopChecking = !updatable;
  26262. }
  26263. }
  26264. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26265. geometry.delayLoadState = this.delayLoadState;
  26266. geometry.delayLoadingFile = this.delayLoadingFile;
  26267. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26268. for (kind in this._delayInfo) {
  26269. geometry._delayInfo = geometry._delayInfo || [];
  26270. geometry._delayInfo.push(kind);
  26271. }
  26272. // Bounding info
  26273. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26274. return geometry;
  26275. };
  26276. // Statics
  26277. Geometry.ExtractFromMesh = function (mesh, id) {
  26278. var geometry = mesh._geometry;
  26279. if (!geometry) {
  26280. return null;
  26281. }
  26282. return geometry.copy(id);
  26283. };
  26284. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26285. // be aware Math.random() could cause collisions
  26286. Geometry.RandomId = function () {
  26287. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26288. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26289. return v.toString(16);
  26290. });
  26291. };
  26292. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26293. var scene = mesh.getScene();
  26294. // Geometry
  26295. var geometryId = parsedGeometry.geometryId;
  26296. if (geometryId) {
  26297. var geometry = scene.getGeometryByID(geometryId);
  26298. if (geometry) {
  26299. geometry.applyToMesh(mesh);
  26300. }
  26301. }
  26302. else if (parsedGeometry instanceof ArrayBuffer) {
  26303. var binaryInfo = mesh._binaryInfo;
  26304. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26305. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26306. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26307. }
  26308. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26309. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26310. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26311. }
  26312. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26313. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26314. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26315. }
  26316. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26317. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26318. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26319. }
  26320. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26321. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26322. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26323. }
  26324. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26325. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26326. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26327. }
  26328. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26329. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26330. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26331. }
  26332. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26333. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26334. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26335. }
  26336. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26337. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26338. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26339. }
  26340. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26341. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26342. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26343. }
  26344. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26345. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26346. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26347. }
  26348. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26349. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26350. mesh.setIndices(indicesData);
  26351. }
  26352. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26353. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26354. mesh.subMeshes = [];
  26355. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26356. var materialIndex = subMeshesData[(i * 5) + 0];
  26357. var verticesStart = subMeshesData[(i * 5) + 1];
  26358. var verticesCount = subMeshesData[(i * 5) + 2];
  26359. var indexStart = subMeshesData[(i * 5) + 3];
  26360. var indexCount = subMeshesData[(i * 5) + 4];
  26361. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26362. }
  26363. }
  26364. }
  26365. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26366. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26367. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26368. if (parsedGeometry.uvs) {
  26369. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26370. }
  26371. if (parsedGeometry.uvs2) {
  26372. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26373. }
  26374. if (parsedGeometry.uvs3) {
  26375. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26376. }
  26377. if (parsedGeometry.uvs4) {
  26378. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26379. }
  26380. if (parsedGeometry.uvs5) {
  26381. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26382. }
  26383. if (parsedGeometry.uvs6) {
  26384. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26385. }
  26386. if (parsedGeometry.colors) {
  26387. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26388. }
  26389. if (parsedGeometry.matricesIndices) {
  26390. if (!parsedGeometry.matricesIndices._isExpanded) {
  26391. var floatIndices = [];
  26392. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26393. var matricesIndex = parsedGeometry.matricesIndices[i];
  26394. floatIndices.push(matricesIndex & 0x000000FF);
  26395. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26396. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26397. floatIndices.push(matricesIndex >> 24);
  26398. }
  26399. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26400. }
  26401. else {
  26402. delete parsedGeometry.matricesIndices._isExpanded;
  26403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26404. }
  26405. }
  26406. if (parsedGeometry.matricesIndicesExtra) {
  26407. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26408. var floatIndices = [];
  26409. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26410. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26411. floatIndices.push(matricesIndex & 0x000000FF);
  26412. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26413. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26414. floatIndices.push(matricesIndex >> 24);
  26415. }
  26416. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26417. }
  26418. else {
  26419. delete parsedGeometry.matricesIndices._isExpanded;
  26420. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26421. }
  26422. }
  26423. if (parsedGeometry.matricesWeights) {
  26424. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26425. }
  26426. if (parsedGeometry.matricesWeightsExtra) {
  26427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26428. }
  26429. mesh.setIndices(parsedGeometry.indices);
  26430. }
  26431. // SubMeshes
  26432. if (parsedGeometry.subMeshes) {
  26433. mesh.subMeshes = [];
  26434. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26435. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26436. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26437. }
  26438. }
  26439. // Flat shading
  26440. if (mesh._shouldGenerateFlatShading) {
  26441. mesh.convertToFlatShadedMesh();
  26442. delete mesh._shouldGenerateFlatShading;
  26443. }
  26444. // Update
  26445. mesh.computeWorldMatrix(true);
  26446. // Octree
  26447. if (scene['_selectionOctree']) {
  26448. scene['_selectionOctree'].addMesh(mesh);
  26449. }
  26450. };
  26451. Geometry.ParseGeometry = function (parsedVertexData, scene, rootUrl) {
  26452. if (scene.getGeometryByID(parsedVertexData.id)) {
  26453. return null; // null since geometry could be something else than a box...
  26454. }
  26455. var geometry = new Geometry(parsedVertexData.id, scene);
  26456. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26457. if (parsedVertexData.delayLoadingFile) {
  26458. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26459. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26460. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26461. geometry._delayInfo = [];
  26462. if (parsedVertexData.hasUVs) {
  26463. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26464. }
  26465. if (parsedVertexData.hasUVs2) {
  26466. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26467. }
  26468. if (parsedVertexData.hasUVs3) {
  26469. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26470. }
  26471. if (parsedVertexData.hasUVs4) {
  26472. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26473. }
  26474. if (parsedVertexData.hasUVs5) {
  26475. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26476. }
  26477. if (parsedVertexData.hasUVs6) {
  26478. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26479. }
  26480. if (parsedVertexData.hasColors) {
  26481. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26482. }
  26483. if (parsedVertexData.hasMatricesIndices) {
  26484. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26485. }
  26486. if (parsedVertexData.hasMatricesWeights) {
  26487. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26488. }
  26489. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26490. }
  26491. else {
  26492. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26493. }
  26494. scene.pushGeometry(geometry, true);
  26495. return geometry;
  26496. };
  26497. return Geometry;
  26498. })();
  26499. BABYLON.Geometry = Geometry;
  26500. /////// Primitives //////////////////////////////////////////////
  26501. var Geometry;
  26502. (function (Geometry) {
  26503. var Primitives;
  26504. (function (Primitives) {
  26505. /// Abstract class
  26506. var _Primitive = (function (_super) {
  26507. __extends(_Primitive, _super);
  26508. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26509. this._beingRegenerated = true;
  26510. this._canBeRegenerated = canBeRegenerated;
  26511. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26512. this._beingRegenerated = false;
  26513. }
  26514. _Primitive.prototype.canBeRegenerated = function () {
  26515. return this._canBeRegenerated;
  26516. };
  26517. _Primitive.prototype.regenerate = function () {
  26518. if (!this._canBeRegenerated) {
  26519. return;
  26520. }
  26521. this._beingRegenerated = true;
  26522. this.setAllVerticesData(this._regenerateVertexData(), false);
  26523. this._beingRegenerated = false;
  26524. };
  26525. _Primitive.prototype.asNewGeometry = function (id) {
  26526. return _super.prototype.copy.call(this, id);
  26527. };
  26528. // overrides
  26529. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26530. if (!this._beingRegenerated) {
  26531. return;
  26532. }
  26533. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26534. };
  26535. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26536. if (!this._beingRegenerated) {
  26537. return;
  26538. }
  26539. _super.prototype.setVerticesData.call(this, kind, data, false);
  26540. };
  26541. // to override
  26542. // protected
  26543. _Primitive.prototype._regenerateVertexData = function () {
  26544. throw new Error("Abstract method");
  26545. };
  26546. _Primitive.prototype.copy = function (id) {
  26547. throw new Error("Must be overriden in sub-classes.");
  26548. };
  26549. return _Primitive;
  26550. })(Geometry);
  26551. Primitives._Primitive = _Primitive;
  26552. var Ribbon = (function (_super) {
  26553. __extends(Ribbon, _super);
  26554. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26555. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26556. this.pathArray = pathArray;
  26557. this.closeArray = closeArray;
  26558. this.closePath = closePath;
  26559. this.offset = offset;
  26560. this.side = side;
  26561. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26562. }
  26563. Ribbon.prototype._regenerateVertexData = function () {
  26564. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26565. };
  26566. Ribbon.prototype.copy = function (id) {
  26567. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26568. };
  26569. return Ribbon;
  26570. })(_Primitive);
  26571. Primitives.Ribbon = Ribbon;
  26572. var Box = (function (_super) {
  26573. __extends(Box, _super);
  26574. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26576. this.size = size;
  26577. this.side = side;
  26578. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26579. }
  26580. Box.prototype._regenerateVertexData = function () {
  26581. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26582. };
  26583. Box.prototype.copy = function (id) {
  26584. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26585. };
  26586. Box.ParseBox = function (parsedBox, scene) {
  26587. if (scene.getGeometryByID(parsedBox.id)) {
  26588. return null; // null since geometry could be something else than a box...
  26589. }
  26590. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26591. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26592. scene.pushGeometry(box, true);
  26593. return box;
  26594. };
  26595. return Box;
  26596. })(_Primitive);
  26597. Primitives.Box = Box;
  26598. var Sphere = (function (_super) {
  26599. __extends(Sphere, _super);
  26600. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26601. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26602. this.segments = segments;
  26603. this.diameter = diameter;
  26604. this.side = side;
  26605. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26606. }
  26607. Sphere.prototype._regenerateVertexData = function () {
  26608. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26609. };
  26610. Sphere.prototype.copy = function (id) {
  26611. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26612. };
  26613. Sphere.ParseSphere = function (parsedSphere, scene) {
  26614. if (scene.getGeometryByID(parsedSphere.id)) {
  26615. return null; // null since geometry could be something else than a sphere...
  26616. }
  26617. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26618. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26619. scene.pushGeometry(sphere, true);
  26620. return sphere;
  26621. };
  26622. return Sphere;
  26623. })(_Primitive);
  26624. Primitives.Sphere = Sphere;
  26625. var Disc = (function (_super) {
  26626. __extends(Disc, _super);
  26627. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26628. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26629. this.radius = radius;
  26630. this.tessellation = tessellation;
  26631. this.side = side;
  26632. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26633. }
  26634. Disc.prototype._regenerateVertexData = function () {
  26635. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26636. };
  26637. Disc.prototype.copy = function (id) {
  26638. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26639. };
  26640. return Disc;
  26641. })(_Primitive);
  26642. Primitives.Disc = Disc;
  26643. var Cylinder = (function (_super) {
  26644. __extends(Cylinder, _super);
  26645. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26646. if (subdivisions === void 0) { subdivisions = 1; }
  26647. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26648. this.height = height;
  26649. this.diameterTop = diameterTop;
  26650. this.diameterBottom = diameterBottom;
  26651. this.tessellation = tessellation;
  26652. this.subdivisions = subdivisions;
  26653. this.side = side;
  26654. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26655. }
  26656. Cylinder.prototype._regenerateVertexData = function () {
  26657. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26658. };
  26659. Cylinder.prototype.copy = function (id) {
  26660. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26661. };
  26662. Cylinder.ParseCylinder = function (parsedCylinder, scene) {
  26663. if (scene.getGeometryByID(parsedCylinder.id)) {
  26664. return null; // null since geometry could be something else than a cylinder...
  26665. }
  26666. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26667. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26668. scene.pushGeometry(cylinder, true);
  26669. return cylinder;
  26670. };
  26671. return Cylinder;
  26672. })(_Primitive);
  26673. Primitives.Cylinder = Cylinder;
  26674. var Torus = (function (_super) {
  26675. __extends(Torus, _super);
  26676. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26677. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26678. this.diameter = diameter;
  26679. this.thickness = thickness;
  26680. this.tessellation = tessellation;
  26681. this.side = side;
  26682. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26683. }
  26684. Torus.prototype._regenerateVertexData = function () {
  26685. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26686. };
  26687. Torus.prototype.copy = function (id) {
  26688. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26689. };
  26690. Torus.ParseTorus = function (parsedTorus, scene) {
  26691. if (scene.getGeometryByID(parsedTorus.id)) {
  26692. return null; // null since geometry could be something else than a torus...
  26693. }
  26694. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26695. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26696. scene.pushGeometry(torus, true);
  26697. return torus;
  26698. };
  26699. return Torus;
  26700. })(_Primitive);
  26701. Primitives.Torus = Torus;
  26702. var Ground = (function (_super) {
  26703. __extends(Ground, _super);
  26704. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26705. this.width = width;
  26706. this.height = height;
  26707. this.subdivisions = subdivisions;
  26708. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26709. }
  26710. Ground.prototype._regenerateVertexData = function () {
  26711. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26712. };
  26713. Ground.prototype.copy = function (id) {
  26714. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26715. };
  26716. Ground.ParseGround = function (parsedGround, scene) {
  26717. if (scene.getGeometryByID(parsedGround.id)) {
  26718. return null; // null since geometry could be something else than a ground...
  26719. }
  26720. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26721. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26722. scene.pushGeometry(ground, true);
  26723. return ground;
  26724. };
  26725. return Ground;
  26726. })(_Primitive);
  26727. Primitives.Ground = Ground;
  26728. var TiledGround = (function (_super) {
  26729. __extends(TiledGround, _super);
  26730. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26731. this.xmin = xmin;
  26732. this.zmin = zmin;
  26733. this.xmax = xmax;
  26734. this.zmax = zmax;
  26735. this.subdivisions = subdivisions;
  26736. this.precision = precision;
  26737. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26738. }
  26739. TiledGround.prototype._regenerateVertexData = function () {
  26740. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26741. };
  26742. TiledGround.prototype.copy = function (id) {
  26743. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26744. };
  26745. return TiledGround;
  26746. })(_Primitive);
  26747. Primitives.TiledGround = TiledGround;
  26748. var Plane = (function (_super) {
  26749. __extends(Plane, _super);
  26750. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26752. this.size = size;
  26753. this.side = side;
  26754. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26755. }
  26756. Plane.prototype._regenerateVertexData = function () {
  26757. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26758. };
  26759. Plane.prototype.copy = function (id) {
  26760. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26761. };
  26762. Plane.ParsePlane = function (parsedPlane, scene) {
  26763. if (scene.getGeometryByID(parsedPlane.id)) {
  26764. return null; // null since geometry could be something else than a ground...
  26765. }
  26766. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26767. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26768. scene.pushGeometry(plane, true);
  26769. return plane;
  26770. };
  26771. return Plane;
  26772. })(_Primitive);
  26773. Primitives.Plane = Plane;
  26774. var TorusKnot = (function (_super) {
  26775. __extends(TorusKnot, _super);
  26776. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26777. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26778. this.radius = radius;
  26779. this.tube = tube;
  26780. this.radialSegments = radialSegments;
  26781. this.tubularSegments = tubularSegments;
  26782. this.p = p;
  26783. this.q = q;
  26784. this.side = side;
  26785. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26786. }
  26787. TorusKnot.prototype._regenerateVertexData = function () {
  26788. 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 });
  26789. };
  26790. TorusKnot.prototype.copy = function (id) {
  26791. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26792. };
  26793. TorusKnot.ParseTorusKnot = function (parsedTorusKnot, scene) {
  26794. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26795. return null; // null since geometry could be something else than a ground...
  26796. }
  26797. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26798. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26799. scene.pushGeometry(torusKnot, true);
  26800. return torusKnot;
  26801. };
  26802. return TorusKnot;
  26803. })(_Primitive);
  26804. Primitives.TorusKnot = TorusKnot;
  26805. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26806. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26807. })(BABYLON || (BABYLON = {}));
  26808. var BABYLON;
  26809. (function (BABYLON) {
  26810. var GroundMesh = (function (_super) {
  26811. __extends(GroundMesh, _super);
  26812. function GroundMesh(name, scene) {
  26813. _super.call(this, name, scene);
  26814. this.generateOctree = false;
  26815. this._worldInverse = new BABYLON.Matrix();
  26816. }
  26817. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26818. get: function () {
  26819. return this._subdivisions;
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26825. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26826. this._subdivisions = chunksCount;
  26827. this.subdivide(this._subdivisions);
  26828. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26829. };
  26830. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26831. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26832. this.getWorldMatrix().invertToRef(this._worldInverse);
  26833. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26834. var pickInfo = this.intersects(ray);
  26835. if (pickInfo.hit) {
  26836. return pickInfo.pickedPoint.y;
  26837. }
  26838. return 0;
  26839. };
  26840. return GroundMesh;
  26841. })(BABYLON.Mesh);
  26842. BABYLON.GroundMesh = GroundMesh;
  26843. })(BABYLON || (BABYLON = {}));
  26844. var BABYLON;
  26845. (function (BABYLON) {
  26846. var LinesMesh = (function (_super) {
  26847. __extends(LinesMesh, _super);
  26848. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26849. if (parent === void 0) { parent = null; }
  26850. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26851. this.color = new BABYLON.Color3(1, 1, 1);
  26852. this.alpha = 1;
  26853. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26854. attributes: ["position"],
  26855. uniforms: ["worldViewProjection", "color"],
  26856. needAlphaBlending: true
  26857. });
  26858. }
  26859. Object.defineProperty(LinesMesh.prototype, "material", {
  26860. get: function () {
  26861. return this._colorShader;
  26862. },
  26863. enumerable: true,
  26864. configurable: true
  26865. });
  26866. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26867. get: function () {
  26868. return false;
  26869. },
  26870. enumerable: true,
  26871. configurable: true
  26872. });
  26873. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26874. get: function () {
  26875. return false;
  26876. },
  26877. enumerable: true,
  26878. configurable: true
  26879. });
  26880. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26881. var engine = this.getScene().getEngine();
  26882. var indexToBind = this._geometry.getIndexBuffer();
  26883. // VBOs
  26884. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26885. // Color
  26886. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26887. };
  26888. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26889. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26890. return;
  26891. }
  26892. var engine = this.getScene().getEngine();
  26893. // Draw order
  26894. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26895. };
  26896. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26897. return null;
  26898. };
  26899. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26900. this._colorShader.dispose();
  26901. _super.prototype.dispose.call(this, doNotRecurse);
  26902. };
  26903. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26904. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26905. };
  26906. return LinesMesh;
  26907. })(BABYLON.Mesh);
  26908. BABYLON.LinesMesh = LinesMesh;
  26909. })(BABYLON || (BABYLON = {}));
  26910. var BABYLON;
  26911. (function (BABYLON) {
  26912. var DebugLayer = (function () {
  26913. function DebugLayer(scene) {
  26914. var _this = this;
  26915. this._transformationMatrix = BABYLON.Matrix.Identity();
  26916. this._enabled = false;
  26917. this._labelsEnabled = false;
  26918. this._displayStatistics = true;
  26919. this._displayTree = false;
  26920. this._displayLogs = false;
  26921. this._identityMatrix = BABYLON.Matrix.Identity();
  26922. this.axisRatio = 0.02;
  26923. this.accentColor = "orange";
  26924. this._scene = scene;
  26925. this._syncPositions = function () {
  26926. var engine = _this._scene.getEngine();
  26927. var canvasRect = engine.getRenderingCanvasClientRect();
  26928. if (_this._showUI) {
  26929. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26930. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26931. _this._statsDiv.style.width = "400px";
  26932. _this._statsDiv.style.height = "auto";
  26933. _this._statsSubsetDiv.style.maxHeight = "240px";
  26934. _this._optionsDiv.style.left = "0px";
  26935. _this._optionsDiv.style.top = "10px";
  26936. _this._optionsDiv.style.width = "200px";
  26937. _this._optionsDiv.style.height = "auto";
  26938. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26939. _this._logDiv.style.left = "0px";
  26940. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26941. _this._logDiv.style.width = "600px";
  26942. _this._logDiv.style.height = "160px";
  26943. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26944. _this._treeDiv.style.top = "10px";
  26945. _this._treeDiv.style.width = "300px";
  26946. _this._treeDiv.style.height = "auto";
  26947. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26948. }
  26949. _this._globalDiv.style.left = canvasRect.left + "px";
  26950. _this._globalDiv.style.top = canvasRect.top + "px";
  26951. _this._drawingCanvas.style.left = "0px";
  26952. _this._drawingCanvas.style.top = "0px";
  26953. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26954. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26955. var devicePixelRatio = window.devicePixelRatio || 1;
  26956. var context = _this._drawingContext;
  26957. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26958. context.mozBackingStorePixelRatio ||
  26959. context.msBackingStorePixelRatio ||
  26960. context.oBackingStorePixelRatio ||
  26961. context.backingStorePixelRatio || 1;
  26962. _this._ratio = devicePixelRatio / backingStoreRatio;
  26963. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26964. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26965. };
  26966. this._onCanvasClick = function (evt) {
  26967. _this._clickPosition = {
  26968. x: evt.clientX * _this._ratio,
  26969. y: evt.clientY * _this._ratio
  26970. };
  26971. };
  26972. this._syncUI = function () {
  26973. if (_this._showUI) {
  26974. if (_this._displayStatistics) {
  26975. _this._displayStats();
  26976. _this._statsDiv.style.display = "";
  26977. }
  26978. else {
  26979. _this._statsDiv.style.display = "none";
  26980. }
  26981. if (_this._displayLogs) {
  26982. _this._logDiv.style.display = "";
  26983. }
  26984. else {
  26985. _this._logDiv.style.display = "none";
  26986. }
  26987. if (_this._displayTree) {
  26988. _this._treeDiv.style.display = "";
  26989. if (_this._needToRefreshMeshesTree) {
  26990. _this._needToRefreshMeshesTree = false;
  26991. _this._refreshMeshesTreeContent();
  26992. }
  26993. }
  26994. else {
  26995. _this._treeDiv.style.display = "none";
  26996. }
  26997. }
  26998. };
  26999. this._syncData = function () {
  27000. if (_this._labelsEnabled || !_this._showUI) {
  27001. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27002. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27003. var engine = _this._scene.getEngine();
  27004. var viewport = _this._camera.viewport;
  27005. var globalViewport = viewport.toGlobal(engine);
  27006. // Meshes
  27007. var meshes = _this._camera.getActiveMeshes();
  27008. var index;
  27009. var projectedPosition;
  27010. for (index = 0; index < meshes.length; index++) {
  27011. var mesh = meshes.data[index];
  27012. var position = mesh.getBoundingInfo().boundingSphere.center;
  27013. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27014. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27015. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27016. }
  27017. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27018. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27019. }
  27020. }
  27021. // Cameras
  27022. var cameras = _this._scene.cameras;
  27023. for (index = 0; index < cameras.length; index++) {
  27024. var camera = cameras[index];
  27025. if (camera === _this._camera) {
  27026. continue;
  27027. }
  27028. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27029. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27030. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27031. _this._camera.detachControl(engine.getRenderingCanvas());
  27032. _this._camera = camera;
  27033. _this._camera.attachControl(engine.getRenderingCanvas());
  27034. }, function () { return "purple"; });
  27035. }
  27036. }
  27037. // Lights
  27038. var lights = _this._scene.lights;
  27039. for (index = 0; index < lights.length; index++) {
  27040. var light = lights[index];
  27041. if (light.position) {
  27042. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27043. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27044. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27045. light.setEnabled(!light.isEnabled());
  27046. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27047. }
  27048. }
  27049. }
  27050. }
  27051. _this._clickPosition = undefined;
  27052. };
  27053. }
  27054. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27055. while (this._treeSubsetDiv.hasChildNodes()) {
  27056. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27057. }
  27058. // Add meshes
  27059. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27060. sortedArray.sort(function (a, b) {
  27061. if (a.name === b.name) {
  27062. return 0;
  27063. }
  27064. return (a.name > b.name) ? 1 : -1;
  27065. });
  27066. for (var index = 0; index < sortedArray.length; index++) {
  27067. var mesh = sortedArray[index];
  27068. if (!mesh.isEnabled()) {
  27069. continue;
  27070. }
  27071. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27072. m.isVisible = element.checked;
  27073. }, mesh);
  27074. }
  27075. };
  27076. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27077. this._drawingContext.beginPath();
  27078. this._drawingContext.moveTo(zero.x, zero.y);
  27079. this._drawingContext.lineTo(unit.x, unit.y);
  27080. this._drawingContext.strokeStyle = color;
  27081. this._drawingContext.lineWidth = 4;
  27082. this._drawingContext.stroke();
  27083. this._drawingContext.font = "normal 14px Segoe UI";
  27084. this._drawingContext.fillStyle = color;
  27085. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27086. };
  27087. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27088. var position = mesh.getBoundingInfo().boundingSphere.center;
  27089. var worldMatrix = mesh.getWorldMatrix();
  27090. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27091. var unit = (unprojectedVector.subtract(position)).length();
  27092. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27093. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27094. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27095. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27096. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27097. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27098. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27099. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27100. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27101. };
  27102. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27103. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27104. this._drawingContext.font = "normal 12px Segoe UI";
  27105. var textMetrics = this._drawingContext.measureText(text);
  27106. var centerX = projectedPosition.x - textMetrics.width / 2;
  27107. var centerY = projectedPosition.y;
  27108. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27109. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27110. onClick();
  27111. }
  27112. this._drawingContext.beginPath();
  27113. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27114. this._drawingContext.fillStyle = getFillStyle();
  27115. this._drawingContext.globalAlpha = 0.5;
  27116. this._drawingContext.fill();
  27117. this._drawingContext.globalAlpha = 1.0;
  27118. this._drawingContext.strokeStyle = '#FFFFFF';
  27119. this._drawingContext.lineWidth = 1;
  27120. this._drawingContext.stroke();
  27121. this._drawingContext.fillStyle = "#FFFFFF";
  27122. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27123. this._drawingContext.beginPath();
  27124. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27125. this._drawingContext.fill();
  27126. }
  27127. };
  27128. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27129. if (!this._clickPosition) {
  27130. return false;
  27131. }
  27132. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27133. return false;
  27134. }
  27135. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27136. return false;
  27137. }
  27138. return true;
  27139. };
  27140. DebugLayer.prototype.isVisible = function () {
  27141. return this._enabled;
  27142. };
  27143. DebugLayer.prototype.hide = function () {
  27144. if (!this._enabled) {
  27145. return;
  27146. }
  27147. this._enabled = false;
  27148. var engine = this._scene.getEngine();
  27149. this._scene.unregisterBeforeRender(this._syncData);
  27150. this._scene.unregisterAfterRender(this._syncUI);
  27151. this._rootElement.removeChild(this._globalDiv);
  27152. this._scene.forceShowBoundingBoxes = false;
  27153. this._scene.forceWireframe = false;
  27154. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27155. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27156. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27157. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27158. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27159. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27160. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27161. BABYLON.StandardMaterial.LightmapEnabled = true;
  27162. this._scene.shadowsEnabled = true;
  27163. this._scene.particlesEnabled = true;
  27164. this._scene.postProcessesEnabled = true;
  27165. this._scene.collisionsEnabled = true;
  27166. this._scene.lightsEnabled = true;
  27167. this._scene.texturesEnabled = true;
  27168. this._scene.lensFlaresEnabled = true;
  27169. this._scene.proceduralTexturesEnabled = true;
  27170. this._scene.renderTargetsEnabled = true;
  27171. this._scene.probesEnabled = true;
  27172. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27173. };
  27174. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27175. if (showUI === void 0) { showUI = true; }
  27176. if (camera === void 0) { camera = null; }
  27177. if (rootElement === void 0) { rootElement = null; }
  27178. if (this._enabled) {
  27179. return;
  27180. }
  27181. this._enabled = true;
  27182. if (camera) {
  27183. this._camera = camera;
  27184. }
  27185. else {
  27186. this._camera = this._scene.activeCamera;
  27187. }
  27188. this._showUI = showUI;
  27189. var engine = this._scene.getEngine();
  27190. this._globalDiv = document.createElement("div");
  27191. this._rootElement = rootElement || document.body;
  27192. this._rootElement.appendChild(this._globalDiv);
  27193. this._generateDOMelements();
  27194. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27195. this._syncPositions();
  27196. this._scene.registerBeforeRender(this._syncData);
  27197. this._scene.registerAfterRender(this._syncUI);
  27198. };
  27199. DebugLayer.prototype._clearLabels = function () {
  27200. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27201. for (var index = 0; index < this._scene.meshes.length; index++) {
  27202. var mesh = this._scene.meshes[index];
  27203. mesh.renderOverlay = false;
  27204. }
  27205. };
  27206. DebugLayer.prototype._generateheader = function (root, text) {
  27207. var header = document.createElement("div");
  27208. header.innerHTML = text + "&nbsp;";
  27209. header.style.textAlign = "right";
  27210. header.style.width = "100%";
  27211. header.style.color = "white";
  27212. header.style.backgroundColor = "Black";
  27213. header.style.padding = "5px 5px 4px 0px";
  27214. header.style.marginLeft = "-5px";
  27215. header.style.fontWeight = "bold";
  27216. root.appendChild(header);
  27217. };
  27218. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27219. var label = document.createElement("label");
  27220. label.innerHTML = title;
  27221. label.style.color = color;
  27222. root.appendChild(label);
  27223. root.appendChild(document.createElement("br"));
  27224. };
  27225. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27226. if (tag === void 0) { tag = null; }
  27227. var label = document.createElement("label");
  27228. var boundingBoxesCheckbox = document.createElement("input");
  27229. boundingBoxesCheckbox.type = "checkbox";
  27230. boundingBoxesCheckbox.checked = initialState;
  27231. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27232. task(evt.target, tag);
  27233. });
  27234. label.appendChild(boundingBoxesCheckbox);
  27235. var container = document.createElement("span");
  27236. var leftPart = document.createElement("span");
  27237. var rightPart = document.createElement("span");
  27238. rightPart.style.cssFloat = "right";
  27239. leftPart.innerHTML = leftTitle;
  27240. rightPart.innerHTML = rightTitle;
  27241. rightPart.style.fontSize = "12px";
  27242. rightPart.style.maxWidth = "200px";
  27243. container.appendChild(leftPart);
  27244. container.appendChild(rightPart);
  27245. label.appendChild(container);
  27246. root.appendChild(label);
  27247. root.appendChild(document.createElement("br"));
  27248. };
  27249. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27250. if (tag === void 0) { tag = null; }
  27251. var label = document.createElement("label");
  27252. var checkBox = document.createElement("input");
  27253. checkBox.type = "checkbox";
  27254. checkBox.checked = initialState;
  27255. checkBox.addEventListener("change", function (evt) {
  27256. task(evt.target, tag);
  27257. });
  27258. label.appendChild(checkBox);
  27259. label.appendChild(document.createTextNode(title));
  27260. root.appendChild(label);
  27261. root.appendChild(document.createElement("br"));
  27262. };
  27263. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27264. if (tag === void 0) { tag = null; }
  27265. var button = document.createElement("button");
  27266. button.innerHTML = title;
  27267. button.style.height = "24px";
  27268. button.style.width = "150px";
  27269. button.style.marginBottom = "5px";
  27270. button.style.color = "#444444";
  27271. button.style.border = "1px solid white";
  27272. button.className = "debugLayerButton";
  27273. button.addEventListener("click", function (evt) {
  27274. task(evt.target, tag);
  27275. });
  27276. root.appendChild(button);
  27277. root.appendChild(document.createElement("br"));
  27278. };
  27279. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27280. if (tag === void 0) { tag = null; }
  27281. var label = document.createElement("label");
  27282. var boundingBoxesRadio = document.createElement("input");
  27283. boundingBoxesRadio.type = "radio";
  27284. boundingBoxesRadio.name = name;
  27285. boundingBoxesRadio.checked = initialState;
  27286. boundingBoxesRadio.addEventListener("change", function (evt) {
  27287. task(evt.target, tag);
  27288. });
  27289. label.appendChild(boundingBoxesRadio);
  27290. label.appendChild(document.createTextNode(title));
  27291. root.appendChild(label);
  27292. root.appendChild(document.createElement("br"));
  27293. };
  27294. DebugLayer.prototype._generateDOMelements = function () {
  27295. var _this = this;
  27296. this._globalDiv.id = "DebugLayer";
  27297. this._globalDiv.style.position = "absolute";
  27298. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27299. this._globalDiv.style.fontSize = "14px";
  27300. this._globalDiv.style.color = "white";
  27301. // Drawing canvas
  27302. this._drawingCanvas = document.createElement("canvas");
  27303. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27304. this._drawingCanvas.style.position = "absolute";
  27305. this._drawingCanvas.style.pointerEvents = "none";
  27306. this._drawingCanvas.style.backgroundColor = "transparent";
  27307. this._drawingContext = this._drawingCanvas.getContext("2d");
  27308. this._globalDiv.appendChild(this._drawingCanvas);
  27309. if (this._showUI) {
  27310. var background = "rgba(128, 128, 128, 0.4)";
  27311. var border = "rgb(180, 180, 180) solid 1px";
  27312. // Stats
  27313. this._statsDiv = document.createElement("div");
  27314. this._statsDiv.id = "DebugLayerStats";
  27315. this._statsDiv.style.border = border;
  27316. this._statsDiv.style.position = "absolute";
  27317. this._statsDiv.style.background = background;
  27318. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27319. this._generateheader(this._statsDiv, "STATISTICS");
  27320. this._statsSubsetDiv = document.createElement("div");
  27321. this._statsSubsetDiv.style.paddingTop = "5px";
  27322. this._statsSubsetDiv.style.paddingBottom = "5px";
  27323. this._statsSubsetDiv.style.overflowY = "auto";
  27324. this._statsDiv.appendChild(this._statsSubsetDiv);
  27325. // Tree
  27326. this._treeDiv = document.createElement("div");
  27327. this._treeDiv.id = "DebugLayerTree";
  27328. this._treeDiv.style.border = border;
  27329. this._treeDiv.style.position = "absolute";
  27330. this._treeDiv.style.background = background;
  27331. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27332. this._treeDiv.style.display = "none";
  27333. this._generateheader(this._treeDiv, "MESHES TREE");
  27334. this._treeSubsetDiv = document.createElement("div");
  27335. this._treeSubsetDiv.style.paddingTop = "5px";
  27336. this._treeSubsetDiv.style.paddingRight = "5px";
  27337. this._treeSubsetDiv.style.overflowY = "auto";
  27338. this._treeSubsetDiv.style.maxHeight = "300px";
  27339. this._treeDiv.appendChild(this._treeSubsetDiv);
  27340. this._needToRefreshMeshesTree = true;
  27341. // Logs
  27342. this._logDiv = document.createElement("div");
  27343. this._logDiv.style.border = border;
  27344. this._logDiv.id = "DebugLayerLogs";
  27345. this._logDiv.style.position = "absolute";
  27346. this._logDiv.style.background = background;
  27347. this._logDiv.style.padding = "0px 0px 0px 5px";
  27348. this._logDiv.style.display = "none";
  27349. this._generateheader(this._logDiv, "LOGS");
  27350. this._logSubsetDiv = document.createElement("div");
  27351. this._logSubsetDiv.style.height = "127px";
  27352. this._logSubsetDiv.style.paddingTop = "5px";
  27353. this._logSubsetDiv.style.overflowY = "auto";
  27354. this._logSubsetDiv.style.fontSize = "12px";
  27355. this._logSubsetDiv.style.fontFamily = "consolas";
  27356. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27357. this._logDiv.appendChild(this._logSubsetDiv);
  27358. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27359. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27360. };
  27361. // Options
  27362. this._optionsDiv = document.createElement("div");
  27363. this._optionsDiv.id = "DebugLayerOptions";
  27364. this._optionsDiv.style.border = border;
  27365. this._optionsDiv.style.position = "absolute";
  27366. this._optionsDiv.style.background = background;
  27367. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27368. this._optionsDiv.style.overflowY = "auto";
  27369. this._generateheader(this._optionsDiv, "OPTIONS");
  27370. this._optionsSubsetDiv = document.createElement("div");
  27371. this._optionsSubsetDiv.style.paddingTop = "5px";
  27372. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27373. this._optionsSubsetDiv.style.overflowY = "auto";
  27374. this._optionsSubsetDiv.style.maxHeight = "200px";
  27375. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27376. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27377. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27378. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27379. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27380. _this._displayTree = element.checked;
  27381. _this._needToRefreshMeshesTree = true;
  27382. });
  27383. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27384. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27385. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27386. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27387. _this._labelsEnabled = element.checked;
  27388. if (!_this._labelsEnabled) {
  27389. _this._clearLabels();
  27390. }
  27391. });
  27392. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27393. if (element.checked) {
  27394. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27395. }
  27396. else {
  27397. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27398. }
  27399. });
  27400. ;
  27401. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27402. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27403. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27404. if (element.checked) {
  27405. _this._scene.forceWireframe = false;
  27406. _this._scene.forcePointsCloud = false;
  27407. }
  27408. });
  27409. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27410. if (element.checked) {
  27411. _this._scene.forceWireframe = true;
  27412. _this._scene.forcePointsCloud = false;
  27413. }
  27414. });
  27415. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27416. if (element.checked) {
  27417. _this._scene.forceWireframe = false;
  27418. _this._scene.forcePointsCloud = true;
  27419. }
  27420. });
  27421. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27422. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27423. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27424. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27425. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27426. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27427. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27428. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27429. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27430. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27431. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27432. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27433. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27434. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27435. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27436. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27437. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27438. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27439. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27440. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27441. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27442. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27443. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27444. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27445. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27446. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27447. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27448. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27449. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27450. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27451. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27452. if (element.checked) {
  27453. _this._scene.headphone = true;
  27454. }
  27455. });
  27456. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27457. if (element.checked) {
  27458. _this._scene.headphone = false;
  27459. }
  27460. });
  27461. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27462. _this._scene.audioEnabled = !element.checked;
  27463. });
  27464. }
  27465. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27466. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27467. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27468. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27469. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27470. if (_this._camera) {
  27471. console.log(_this._camera);
  27472. }
  27473. else {
  27474. console.warn("No camera defined, or debug layer created before camera creation!");
  27475. }
  27476. });
  27477. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27478. this._globalDiv.appendChild(this._statsDiv);
  27479. this._globalDiv.appendChild(this._logDiv);
  27480. this._globalDiv.appendChild(this._optionsDiv);
  27481. this._globalDiv.appendChild(this._treeDiv);
  27482. }
  27483. };
  27484. DebugLayer.prototype._displayStats = function () {
  27485. var scene = this._scene;
  27486. var engine = scene.getEngine();
  27487. var glInfo = engine.getGlInfo();
  27488. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27489. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27490. + "<b>Count</b><br>"
  27491. + "Total meshes: " + scene.meshes.length + "<br>"
  27492. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27493. + "Total materials: " + scene.materials.length + "<br>"
  27494. + "Total textures: " + scene.textures.length + "<br>"
  27495. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27496. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27497. + "Active bones: " + scene.getActiveBones() + "<br>"
  27498. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27499. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27500. + "<b>Duration</b><br>"
  27501. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27502. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27503. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27504. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27505. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27506. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27507. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27508. + "</div>"
  27509. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27510. + "<b>Extensions</b><br>"
  27511. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27512. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27513. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27514. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27515. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27516. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27517. + "<b>Caps.</b><br>"
  27518. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27519. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27520. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27521. + "</div><br>"
  27522. + "<b>Info</b><br>"
  27523. + glInfo.version + "<br>"
  27524. + glInfo.renderer + "<br>";
  27525. if (this.customStatsFunction) {
  27526. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27527. }
  27528. };
  27529. return DebugLayer;
  27530. })();
  27531. BABYLON.DebugLayer = DebugLayer;
  27532. })(BABYLON || (BABYLON = {}));
  27533. var BABYLON;
  27534. (function (BABYLON) {
  27535. var DefaultLoadingScreen = (function () {
  27536. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27537. var _this = this;
  27538. if (_loadingText === void 0) { _loadingText = ""; }
  27539. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27540. this._renderingCanvas = _renderingCanvas;
  27541. this._loadingText = _loadingText;
  27542. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27543. // Resize
  27544. this._resizeLoadingUI = function () {
  27545. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27546. _this._loadingDiv.style.position = "absolute";
  27547. _this._loadingDiv.style.left = canvasRect.left + "px";
  27548. _this._loadingDiv.style.top = canvasRect.top + "px";
  27549. _this._loadingDiv.style.width = canvasRect.width + "px";
  27550. _this._loadingDiv.style.height = canvasRect.height + "px";
  27551. };
  27552. }
  27553. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27554. var _this = this;
  27555. this._loadingDiv = document.createElement("div");
  27556. this._loadingDiv.id = "babylonjsLoadingDiv";
  27557. this._loadingDiv.style.opacity = "0";
  27558. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27559. // Loading text
  27560. this._loadingTextDiv = document.createElement("div");
  27561. this._loadingTextDiv.style.position = "absolute";
  27562. this._loadingTextDiv.style.left = "0";
  27563. this._loadingTextDiv.style.top = "50%";
  27564. this._loadingTextDiv.style.marginTop = "80px";
  27565. this._loadingTextDiv.style.width = "100%";
  27566. this._loadingTextDiv.style.height = "20px";
  27567. this._loadingTextDiv.style.fontFamily = "Arial";
  27568. this._loadingTextDiv.style.fontSize = "14px";
  27569. this._loadingTextDiv.style.color = "white";
  27570. this._loadingTextDiv.style.textAlign = "center";
  27571. this._loadingTextDiv.innerHTML = "Loading";
  27572. this._loadingDiv.appendChild(this._loadingTextDiv);
  27573. //set the predefined text
  27574. this._loadingTextDiv.innerHTML = this._loadingText;
  27575. // Loading img
  27576. var imgBack = new Image();
  27577. 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==";
  27578. imgBack.style.position = "absolute";
  27579. imgBack.style.left = "50%";
  27580. imgBack.style.top = "50%";
  27581. imgBack.style.marginLeft = "-50px";
  27582. imgBack.style.marginTop = "-50px";
  27583. imgBack.style.transition = "transform 1.0s ease";
  27584. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27585. var deg = 360;
  27586. var onTransitionEnd = function () {
  27587. deg += 360;
  27588. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27589. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27590. };
  27591. imgBack.addEventListener("transitionend", onTransitionEnd);
  27592. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27593. this._loadingDiv.appendChild(imgBack);
  27594. // front image
  27595. var imgFront = new Image();
  27596. 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=";
  27597. imgFront.style.position = "absolute";
  27598. imgFront.style.left = "50%";
  27599. imgFront.style.top = "50%";
  27600. imgFront.style.marginLeft = "-50px";
  27601. imgFront.style.marginTop = "-50px";
  27602. this._loadingDiv.appendChild(imgFront);
  27603. this._resizeLoadingUI();
  27604. window.addEventListener("resize", this._resizeLoadingUI);
  27605. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27606. document.body.appendChild(this._loadingDiv);
  27607. setTimeout(function () {
  27608. _this._loadingDiv.style.opacity = "1";
  27609. imgBack.style.transform = "rotateZ(360deg)";
  27610. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27611. }, 0);
  27612. };
  27613. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27614. var _this = this;
  27615. if (!this._loadingDiv) {
  27616. return;
  27617. }
  27618. var onTransitionEnd = function () {
  27619. if (!_this._loadingDiv) {
  27620. return;
  27621. }
  27622. document.body.removeChild(_this._loadingDiv);
  27623. window.removeEventListener("resize", _this._resizeLoadingUI);
  27624. _this._loadingDiv = null;
  27625. };
  27626. this._loadingDiv.style.opacity = "0";
  27627. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27628. };
  27629. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27630. set: function (text) {
  27631. this._loadingText = text;
  27632. if (this._loadingTextDiv) {
  27633. this._loadingTextDiv.innerHTML = this._loadingText;
  27634. }
  27635. },
  27636. enumerable: true,
  27637. configurable: true
  27638. });
  27639. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27640. get: function () {
  27641. return this._loadingDivBackgroundColor;
  27642. },
  27643. set: function (color) {
  27644. this._loadingDivBackgroundColor = color;
  27645. if (!this._loadingDiv) {
  27646. return;
  27647. }
  27648. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27649. },
  27650. enumerable: true,
  27651. configurable: true
  27652. });
  27653. return DefaultLoadingScreen;
  27654. })();
  27655. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27656. })(BABYLON || (BABYLON = {}));
  27657. var BABYLON;
  27658. (function (BABYLON) {
  27659. var SIMDVector3 = (function () {
  27660. function SIMDVector3() {
  27661. }
  27662. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27663. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27664. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27665. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27666. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27667. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27668. 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));
  27669. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27670. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27671. };
  27672. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27673. var v0 = SIMD.float32x4.splat(x);
  27674. var v1 = SIMD.float32x4.splat(y);
  27675. var v2 = SIMD.float32x4.splat(z);
  27676. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27677. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27678. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27679. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27680. 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));
  27681. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27682. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27683. };
  27684. return SIMDVector3;
  27685. })();
  27686. BABYLON.SIMDVector3 = SIMDVector3;
  27687. var SIMDMatrix = (function () {
  27688. function SIMDMatrix() {
  27689. }
  27690. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27691. if (offset === void 0) { offset = 0; }
  27692. var tm = this.m;
  27693. var om = other.m;
  27694. var om0 = SIMD.float32x4.load(om, 0);
  27695. var om1 = SIMD.float32x4.load(om, 4);
  27696. var om2 = SIMD.float32x4.load(om, 8);
  27697. var om3 = SIMD.float32x4.load(om, 12);
  27698. var tm0 = SIMD.float32x4.load(tm, 0);
  27699. 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)))));
  27700. var tm1 = SIMD.float32x4.load(tm, 4);
  27701. 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)))));
  27702. var tm2 = SIMD.float32x4.load(tm, 8);
  27703. 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)))));
  27704. var tm3 = SIMD.float32x4.load(tm, 12);
  27705. 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)))));
  27706. };
  27707. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27708. var src = this.m;
  27709. var dest = other.m;
  27710. var row0, row1, row2, row3;
  27711. var tmp1;
  27712. var minor0, minor1, minor2, minor3;
  27713. var det;
  27714. // Load the 4 rows
  27715. var src0 = SIMD.float32x4.load(src, 0);
  27716. var src1 = SIMD.float32x4.load(src, 4);
  27717. var src2 = SIMD.float32x4.load(src, 8);
  27718. var src3 = SIMD.float32x4.load(src, 12);
  27719. // Transpose the source matrix. Sort of. Not a true transpose operation
  27720. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27721. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27722. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27723. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27724. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27725. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27726. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27727. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27728. // This is a true transposition, but it will lead to an incorrect result
  27729. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27730. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27731. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27732. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27733. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27734. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27735. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27736. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27737. // ----
  27738. tmp1 = SIMD.float32x4.mul(row2, row3);
  27739. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27740. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27741. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27742. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27743. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27744. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27745. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27746. // ----
  27747. tmp1 = SIMD.float32x4.mul(row1, row2);
  27748. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27749. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27750. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27751. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27752. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27753. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27754. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27755. // ----
  27756. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27757. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27758. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27759. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27760. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27761. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27762. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27763. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27764. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27765. // ----
  27766. tmp1 = SIMD.float32x4.mul(row0, row1);
  27767. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27768. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27769. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27770. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27771. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27772. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27773. // ----
  27774. tmp1 = SIMD.float32x4.mul(row0, row3);
  27775. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27776. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27777. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27778. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27779. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27780. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27781. // ----
  27782. tmp1 = SIMD.float32x4.mul(row0, row2);
  27783. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27784. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27785. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27786. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27787. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27788. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27789. // Compute determinant
  27790. det = SIMD.float32x4.mul(row0, minor0);
  27791. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27792. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27793. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27794. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27795. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27796. // These shuffles aren't necessary if the faulty transposition is done
  27797. // up at the top of this function.
  27798. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27799. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27800. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27801. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27802. // Compute final values by multiplying with 1/det
  27803. minor0 = SIMD.float32x4.mul(det, minor0);
  27804. minor1 = SIMD.float32x4.mul(det, minor1);
  27805. minor2 = SIMD.float32x4.mul(det, minor2);
  27806. minor3 = SIMD.float32x4.mul(det, minor3);
  27807. SIMD.float32x4.store(dest, 0, minor0);
  27808. SIMD.float32x4.store(dest, 4, minor1);
  27809. SIMD.float32x4.store(dest, 8, minor2);
  27810. SIMD.float32x4.store(dest, 12, minor3);
  27811. return this;
  27812. };
  27813. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27814. var out = result.m;
  27815. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27816. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27817. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27818. // cc.kmVec3Subtract(f, pCenter, pEye);
  27819. var f = SIMD.float32x4.sub(center, eye);
  27820. // cc.kmVec3Normalize(f, f);
  27821. var tmp = SIMD.float32x4.mul(f, f);
  27822. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27823. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27824. // cc.kmVec3Assign(up, pUp);
  27825. // cc.kmVec3Normalize(up, up);
  27826. tmp = SIMD.float32x4.mul(up, up);
  27827. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27828. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27829. // cc.kmVec3Cross(s, f, up);
  27830. 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)));
  27831. // cc.kmVec3Normalize(s, s);
  27832. tmp = SIMD.float32x4.mul(s, s);
  27833. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27834. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27835. // cc.kmVec3Cross(u, s, f);
  27836. 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)));
  27837. // cc.kmVec3Normalize(s, s);
  27838. tmp = SIMD.float32x4.mul(s, s);
  27839. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27840. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27841. var zero = SIMD.float32x4.splat(0.0);
  27842. s = SIMD.float32x4.neg(s);
  27843. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27844. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27845. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27846. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27847. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27848. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27849. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27850. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27851. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27852. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27853. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27854. var b3 = SIMD.float32x4.neg(eye);
  27855. b3 = SIMD.float32x4.withW(b3, 1.0);
  27856. 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)))));
  27857. 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)))));
  27858. 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)))));
  27859. 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)))));
  27860. };
  27861. return SIMDMatrix;
  27862. })();
  27863. BABYLON.SIMDMatrix = SIMDMatrix;
  27864. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27865. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27866. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27867. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27868. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27869. var SIMDHelper = (function () {
  27870. function SIMDHelper() {
  27871. }
  27872. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27873. get: function () {
  27874. return SIMDHelper._isEnabled;
  27875. },
  27876. enumerable: true,
  27877. configurable: true
  27878. });
  27879. SIMDHelper.DisableSIMD = function () {
  27880. // Replace functions
  27881. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27882. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27883. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27884. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27885. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27886. SIMDHelper._isEnabled = false;
  27887. };
  27888. SIMDHelper.EnableSIMD = function () {
  27889. if (window.SIMD === undefined) {
  27890. return;
  27891. }
  27892. // Replace functions
  27893. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27894. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27895. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27896. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27897. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27898. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27899. get: function () { return this._data[0]; },
  27900. set: function (value) {
  27901. if (!this._data) {
  27902. this._data = new Float32Array(3);
  27903. }
  27904. this._data[0] = value;
  27905. }
  27906. });
  27907. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27908. get: function () { return this._data[1]; },
  27909. set: function (value) {
  27910. this._data[1] = value;
  27911. }
  27912. });
  27913. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27914. get: function () { return this._data[2]; },
  27915. set: function (value) {
  27916. this._data[2] = value;
  27917. }
  27918. });
  27919. SIMDHelper._isEnabled = true;
  27920. };
  27921. SIMDHelper._isEnabled = false;
  27922. return SIMDHelper;
  27923. })();
  27924. BABYLON.SIMDHelper = SIMDHelper;
  27925. })(BABYLON || (BABYLON = {}));
  27926. var BABYLON;
  27927. (function (BABYLON) {
  27928. var ShaderMaterial = (function (_super) {
  27929. __extends(ShaderMaterial, _super);
  27930. function ShaderMaterial(name, scene, shaderPath, options) {
  27931. _super.call(this, name, scene);
  27932. this._textures = new Array();
  27933. this._floats = new Array();
  27934. this._floatsArrays = {};
  27935. this._colors3 = new Array();
  27936. this._colors4 = new Array();
  27937. this._vectors2 = new Array();
  27938. this._vectors3 = new Array();
  27939. this._vectors4 = new Array();
  27940. this._matrices = new Array();
  27941. this._matrices3x3 = new Array();
  27942. this._matrices2x2 = new Array();
  27943. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27944. this._shaderPath = shaderPath;
  27945. options.needAlphaBlending = options.needAlphaBlending || false;
  27946. options.needAlphaTesting = options.needAlphaTesting || false;
  27947. options.attributes = options.attributes || ["position", "normal", "uv"];
  27948. options.uniforms = options.uniforms || ["worldViewProjection"];
  27949. options.samplers = options.samplers || [];
  27950. options.defines = options.defines || [];
  27951. this._options = options;
  27952. }
  27953. ShaderMaterial.prototype.needAlphaBlending = function () {
  27954. return this._options.needAlphaBlending;
  27955. };
  27956. ShaderMaterial.prototype.needAlphaTesting = function () {
  27957. return this._options.needAlphaTesting;
  27958. };
  27959. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27960. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27961. this._options.uniforms.push(uniformName);
  27962. }
  27963. };
  27964. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27965. if (this._options.samplers.indexOf(name) === -1) {
  27966. this._options.samplers.push(name);
  27967. }
  27968. this._textures[name] = texture;
  27969. return this;
  27970. };
  27971. ShaderMaterial.prototype.setFloat = function (name, value) {
  27972. this._checkUniform(name);
  27973. this._floats[name] = value;
  27974. return this;
  27975. };
  27976. ShaderMaterial.prototype.setFloats = function (name, value) {
  27977. this._checkUniform(name);
  27978. this._floatsArrays[name] = value;
  27979. return this;
  27980. };
  27981. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27982. this._checkUniform(name);
  27983. this._colors3[name] = value;
  27984. return this;
  27985. };
  27986. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27987. this._checkUniform(name);
  27988. this._colors4[name] = value;
  27989. return this;
  27990. };
  27991. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27992. this._checkUniform(name);
  27993. this._vectors2[name] = value;
  27994. return this;
  27995. };
  27996. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27997. this._checkUniform(name);
  27998. this._vectors3[name] = value;
  27999. return this;
  28000. };
  28001. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28002. this._checkUniform(name);
  28003. this._vectors4[name] = value;
  28004. return this;
  28005. };
  28006. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28007. this._checkUniform(name);
  28008. this._matrices[name] = value;
  28009. return this;
  28010. };
  28011. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28012. this._checkUniform(name);
  28013. this._matrices3x3[name] = value;
  28014. return this;
  28015. };
  28016. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28017. this._checkUniform(name);
  28018. this._matrices2x2[name] = value;
  28019. return this;
  28020. };
  28021. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28022. var scene = this.getScene();
  28023. var engine = scene.getEngine();
  28024. if (!this.checkReadyOnEveryCall) {
  28025. if (this._renderId === scene.getRenderId()) {
  28026. return true;
  28027. }
  28028. }
  28029. // Instances
  28030. var defines = [];
  28031. var fallbacks = new BABYLON.EffectFallbacks();
  28032. if (useInstances) {
  28033. defines.push("#define INSTANCES");
  28034. }
  28035. for (var index = 0; index < this._options.defines.length; index++) {
  28036. defines.push(this._options.defines[index]);
  28037. }
  28038. // Bones
  28039. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28040. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28041. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28042. fallbacks.addCPUSkinningFallback(0, mesh);
  28043. }
  28044. // Alpha test
  28045. if (engine.getAlphaTesting()) {
  28046. defines.push("#define ALPHATEST");
  28047. }
  28048. var previousEffect = this._effect;
  28049. var join = defines.join("\n");
  28050. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28051. if (!this._effect.isReady()) {
  28052. return false;
  28053. }
  28054. if (previousEffect !== this._effect) {
  28055. scene.resetCachedMaterial();
  28056. }
  28057. this._renderId = scene.getRenderId();
  28058. return true;
  28059. };
  28060. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28061. var scene = this.getScene();
  28062. if (this._options.uniforms.indexOf("world") !== -1) {
  28063. this._effect.setMatrix("world", world);
  28064. }
  28065. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28066. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28067. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28068. }
  28069. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28070. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28071. }
  28072. };
  28073. ShaderMaterial.prototype.bind = function (world, mesh) {
  28074. // Std values
  28075. this.bindOnlyWorldMatrix(world);
  28076. if (this.getScene().getCachedMaterial() !== this) {
  28077. if (this._options.uniforms.indexOf("view") !== -1) {
  28078. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28079. }
  28080. if (this._options.uniforms.indexOf("projection") !== -1) {
  28081. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28082. }
  28083. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28084. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28085. }
  28086. // Bones
  28087. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28088. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28089. }
  28090. // Texture
  28091. for (var name in this._textures) {
  28092. this._effect.setTexture(name, this._textures[name]);
  28093. }
  28094. // Float
  28095. for (name in this._floats) {
  28096. this._effect.setFloat(name, this._floats[name]);
  28097. }
  28098. // Float s
  28099. for (name in this._floatsArrays) {
  28100. this._effect.setArray(name, this._floatsArrays[name]);
  28101. }
  28102. // Color3
  28103. for (name in this._colors3) {
  28104. this._effect.setColor3(name, this._colors3[name]);
  28105. }
  28106. // Color4
  28107. for (name in this._colors4) {
  28108. var color = this._colors4[name];
  28109. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28110. }
  28111. // Vector2
  28112. for (name in this._vectors2) {
  28113. this._effect.setVector2(name, this._vectors2[name]);
  28114. }
  28115. // Vector3
  28116. for (name in this._vectors3) {
  28117. this._effect.setVector3(name, this._vectors3[name]);
  28118. }
  28119. // Vector4
  28120. for (name in this._vectors4) {
  28121. this._effect.setVector4(name, this._vectors4[name]);
  28122. }
  28123. // Matrix
  28124. for (name in this._matrices) {
  28125. this._effect.setMatrix(name, this._matrices[name]);
  28126. }
  28127. // Matrix 3x3
  28128. for (name in this._matrices3x3) {
  28129. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28130. }
  28131. // Matrix 2x2
  28132. for (name in this._matrices2x2) {
  28133. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28134. }
  28135. }
  28136. _super.prototype.bind.call(this, world, mesh);
  28137. };
  28138. ShaderMaterial.prototype.clone = function (name) {
  28139. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28140. return newShaderMaterial;
  28141. };
  28142. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28143. for (var name in this._textures) {
  28144. this._textures[name].dispose();
  28145. }
  28146. this._textures = [];
  28147. _super.prototype.dispose.call(this, forceDisposeEffect);
  28148. };
  28149. return ShaderMaterial;
  28150. })(BABYLON.Material);
  28151. BABYLON.ShaderMaterial = ShaderMaterial;
  28152. })(BABYLON || (BABYLON = {}));
  28153. var BABYLON;
  28154. (function (BABYLON) {
  28155. var Internals;
  28156. (function (Internals) {
  28157. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28158. // All values and structures referenced from:
  28159. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28160. var DDS_MAGIC = 0x20534444;
  28161. 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;
  28162. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28163. 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;
  28164. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28165. function FourCCToInt32(value) {
  28166. return value.charCodeAt(0) +
  28167. (value.charCodeAt(1) << 8) +
  28168. (value.charCodeAt(2) << 16) +
  28169. (value.charCodeAt(3) << 24);
  28170. }
  28171. function Int32ToFourCC(value) {
  28172. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28173. }
  28174. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28175. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28176. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28177. var headerLengthInt = 31; // The header length in 32 bit ints
  28178. // Offsets into the header array
  28179. var off_magic = 0;
  28180. var off_size = 1;
  28181. var off_flags = 2;
  28182. var off_height = 3;
  28183. var off_width = 4;
  28184. var off_mipmapCount = 7;
  28185. var off_pfFlags = 20;
  28186. var off_pfFourCC = 21;
  28187. var off_RGBbpp = 22;
  28188. var off_RMask = 23;
  28189. var off_GMask = 24;
  28190. var off_BMask = 25;
  28191. var off_AMask = 26;
  28192. var off_caps1 = 27;
  28193. var off_caps2 = 28;
  28194. ;
  28195. var DDSTools = (function () {
  28196. function DDSTools() {
  28197. }
  28198. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28199. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28200. var mipmapCount = 1;
  28201. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28202. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28203. }
  28204. return {
  28205. width: header[off_width],
  28206. height: header[off_height],
  28207. mipmapCount: mipmapCount,
  28208. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28209. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28210. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28211. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28212. };
  28213. };
  28214. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28215. var byteArray = new Uint8Array(dataLength);
  28216. var srcData = new Uint8Array(arrayBuffer);
  28217. var index = 0;
  28218. for (var y = height - 1; y >= 0; y--) {
  28219. for (var x = 0; x < width; x++) {
  28220. var srcPos = dataOffset + (x + y * width) * 4;
  28221. byteArray[index + 2] = srcData[srcPos];
  28222. byteArray[index + 1] = srcData[srcPos + 1];
  28223. byteArray[index] = srcData[srcPos + 2];
  28224. byteArray[index + 3] = srcData[srcPos + 3];
  28225. index += 4;
  28226. }
  28227. }
  28228. return byteArray;
  28229. };
  28230. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28231. var byteArray = new Uint8Array(dataLength);
  28232. var srcData = new Uint8Array(arrayBuffer);
  28233. var index = 0;
  28234. for (var y = height - 1; y >= 0; y--) {
  28235. for (var x = 0; x < width; x++) {
  28236. var srcPos = dataOffset + (x + y * width) * 3;
  28237. byteArray[index + 2] = srcData[srcPos];
  28238. byteArray[index + 1] = srcData[srcPos + 1];
  28239. byteArray[index] = srcData[srcPos + 2];
  28240. index += 3;
  28241. }
  28242. }
  28243. return byteArray;
  28244. };
  28245. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28246. var byteArray = new Uint8Array(dataLength);
  28247. var srcData = new Uint8Array(arrayBuffer);
  28248. var index = 0;
  28249. for (var y = height - 1; y >= 0; y--) {
  28250. for (var x = 0; x < width; x++) {
  28251. var srcPos = dataOffset + (x + y * width);
  28252. byteArray[index] = srcData[srcPos];
  28253. index++;
  28254. }
  28255. }
  28256. return byteArray;
  28257. };
  28258. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28259. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28260. if (header[off_magic] != DDS_MAGIC) {
  28261. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28262. return;
  28263. }
  28264. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28265. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28266. return;
  28267. }
  28268. if (info.isFourCC) {
  28269. fourCC = header[off_pfFourCC];
  28270. switch (fourCC) {
  28271. case FOURCC_DXT1:
  28272. blockBytes = 8;
  28273. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28274. break;
  28275. case FOURCC_DXT3:
  28276. blockBytes = 16;
  28277. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28278. break;
  28279. case FOURCC_DXT5:
  28280. blockBytes = 16;
  28281. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28282. break;
  28283. default:
  28284. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28285. return;
  28286. }
  28287. }
  28288. mipmapCount = 1;
  28289. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28290. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28291. }
  28292. var bpp = header[off_RGBbpp];
  28293. for (var face = 0; face < faces; face++) {
  28294. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28295. width = header[off_width];
  28296. height = header[off_height];
  28297. dataOffset = header[off_size] + 4;
  28298. for (i = 0; i < mipmapCount; ++i) {
  28299. if (info.isRGB) {
  28300. if (bpp === 24) {
  28301. dataLength = width * height * 3;
  28302. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28303. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28304. }
  28305. else {
  28306. dataLength = width * height * 4;
  28307. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28308. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28309. }
  28310. }
  28311. else if (info.isLuminance) {
  28312. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28313. var unpaddedRowSize = width;
  28314. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28315. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28316. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28317. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28318. }
  28319. else {
  28320. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28321. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28322. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28323. }
  28324. dataOffset += dataLength;
  28325. width *= 0.5;
  28326. height *= 0.5;
  28327. width = Math.max(1.0, width);
  28328. height = Math.max(1.0, height);
  28329. }
  28330. }
  28331. };
  28332. return DDSTools;
  28333. })();
  28334. Internals.DDSTools = DDSTools;
  28335. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28336. })(BABYLON || (BABYLON = {}));
  28337. var BABYLON;
  28338. (function (BABYLON) {
  28339. var CannonJSPlugin = (function () {
  28340. function CannonJSPlugin() {
  28341. this._registeredMeshes = [];
  28342. this._physicsMaterials = [];
  28343. this.name = "cannon";
  28344. this.updateBodyPosition = function (mesh) {
  28345. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28346. var registeredMesh = this._registeredMeshes[index];
  28347. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28348. var body = registeredMesh.body;
  28349. var center = mesh.getBoundingInfo().boundingBox.center;
  28350. body.position.set(center.x, center.y, center.z);
  28351. body.quaternion.copy(mesh.rotationQuaternion);
  28352. if (registeredMesh.deltaRotation) {
  28353. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28354. body.quaternion = body.quaternion.mult(tmpQ);
  28355. }
  28356. if (registeredMesh.heightmap) {
  28357. //calculate the correct body position:
  28358. var rotationQuaternion = mesh.rotationQuaternion;
  28359. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28360. mesh.computeWorldMatrix(true);
  28361. //get original center with no rotation
  28362. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28363. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28364. //rotation is back
  28365. mesh.rotationQuaternion = rotationQuaternion;
  28366. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28367. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28368. mesh.setPivotMatrix(p);
  28369. mesh.computeWorldMatrix(true);
  28370. //calculate the translation
  28371. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28372. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28373. //add it inverted to the delta
  28374. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28375. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28376. mesh.setPivotMatrix(oldPivot);
  28377. mesh.computeWorldMatrix(true);
  28378. }
  28379. return;
  28380. }
  28381. }
  28382. };
  28383. }
  28384. CannonJSPlugin.prototype.initialize = function (iterations) {
  28385. if (iterations === void 0) { iterations = 10; }
  28386. this._world = new CANNON.World();
  28387. this._world.broadphase = new CANNON.NaiveBroadphase();
  28388. this._world.solver.iterations = iterations;
  28389. };
  28390. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28391. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28392. };
  28393. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28394. var _this = this;
  28395. this._world.step(delta);
  28396. this._registeredMeshes.forEach(function (registeredMesh) {
  28397. // Body position
  28398. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28399. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28400. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28401. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28402. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28403. if (registeredMesh.deltaRotation) {
  28404. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28405. }
  28406. //is the physics collision callback is set?
  28407. if (registeredMesh.mesh.onPhysicsCollide) {
  28408. if (!registeredMesh.collisionFunction) {
  28409. registeredMesh.collisionFunction = function (e) {
  28410. //find the mesh that collided with the registered mesh
  28411. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28412. if (_this._registeredMeshes[idx].body == e.body) {
  28413. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28414. }
  28415. }
  28416. };
  28417. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28418. }
  28419. }
  28420. else {
  28421. //unregister, in case the function was removed for some reason
  28422. if (registeredMesh.collisionFunction) {
  28423. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28424. }
  28425. }
  28426. });
  28427. };
  28428. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28429. this._gravity = gravity;
  28430. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28431. };
  28432. CannonJSPlugin.prototype.getGravity = function () {
  28433. return this._gravity;
  28434. };
  28435. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28436. this.unregisterMesh(mesh);
  28437. if (!mesh.rotationQuaternion) {
  28438. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28439. }
  28440. mesh.computeWorldMatrix(true);
  28441. var shape = this._createShape(mesh, impostor);
  28442. return this._createRigidBodyFromShape(shape, mesh, options);
  28443. };
  28444. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28445. //get the correct bounding box
  28446. var oldQuaternion = mesh.rotationQuaternion;
  28447. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28448. mesh.computeWorldMatrix(true);
  28449. var returnValue;
  28450. switch (impostor) {
  28451. case BABYLON.PhysicsEngine.SphereImpostor:
  28452. var bbox = mesh.getBoundingInfo().boundingBox;
  28453. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28454. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28455. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28456. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28457. break;
  28458. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28459. case BABYLON.PhysicsEngine.CylinderImpostor:
  28460. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28461. case BABYLON.PhysicsEngine.BoxImpostor:
  28462. bbox = mesh.getBoundingInfo().boundingBox;
  28463. var min = bbox.minimumWorld;
  28464. var max = bbox.maximumWorld;
  28465. var box = max.subtract(min).scale(0.5);
  28466. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28467. break;
  28468. case BABYLON.PhysicsEngine.PlaneImpostor:
  28469. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28470. returnValue = new CANNON.Plane();
  28471. break;
  28472. case BABYLON.PhysicsEngine.MeshImpostor:
  28473. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28474. var rawFaces = mesh.getIndices();
  28475. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28476. break;
  28477. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28478. returnValue = this._createHeightmap(mesh);
  28479. break;
  28480. }
  28481. mesh.rotationQuaternion = oldQuaternion;
  28482. return returnValue;
  28483. };
  28484. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28485. var verts = [], faces = [];
  28486. mesh.computeWorldMatrix(true);
  28487. //reuse this variable
  28488. var transformed = BABYLON.Vector3.Zero();
  28489. // Get vertices
  28490. for (var i = 0; i < rawVerts.length; i += 3) {
  28491. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28492. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28493. }
  28494. // Get faces
  28495. for (var j = 0; j < rawFaces.length; j += 3) {
  28496. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28497. }
  28498. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28499. return shape;
  28500. };
  28501. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28502. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28503. var matrix = [];
  28504. //For now pointDepth will not be used and will be automatically calculated.
  28505. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28506. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28507. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28508. var elementSize = dim * 2 / arraySize;
  28509. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28510. for (var i = 0; i < pos.length; i = i + 3) {
  28511. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28512. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28513. var y = pos[i + 1] + minY;
  28514. if (!matrix[x]) {
  28515. matrix[x] = [];
  28516. }
  28517. if (!matrix[x][z]) {
  28518. matrix[x][z] = y;
  28519. }
  28520. matrix[x][z] = Math.max(y, matrix[x][z]);
  28521. }
  28522. for (var x = 0; x <= arraySize; ++x) {
  28523. if (!matrix[x]) {
  28524. var loc = 1;
  28525. while (!matrix[(x + loc) % arraySize]) {
  28526. loc++;
  28527. }
  28528. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28529. }
  28530. for (var z = 0; z <= arraySize; ++z) {
  28531. if (!matrix[x][z]) {
  28532. var loc = 1;
  28533. var newValue;
  28534. while (newValue === undefined) {
  28535. newValue = matrix[x][(z + loc++) % arraySize];
  28536. }
  28537. matrix[x][z] = newValue;
  28538. }
  28539. }
  28540. }
  28541. var shape = new CANNON.Heightfield(matrix, {
  28542. elementSize: elementSize
  28543. });
  28544. //For future reference, needed for body transformation
  28545. shape.minY = minY;
  28546. return shape;
  28547. };
  28548. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28549. var index;
  28550. var mat;
  28551. for (index = 0; index < this._physicsMaterials.length; index++) {
  28552. mat = this._physicsMaterials[index];
  28553. if (mat.friction === friction && mat.restitution === restitution) {
  28554. return mat;
  28555. }
  28556. }
  28557. var currentMat = new CANNON.Material("mat");
  28558. this._physicsMaterials.push(currentMat);
  28559. for (index = 0; index < this._physicsMaterials.length; index++) {
  28560. mat = this._physicsMaterials[index];
  28561. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28562. this._world.addContactMaterial(contactMaterial);
  28563. }
  28564. return currentMat;
  28565. };
  28566. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28567. if (!mesh.rotationQuaternion) {
  28568. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28569. }
  28570. // The delta between the mesh position and the mesh bounding box center
  28571. var bbox = mesh.getBoundingInfo().boundingBox;
  28572. var deltaPosition = mesh.position.subtract(bbox.center);
  28573. var deltaRotation;
  28574. var material = this._addMaterial(options.friction, options.restitution);
  28575. var body = new CANNON.Body({
  28576. mass: options.mass,
  28577. material: material,
  28578. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28579. });
  28580. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28581. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28582. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28583. //-90 DEG in X, precalculated
  28584. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28585. body.quaternion = body.quaternion.mult(tmpQ);
  28586. //Invert! (Precalculated, 90 deg in X)
  28587. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28588. }
  28589. //If it is a heightfield, if should be centered.
  28590. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28591. //calculate the correct body position:
  28592. var rotationQuaternion = mesh.rotationQuaternion;
  28593. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28594. mesh.computeWorldMatrix(true);
  28595. //get original center with no rotation
  28596. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28597. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28598. //rotation is back
  28599. mesh.rotationQuaternion = rotationQuaternion;
  28600. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28601. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28602. mesh.setPivotMatrix(p);
  28603. mesh.computeWorldMatrix(true);
  28604. //calculate the translation
  28605. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28606. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28607. //add it inverted to the delta
  28608. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28609. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28610. mesh.setPivotMatrix(oldPivot);
  28611. mesh.computeWorldMatrix(true);
  28612. }
  28613. //add the shape
  28614. body.addShape(shape);
  28615. this._world.add(body);
  28616. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28617. return body;
  28618. };
  28619. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28620. var initialMesh = parts[0].mesh;
  28621. this.unregisterMesh(initialMesh);
  28622. initialMesh.computeWorldMatrix(true);
  28623. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28624. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28625. for (var index = 1; index < parts.length; index++) {
  28626. var mesh = parts[index].mesh;
  28627. mesh.computeWorldMatrix(true);
  28628. var shape = this._createShape(mesh, parts[index].impostor);
  28629. var localPosition = mesh.position;
  28630. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28631. }
  28632. return body;
  28633. };
  28634. CannonJSPlugin.prototype._unbindBody = function (body) {
  28635. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28636. var registeredMesh = this._registeredMeshes[index];
  28637. if (registeredMesh.body === body) {
  28638. this._world.remove(registeredMesh.body);
  28639. registeredMesh.body = null;
  28640. registeredMesh.delta = null;
  28641. registeredMesh.deltaRotation = null;
  28642. }
  28643. }
  28644. };
  28645. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28646. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28647. var registeredMesh = this._registeredMeshes[index];
  28648. if (registeredMesh.mesh === mesh) {
  28649. // Remove body
  28650. if (registeredMesh.body) {
  28651. this._unbindBody(registeredMesh.body);
  28652. }
  28653. this._registeredMeshes.splice(index, 1);
  28654. return;
  28655. }
  28656. }
  28657. };
  28658. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28659. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28660. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28661. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28662. var registeredMesh = this._registeredMeshes[index];
  28663. if (registeredMesh.mesh === mesh) {
  28664. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28665. return;
  28666. }
  28667. }
  28668. };
  28669. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28670. var body1 = null, body2 = null;
  28671. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28672. var registeredMesh = this._registeredMeshes[index];
  28673. if (registeredMesh.mesh === mesh1) {
  28674. body1 = registeredMesh.body;
  28675. }
  28676. else if (registeredMesh.mesh === mesh2) {
  28677. body2 = registeredMesh.body;
  28678. }
  28679. }
  28680. if (!body1 || !body2) {
  28681. return false;
  28682. }
  28683. 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));
  28684. this._world.addConstraint(constraint);
  28685. return true;
  28686. };
  28687. CannonJSPlugin.prototype.dispose = function () {
  28688. while (this._registeredMeshes.length) {
  28689. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28690. }
  28691. };
  28692. CannonJSPlugin.prototype.isSupported = function () {
  28693. return window.CANNON !== undefined;
  28694. };
  28695. CannonJSPlugin.prototype.getWorldObject = function () {
  28696. return this._world;
  28697. };
  28698. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28699. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28700. var registeredMesh = this._registeredMeshes[index];
  28701. if (registeredMesh.mesh === mesh) {
  28702. return registeredMesh.body;
  28703. }
  28704. }
  28705. return null;
  28706. };
  28707. return CannonJSPlugin;
  28708. })();
  28709. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28710. })(BABYLON || (BABYLON = {}));
  28711. var BABYLON;
  28712. (function (BABYLON) {
  28713. var OimoJSPlugin = (function () {
  28714. function OimoJSPlugin() {
  28715. this._registeredMeshes = [];
  28716. this.name = "oimo";
  28717. /**
  28718. * Update the body position according to the mesh position
  28719. * @param mesh
  28720. */
  28721. this.updateBodyPosition = function (mesh) {
  28722. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28723. var registeredMesh = this._registeredMeshes[index];
  28724. var body = registeredMesh.body.body;
  28725. var updated = false;
  28726. var newPosition;
  28727. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28728. mesh.computeWorldMatrix(true);
  28729. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28730. updated = true;
  28731. }
  28732. else if (registeredMesh.mesh.parent === mesh) {
  28733. mesh.computeWorldMatrix(true);
  28734. registeredMesh.mesh.computeWorldMatrix(true);
  28735. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28736. updated = true;
  28737. }
  28738. if (updated) {
  28739. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28740. body.setQuaternion(mesh.rotationQuaternion);
  28741. body.sleeping = false;
  28742. //force Oimo to update the body's position
  28743. body.updatePosition(1);
  28744. }
  28745. }
  28746. };
  28747. }
  28748. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28749. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28750. };
  28751. OimoJSPlugin.prototype.initialize = function (iterations) {
  28752. this._world = new OIMO.World(null, null, iterations);
  28753. this._world.clear();
  28754. };
  28755. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28756. this._gravity = this._world.gravity = gravity;
  28757. };
  28758. OimoJSPlugin.prototype.getGravity = function () {
  28759. return this._gravity;
  28760. };
  28761. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28762. this.unregisterMesh(mesh);
  28763. if (!mesh.rotationQuaternion) {
  28764. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28765. }
  28766. mesh.computeWorldMatrix(true);
  28767. var bbox = mesh.getBoundingInfo().boundingBox;
  28768. // The delta between the mesh position and the mesh bounding box center
  28769. var deltaPosition = mesh.position.subtract(bbox.center);
  28770. //calculate rotation to fit Oimo's needs (Euler...)
  28771. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28772. //get the correct bounding box
  28773. var oldQuaternion = mesh.rotationQuaternion;
  28774. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28775. mesh.computeWorldMatrix(true);
  28776. var bodyConfig = {
  28777. name: mesh.uniqueId,
  28778. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28779. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28780. move: options.mass != 0,
  28781. config: [options.mass, options.friction, options.restitution],
  28782. world: this._world
  28783. };
  28784. // register mesh
  28785. switch (impostor) {
  28786. case BABYLON.PhysicsEngine.SphereImpostor:
  28787. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28788. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28789. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28790. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28791. bodyConfig.type = 'sphere';
  28792. bodyConfig.size = [size];
  28793. break;
  28794. case BABYLON.PhysicsEngine.PlaneImpostor:
  28795. //Oimo "fakes" a cylinder as a box, so why don't we!
  28796. case BABYLON.PhysicsEngine.CylinderImpostor:
  28797. case BABYLON.PhysicsEngine.BoxImpostor:
  28798. var min = bbox.minimumWorld;
  28799. var max = bbox.maximumWorld;
  28800. var box = max.subtract(min);
  28801. var sizeX = this._checkWithEpsilon(box.x);
  28802. var sizeY = this._checkWithEpsilon(box.y);
  28803. var sizeZ = this._checkWithEpsilon(box.z);
  28804. bodyConfig.type = 'box';
  28805. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28806. break;
  28807. }
  28808. var body = new OIMO.Body(bodyConfig);
  28809. //We have to access the rigid body's properties to set the quaternion.
  28810. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28811. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28812. //TEST
  28813. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28814. //update the internal rotation matrix
  28815. //body.body.syncShapes();
  28816. this._registeredMeshes.push({
  28817. mesh: mesh,
  28818. body: body,
  28819. delta: deltaPosition
  28820. });
  28821. //for the sake of consistency.
  28822. mesh.rotationQuaternion = oldQuaternion;
  28823. return body;
  28824. };
  28825. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28826. var types = [], sizes = [], positions = [], rotations = [];
  28827. var initialMesh = parts[0].mesh;
  28828. for (var index = 0; index < parts.length; index++) {
  28829. var part = parts[index];
  28830. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28831. types.push(bodyParameters.type);
  28832. sizes.push.apply(sizes, bodyParameters.size);
  28833. positions.push.apply(positions, bodyParameters.pos);
  28834. rotations.push.apply(rotations, bodyParameters.rot);
  28835. }
  28836. var body = new OIMO.Body({
  28837. name: initialMesh.uniqueId,
  28838. type: types,
  28839. size: sizes,
  28840. pos: positions,
  28841. rot: rotations,
  28842. move: options.mass != 0,
  28843. config: [options.mass, options.friction, options.restitution],
  28844. world: this._world
  28845. });
  28846. //Reset the body's rotation to be of the initial mesh's.
  28847. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28848. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28849. this._registeredMeshes.push({
  28850. mesh: initialMesh,
  28851. body: body
  28852. });
  28853. return body;
  28854. };
  28855. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28856. var mesh = part.mesh;
  28857. if (!mesh.rotationQuaternion) {
  28858. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28859. }
  28860. // We need the bounding box/sphere info to compute the physics body
  28861. mesh.computeWorldMatrix(true);
  28862. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28863. var bodyParameters = {
  28864. name: mesh.uniqueId,
  28865. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28866. //A bug in Oimo (Body class) prevents us from using rot directly.
  28867. rot: [0, 0, 0],
  28868. //For future reference, if the bug will ever be fixed.
  28869. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28870. };
  28871. var oldQuaternion = mesh.rotationQuaternion;
  28872. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28873. mesh.computeWorldMatrix(true);
  28874. switch (part.impostor) {
  28875. case BABYLON.PhysicsEngine.SphereImpostor:
  28876. var bbox = mesh.getBoundingInfo().boundingBox;
  28877. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28878. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28879. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28880. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28881. bodyParameters.type = 'sphere';
  28882. bodyParameters.size = [size, size, size];
  28883. break;
  28884. case BABYLON.PhysicsEngine.PlaneImpostor:
  28885. case BABYLON.PhysicsEngine.CylinderImpostor:
  28886. case BABYLON.PhysicsEngine.BoxImpostor:
  28887. bbox = mesh.getBoundingInfo().boundingBox;
  28888. var min = bbox.minimumWorld;
  28889. var max = bbox.maximumWorld;
  28890. var box = max.subtract(min);
  28891. var sizeX = this._checkWithEpsilon(box.x);
  28892. var sizeY = this._checkWithEpsilon(box.y);
  28893. var sizeZ = this._checkWithEpsilon(box.z);
  28894. bodyParameters.type = 'box';
  28895. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28896. break;
  28897. }
  28898. mesh.rotationQuaternion = oldQuaternion;
  28899. return bodyParameters;
  28900. };
  28901. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28902. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28903. var registeredMesh = this._registeredMeshes[index];
  28904. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28905. if (registeredMesh.body) {
  28906. this._world.removeRigidBody(registeredMesh.body.body);
  28907. this._unbindBody(registeredMesh.body);
  28908. }
  28909. this._registeredMeshes.splice(index, 1);
  28910. return;
  28911. }
  28912. }
  28913. };
  28914. OimoJSPlugin.prototype._unbindBody = function (body) {
  28915. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28916. var registeredMesh = this._registeredMeshes[index];
  28917. if (registeredMesh.body === body) {
  28918. registeredMesh.body = null;
  28919. }
  28920. }
  28921. };
  28922. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28923. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28924. var registeredMesh = this._registeredMeshes[index];
  28925. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28926. // Get object mass to have a behaviour similar to cannon.js
  28927. var mass = registeredMesh.body.body.massInfo.mass;
  28928. // The force is scaled with the mass of object
  28929. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28930. return;
  28931. }
  28932. }
  28933. };
  28934. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28935. var body1 = null, body2 = null;
  28936. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28937. var registeredMesh = this._registeredMeshes[index];
  28938. if (registeredMesh.mesh === mesh1) {
  28939. body1 = registeredMesh.body.body;
  28940. }
  28941. else if (registeredMesh.mesh === mesh2) {
  28942. body2 = registeredMesh.body.body;
  28943. }
  28944. }
  28945. if (!body1 || !body2) {
  28946. return false;
  28947. }
  28948. if (!options) {
  28949. options = {};
  28950. }
  28951. new OIMO.Link({
  28952. type: options.type,
  28953. body1: body1,
  28954. body2: body2,
  28955. min: options.min,
  28956. max: options.max,
  28957. axe1: options.axe1,
  28958. axe2: options.axe2,
  28959. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28960. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28961. collision: options.collision,
  28962. spring: options.spring,
  28963. world: this._world
  28964. });
  28965. return true;
  28966. };
  28967. OimoJSPlugin.prototype.dispose = function () {
  28968. this._world.clear();
  28969. while (this._registeredMeshes.length) {
  28970. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28971. }
  28972. };
  28973. OimoJSPlugin.prototype.isSupported = function () {
  28974. return OIMO !== undefined;
  28975. };
  28976. OimoJSPlugin.prototype.getWorldObject = function () {
  28977. return this._world;
  28978. };
  28979. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28980. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28981. var registeredMesh = this._registeredMeshes[index];
  28982. if (registeredMesh.mesh === mesh) {
  28983. return registeredMesh.body;
  28984. }
  28985. }
  28986. return null;
  28987. };
  28988. OimoJSPlugin.prototype._getLastShape = function (body) {
  28989. var lastShape = body.shapes;
  28990. while (lastShape.next) {
  28991. lastShape = lastShape.next;
  28992. }
  28993. return lastShape;
  28994. };
  28995. OimoJSPlugin.prototype.runOneStep = function (time) {
  28996. this._world.step();
  28997. // Update the position of all registered meshes
  28998. var i = this._registeredMeshes.length;
  28999. var m;
  29000. while (i--) {
  29001. var body = this._registeredMeshes[i].body.body;
  29002. var mesh = this._registeredMeshes[i].mesh;
  29003. if (!this._registeredMeshes[i].delta) {
  29004. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29005. }
  29006. if (!body.sleeping) {
  29007. //TODO check that
  29008. if (body.shapes.next) {
  29009. var parentShape = this._getLastShape(body);
  29010. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29011. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29012. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29013. }
  29014. else {
  29015. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29016. }
  29017. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29018. mesh.computeWorldMatrix();
  29019. }
  29020. //check if the collide callback is set.
  29021. if (mesh.onPhysicsCollide) {
  29022. var meshUniqueName = mesh.uniqueId;
  29023. var contact = this._world.contacts;
  29024. while (contact !== null) {
  29025. //is this body colliding with any other?
  29026. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29027. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29028. //get the mesh and execute the callback
  29029. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29030. if (otherMesh)
  29031. mesh.onPhysicsCollide(otherMesh);
  29032. }
  29033. contact = contact.next;
  29034. }
  29035. }
  29036. }
  29037. };
  29038. return OimoJSPlugin;
  29039. })();
  29040. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29041. })(BABYLON || (BABYLON = {}));
  29042. var BABYLON;
  29043. (function (BABYLON) {
  29044. var DisplayPassPostProcess = (function (_super) {
  29045. __extends(DisplayPassPostProcess, _super);
  29046. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29047. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29048. }
  29049. return DisplayPassPostProcess;
  29050. })(BABYLON.PostProcess);
  29051. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29052. })(BABYLON || (BABYLON = {}));
  29053. var BABYLON;
  29054. (function (BABYLON) {
  29055. var SimplificationSettings = (function () {
  29056. function SimplificationSettings(quality, distance, optimizeMesh) {
  29057. this.quality = quality;
  29058. this.distance = distance;
  29059. this.optimizeMesh = optimizeMesh;
  29060. }
  29061. return SimplificationSettings;
  29062. })();
  29063. BABYLON.SimplificationSettings = SimplificationSettings;
  29064. var SimplificationQueue = (function () {
  29065. function SimplificationQueue() {
  29066. this.running = false;
  29067. this._simplificationArray = [];
  29068. }
  29069. SimplificationQueue.prototype.addTask = function (task) {
  29070. this._simplificationArray.push(task);
  29071. };
  29072. SimplificationQueue.prototype.executeNext = function () {
  29073. var task = this._simplificationArray.pop();
  29074. if (task) {
  29075. this.running = true;
  29076. this.runSimplification(task);
  29077. }
  29078. else {
  29079. this.running = false;
  29080. }
  29081. };
  29082. SimplificationQueue.prototype.runSimplification = function (task) {
  29083. var _this = this;
  29084. if (task.parallelProcessing) {
  29085. //parallel simplifier
  29086. task.settings.forEach(function (setting) {
  29087. var simplifier = _this.getSimplifier(task);
  29088. simplifier.simplify(setting, function (newMesh) {
  29089. task.mesh.addLODLevel(setting.distance, newMesh);
  29090. newMesh.isVisible = true;
  29091. //check if it is the last
  29092. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29093. //all done, run the success callback.
  29094. task.successCallback();
  29095. }
  29096. _this.executeNext();
  29097. });
  29098. });
  29099. }
  29100. else {
  29101. //single simplifier.
  29102. var simplifier = this.getSimplifier(task);
  29103. var runDecimation = function (setting, callback) {
  29104. simplifier.simplify(setting, function (newMesh) {
  29105. task.mesh.addLODLevel(setting.distance, newMesh);
  29106. newMesh.isVisible = true;
  29107. //run the next quality level
  29108. callback();
  29109. });
  29110. };
  29111. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29112. runDecimation(task.settings[loop.index], function () {
  29113. loop.executeNext();
  29114. });
  29115. }, function () {
  29116. //execution ended, run the success callback.
  29117. if (task.successCallback) {
  29118. task.successCallback();
  29119. }
  29120. _this.executeNext();
  29121. });
  29122. }
  29123. };
  29124. SimplificationQueue.prototype.getSimplifier = function (task) {
  29125. switch (task.simplificationType) {
  29126. case SimplificationType.QUADRATIC:
  29127. default:
  29128. return new QuadraticErrorSimplification(task.mesh);
  29129. }
  29130. };
  29131. return SimplificationQueue;
  29132. })();
  29133. BABYLON.SimplificationQueue = SimplificationQueue;
  29134. /**
  29135. * The implemented types of simplification.
  29136. * At the moment only Quadratic Error Decimation is implemented.
  29137. */
  29138. (function (SimplificationType) {
  29139. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29140. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29141. var SimplificationType = BABYLON.SimplificationType;
  29142. var DecimationTriangle = (function () {
  29143. function DecimationTriangle(vertices) {
  29144. this.vertices = vertices;
  29145. this.error = new Array(4);
  29146. this.deleted = false;
  29147. this.isDirty = false;
  29148. this.deletePending = false;
  29149. this.borderFactor = 0;
  29150. }
  29151. return DecimationTriangle;
  29152. })();
  29153. BABYLON.DecimationTriangle = DecimationTriangle;
  29154. var DecimationVertex = (function () {
  29155. function DecimationVertex(position, id) {
  29156. this.position = position;
  29157. this.id = id;
  29158. this.isBorder = true;
  29159. this.q = new QuadraticMatrix();
  29160. this.triangleCount = 0;
  29161. this.triangleStart = 0;
  29162. this.originalOffsets = [];
  29163. }
  29164. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29165. this.position.copyFrom(newPosition);
  29166. };
  29167. return DecimationVertex;
  29168. })();
  29169. BABYLON.DecimationVertex = DecimationVertex;
  29170. var QuadraticMatrix = (function () {
  29171. function QuadraticMatrix(data) {
  29172. this.data = new Array(10);
  29173. for (var i = 0; i < 10; ++i) {
  29174. if (data && data[i]) {
  29175. this.data[i] = data[i];
  29176. }
  29177. else {
  29178. this.data[i] = 0;
  29179. }
  29180. }
  29181. }
  29182. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29183. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29184. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29185. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29186. return det;
  29187. };
  29188. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29189. for (var i = 0; i < 10; ++i) {
  29190. this.data[i] += matrix.data[i];
  29191. }
  29192. };
  29193. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29194. for (var i = 0; i < 10; ++i) {
  29195. this.data[i] += data[i];
  29196. }
  29197. };
  29198. QuadraticMatrix.prototype.add = function (matrix) {
  29199. var m = new QuadraticMatrix();
  29200. for (var i = 0; i < 10; ++i) {
  29201. m.data[i] = this.data[i] + matrix.data[i];
  29202. }
  29203. return m;
  29204. };
  29205. QuadraticMatrix.FromData = function (a, b, c, d) {
  29206. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29207. };
  29208. //returning an array to avoid garbage collection
  29209. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29210. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29211. };
  29212. return QuadraticMatrix;
  29213. })();
  29214. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29215. var Reference = (function () {
  29216. function Reference(vertexId, triangleId) {
  29217. this.vertexId = vertexId;
  29218. this.triangleId = triangleId;
  29219. }
  29220. return Reference;
  29221. })();
  29222. BABYLON.Reference = Reference;
  29223. /**
  29224. * An implementation of the Quadratic Error simplification algorithm.
  29225. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29226. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29227. * @author RaananW
  29228. */
  29229. var QuadraticErrorSimplification = (function () {
  29230. function QuadraticErrorSimplification(_mesh) {
  29231. this._mesh = _mesh;
  29232. this.initialized = false;
  29233. this.syncIterations = 5000;
  29234. this.aggressiveness = 7;
  29235. this.decimationIterations = 100;
  29236. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29237. }
  29238. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29239. var _this = this;
  29240. this.initDecimatedMesh();
  29241. //iterating through the submeshes array, one after the other.
  29242. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29243. _this.initWithMesh(loop.index, function () {
  29244. _this.runDecimation(settings, loop.index, function () {
  29245. loop.executeNext();
  29246. });
  29247. }, settings.optimizeMesh);
  29248. }, function () {
  29249. setTimeout(function () {
  29250. successCallback(_this._reconstructedMesh);
  29251. }, 0);
  29252. });
  29253. };
  29254. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29255. var _this = this;
  29256. var gCount = 0;
  29257. triangle.vertices.forEach(function (vertex) {
  29258. var count = 0;
  29259. var vPos = vertex.position;
  29260. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29261. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29262. ++count;
  29263. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29264. ++count;
  29265. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29266. ++count;
  29267. if (count > 1) {
  29268. ++gCount;
  29269. }
  29270. ;
  29271. });
  29272. if (gCount > 1) {
  29273. console.log(triangle, gCount);
  29274. }
  29275. return gCount > 1;
  29276. };
  29277. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29278. var _this = this;
  29279. var targetCount = ~~(this.triangles.length * settings.quality);
  29280. var deletedTriangles = 0;
  29281. var triangleCount = this.triangles.length;
  29282. var iterationFunction = function (iteration, callback) {
  29283. setTimeout(function () {
  29284. if (iteration % 5 === 0) {
  29285. _this.updateMesh(iteration === 0);
  29286. }
  29287. for (var i = 0; i < _this.triangles.length; ++i) {
  29288. _this.triangles[i].isDirty = false;
  29289. }
  29290. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29291. var trianglesIterator = function (i) {
  29292. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29293. var t = _this.triangles[tIdx];
  29294. if (!t)
  29295. return;
  29296. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29297. return;
  29298. }
  29299. for (var j = 0; j < 3; ++j) {
  29300. if (t.error[j] < threshold) {
  29301. var deleted0 = [];
  29302. var deleted1 = [];
  29303. var v0 = t.vertices[j];
  29304. var v1 = t.vertices[(j + 1) % 3];
  29305. if (v0.isBorder !== v1.isBorder)
  29306. continue;
  29307. var p = BABYLON.Vector3.Zero();
  29308. var n = BABYLON.Vector3.Zero();
  29309. var uv = BABYLON.Vector2.Zero();
  29310. var color = new BABYLON.Color4(0, 0, 0, 1);
  29311. _this.calculateError(v0, v1, p, n, uv, color);
  29312. var delTr = [];
  29313. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29314. continue;
  29315. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29316. continue;
  29317. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29318. continue;
  29319. var uniqueArray = [];
  29320. delTr.forEach(function (deletedT) {
  29321. if (uniqueArray.indexOf(deletedT) === -1) {
  29322. deletedT.deletePending = true;
  29323. uniqueArray.push(deletedT);
  29324. }
  29325. });
  29326. if (uniqueArray.length % 2 !== 0) {
  29327. continue;
  29328. }
  29329. v0.q = v1.q.add(v0.q);
  29330. v0.updatePosition(p);
  29331. var tStart = _this.references.length;
  29332. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29333. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29334. var tCount = _this.references.length - tStart;
  29335. if (tCount <= v0.triangleCount) {
  29336. if (tCount) {
  29337. for (var c = 0; c < tCount; c++) {
  29338. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29339. }
  29340. }
  29341. }
  29342. else {
  29343. v0.triangleStart = tStart;
  29344. }
  29345. v0.triangleCount = tCount;
  29346. break;
  29347. }
  29348. }
  29349. };
  29350. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29351. }, 0);
  29352. };
  29353. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29354. if (triangleCount - deletedTriangles <= targetCount)
  29355. loop.breakLoop();
  29356. else {
  29357. iterationFunction(loop.index, function () {
  29358. loop.executeNext();
  29359. });
  29360. }
  29361. }, function () {
  29362. setTimeout(function () {
  29363. //reconstruct this part of the mesh
  29364. _this.reconstructMesh(submeshIndex);
  29365. successCallback();
  29366. }, 0);
  29367. });
  29368. };
  29369. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29370. var _this = this;
  29371. this.vertices = [];
  29372. this.triangles = [];
  29373. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29374. var indices = this._mesh.getIndices();
  29375. var submesh = this._mesh.subMeshes[submeshIndex];
  29376. var findInVertices = function (positionToSearch) {
  29377. if (optimizeMesh) {
  29378. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29379. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29380. return _this.vertices[ii];
  29381. }
  29382. }
  29383. }
  29384. return null;
  29385. };
  29386. var vertexReferences = [];
  29387. var vertexInit = function (i) {
  29388. var offset = i + submesh.verticesStart;
  29389. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29390. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29391. vertex.originalOffsets.push(offset);
  29392. if (vertex.id === _this.vertices.length) {
  29393. _this.vertices.push(vertex);
  29394. }
  29395. vertexReferences.push(vertex.id);
  29396. };
  29397. //var totalVertices = mesh.getTotalVertices();
  29398. var totalVertices = submesh.verticesCount;
  29399. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29400. var indicesInit = function (i) {
  29401. var offset = (submesh.indexStart / 3) + i;
  29402. var pos = (offset * 3);
  29403. var i0 = indices[pos + 0];
  29404. var i1 = indices[pos + 1];
  29405. var i2 = indices[pos + 2];
  29406. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29407. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29408. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29409. var triangle = new DecimationTriangle([v0, v1, v2]);
  29410. triangle.originalOffset = pos;
  29411. _this.triangles.push(triangle);
  29412. };
  29413. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29414. _this.init(callback);
  29415. });
  29416. });
  29417. };
  29418. QuadraticErrorSimplification.prototype.init = function (callback) {
  29419. var _this = this;
  29420. var triangleInit1 = function (i) {
  29421. var t = _this.triangles[i];
  29422. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29423. for (var j = 0; j < 3; j++) {
  29424. 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))));
  29425. }
  29426. };
  29427. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29428. var triangleInit2 = function (i) {
  29429. var t = _this.triangles[i];
  29430. for (var j = 0; j < 3; ++j) {
  29431. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29432. }
  29433. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29434. };
  29435. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29436. _this.initialized = true;
  29437. callback();
  29438. });
  29439. });
  29440. };
  29441. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29442. var newTriangles = [];
  29443. var i;
  29444. for (i = 0; i < this.vertices.length; ++i) {
  29445. this.vertices[i].triangleCount = 0;
  29446. }
  29447. var t;
  29448. var j;
  29449. for (i = 0; i < this.triangles.length; ++i) {
  29450. if (!this.triangles[i].deleted) {
  29451. t = this.triangles[i];
  29452. for (j = 0; j < 3; ++j) {
  29453. t.vertices[j].triangleCount = 1;
  29454. }
  29455. newTriangles.push(t);
  29456. }
  29457. }
  29458. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29459. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29460. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29461. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29462. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29463. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29464. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29465. var vertexCount = 0;
  29466. for (i = 0; i < this.vertices.length; ++i) {
  29467. var vertex = this.vertices[i];
  29468. vertex.id = vertexCount;
  29469. if (vertex.triangleCount) {
  29470. vertex.originalOffsets.forEach(function (originalOffset) {
  29471. newPositionData.push(vertex.position.x);
  29472. newPositionData.push(vertex.position.y);
  29473. newPositionData.push(vertex.position.z);
  29474. newNormalData.push(normalData[originalOffset * 3]);
  29475. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29476. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29477. if (uvs && uvs.length) {
  29478. newUVsData.push(uvs[(originalOffset * 2)]);
  29479. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29480. }
  29481. else if (colorsData && colorsData.length) {
  29482. newColorsData.push(colorsData[(originalOffset * 4)]);
  29483. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29484. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29485. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29486. }
  29487. ++vertexCount;
  29488. });
  29489. }
  29490. }
  29491. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29492. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29493. var submeshesArray = this._reconstructedMesh.subMeshes;
  29494. this._reconstructedMesh.subMeshes = [];
  29495. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29496. var originalIndices = this._mesh.getIndices();
  29497. for (i = 0; i < newTriangles.length; ++i) {
  29498. t = newTriangles[i]; //now get the new referencing point for each vertex
  29499. [0, 1, 2].forEach(function (idx) {
  29500. var id = originalIndices[t.originalOffset + idx];
  29501. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29502. if (offset < 0)
  29503. offset = 0;
  29504. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29505. });
  29506. }
  29507. //overwriting the old vertex buffers and indices.
  29508. this._reconstructedMesh.setIndices(newIndicesArray);
  29509. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29510. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29511. if (newUVsData.length > 0)
  29512. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29513. if (newColorsData.length > 0)
  29514. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29515. //create submesh
  29516. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29517. if (submeshIndex > 0) {
  29518. this._reconstructedMesh.subMeshes = [];
  29519. submeshesArray.forEach(function (submesh) {
  29520. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29521. });
  29522. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29523. }
  29524. };
  29525. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29526. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29527. this._reconstructedMesh.material = this._mesh.material;
  29528. this._reconstructedMesh.parent = this._mesh.parent;
  29529. this._reconstructedMesh.isVisible = false;
  29530. };
  29531. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29532. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29533. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29534. if (t.deleted)
  29535. continue;
  29536. var s = this.references[vertex1.triangleStart + i].vertexId;
  29537. var v1 = t.vertices[(s + 1) % 3];
  29538. var v2 = t.vertices[(s + 2) % 3];
  29539. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29540. deletedArray[i] = true;
  29541. delTr.push(t);
  29542. continue;
  29543. }
  29544. var d1 = v1.position.subtract(point);
  29545. d1 = d1.normalize();
  29546. var d2 = v2.position.subtract(point);
  29547. d2 = d2.normalize();
  29548. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29549. return true;
  29550. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29551. deletedArray[i] = false;
  29552. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29553. return true;
  29554. }
  29555. return false;
  29556. };
  29557. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29558. var newDeleted = deletedTriangles;
  29559. for (var i = 0; i < vertex.triangleCount; ++i) {
  29560. var ref = this.references[vertex.triangleStart + i];
  29561. var t = this.triangles[ref.triangleId];
  29562. if (t.deleted)
  29563. continue;
  29564. if (deletedArray[i] && t.deletePending) {
  29565. t.deleted = true;
  29566. newDeleted++;
  29567. continue;
  29568. }
  29569. t.vertices[ref.vertexId] = origVertex;
  29570. t.isDirty = true;
  29571. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29572. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29573. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29574. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29575. this.references.push(ref);
  29576. }
  29577. return newDeleted;
  29578. };
  29579. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29580. for (var i = 0; i < this.vertices.length; ++i) {
  29581. var vCount = [];
  29582. var vId = [];
  29583. var v = this.vertices[i];
  29584. var j;
  29585. for (j = 0; j < v.triangleCount; ++j) {
  29586. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29587. for (var ii = 0; ii < 3; ii++) {
  29588. var ofs = 0;
  29589. var vv = triangle.vertices[ii];
  29590. while (ofs < vCount.length) {
  29591. if (vId[ofs] === vv.id)
  29592. break;
  29593. ++ofs;
  29594. }
  29595. if (ofs === vCount.length) {
  29596. vCount.push(1);
  29597. vId.push(vv.id);
  29598. }
  29599. else {
  29600. vCount[ofs]++;
  29601. }
  29602. }
  29603. }
  29604. for (j = 0; j < vCount.length; ++j) {
  29605. if (vCount[j] === 1) {
  29606. this.vertices[vId[j]].isBorder = true;
  29607. }
  29608. else {
  29609. this.vertices[vId[j]].isBorder = false;
  29610. }
  29611. }
  29612. }
  29613. };
  29614. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29615. if (identifyBorders === void 0) { identifyBorders = false; }
  29616. var i;
  29617. if (!identifyBorders) {
  29618. var newTrianglesVector = [];
  29619. for (i = 0; i < this.triangles.length; ++i) {
  29620. if (!this.triangles[i].deleted) {
  29621. newTrianglesVector.push(this.triangles[i]);
  29622. }
  29623. }
  29624. this.triangles = newTrianglesVector;
  29625. }
  29626. for (i = 0; i < this.vertices.length; ++i) {
  29627. this.vertices[i].triangleCount = 0;
  29628. this.vertices[i].triangleStart = 0;
  29629. }
  29630. var t;
  29631. var j;
  29632. var v;
  29633. for (i = 0; i < this.triangles.length; ++i) {
  29634. t = this.triangles[i];
  29635. for (j = 0; j < 3; ++j) {
  29636. v = t.vertices[j];
  29637. v.triangleCount++;
  29638. }
  29639. }
  29640. var tStart = 0;
  29641. for (i = 0; i < this.vertices.length; ++i) {
  29642. this.vertices[i].triangleStart = tStart;
  29643. tStart += this.vertices[i].triangleCount;
  29644. this.vertices[i].triangleCount = 0;
  29645. }
  29646. var newReferences = new Array(this.triangles.length * 3);
  29647. for (i = 0; i < this.triangles.length; ++i) {
  29648. t = this.triangles[i];
  29649. for (j = 0; j < 3; ++j) {
  29650. v = t.vertices[j];
  29651. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29652. v.triangleCount++;
  29653. }
  29654. }
  29655. this.references = newReferences;
  29656. if (identifyBorders) {
  29657. this.identifyBorder();
  29658. }
  29659. };
  29660. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29661. var x = point.x;
  29662. var y = point.y;
  29663. var z = point.z;
  29664. 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
  29665. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29666. };
  29667. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29668. var q = vertex1.q.add(vertex2.q);
  29669. var border = vertex1.isBorder && vertex2.isBorder;
  29670. var error = 0;
  29671. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29672. if (qDet !== 0 && !border) {
  29673. if (!pointResult) {
  29674. pointResult = BABYLON.Vector3.Zero();
  29675. }
  29676. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29677. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29678. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29679. error = this.vertexError(q, pointResult);
  29680. }
  29681. else {
  29682. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29683. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29684. var error1 = this.vertexError(q, vertex1.position);
  29685. var error2 = this.vertexError(q, vertex2.position);
  29686. var error3 = this.vertexError(q, p3);
  29687. error = Math.min(error1, error2, error3);
  29688. if (error === error1) {
  29689. if (pointResult) {
  29690. pointResult.copyFrom(vertex1.position);
  29691. }
  29692. }
  29693. else if (error === error2) {
  29694. if (pointResult) {
  29695. pointResult.copyFrom(vertex2.position);
  29696. }
  29697. }
  29698. else {
  29699. if (pointResult) {
  29700. pointResult.copyFrom(p3);
  29701. }
  29702. }
  29703. }
  29704. return error;
  29705. };
  29706. return QuadraticErrorSimplification;
  29707. })();
  29708. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29709. })(BABYLON || (BABYLON = {}));
  29710. var BABYLON;
  29711. (function (BABYLON) {
  29712. var serializedGeometries = [];
  29713. var serializeVertexData;
  29714. var serializeTorusKnot;
  29715. var serializePlane;
  29716. var serializeGround;
  29717. var serializeTorus;
  29718. var serializeCylinder;
  29719. var serializeSphere;
  29720. var serializeBox;
  29721. var serializeGeometry = function (geometry, serializationGeometries) {
  29722. if (serializedGeometries[geometry.id]) {
  29723. return;
  29724. }
  29725. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29726. serializationGeometries.boxes.push(serializeBox(geometry));
  29727. }
  29728. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29729. serializationGeometries.spheres.push(serializeSphere(geometry));
  29730. }
  29731. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29732. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29733. }
  29734. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29735. serializationGeometries.toruses.push(serializeTorus(geometry));
  29736. }
  29737. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29738. serializationGeometries.grounds.push(serializeGround(geometry));
  29739. }
  29740. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29741. serializationGeometries.planes.push(serializePlane(geometry));
  29742. }
  29743. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29744. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29745. }
  29746. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29747. throw new Error("Unknown primitive type");
  29748. }
  29749. else {
  29750. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29751. }
  29752. serializedGeometries[geometry.id] = true;
  29753. };
  29754. var serializeGeometryBase = function (geometry) {
  29755. var serializationObject = {};
  29756. serializationObject.id = geometry.id;
  29757. if (BABYLON.Tags.HasTags(geometry)) {
  29758. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29759. }
  29760. return serializationObject;
  29761. };
  29762. serializeVertexData = function (vertexData) {
  29763. var serializationObject = serializeGeometryBase(vertexData);
  29764. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29765. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29766. }
  29767. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29768. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29769. }
  29770. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29771. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29772. }
  29773. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29774. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29775. }
  29776. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29777. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29778. }
  29779. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29780. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29781. }
  29782. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29783. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29784. }
  29785. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29786. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29787. }
  29788. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29789. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29790. }
  29791. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29792. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29793. serializationObject.matricesIndices._isExpanded = true;
  29794. }
  29795. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29796. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29797. }
  29798. serializationObject.indices = vertexData.getIndices();
  29799. return serializationObject;
  29800. };
  29801. var serializePrimitive = function (primitive) {
  29802. var serializationObject = serializeGeometryBase(primitive);
  29803. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29804. return serializationObject;
  29805. };
  29806. serializeBox = function (box) {
  29807. var serializationObject = serializePrimitive(box);
  29808. serializationObject.size = box.size;
  29809. return serializationObject;
  29810. };
  29811. serializeSphere = function (sphere) {
  29812. var serializationObject = serializePrimitive(sphere);
  29813. serializationObject.segments = sphere.segments;
  29814. serializationObject.diameter = sphere.diameter;
  29815. return serializationObject;
  29816. };
  29817. serializeCylinder = function (cylinder) {
  29818. var serializationObject = serializePrimitive(cylinder);
  29819. serializationObject.height = cylinder.height;
  29820. serializationObject.diameterTop = cylinder.diameterTop;
  29821. serializationObject.diameterBottom = cylinder.diameterBottom;
  29822. serializationObject.tessellation = cylinder.tessellation;
  29823. return serializationObject;
  29824. };
  29825. serializeTorus = function (torus) {
  29826. var serializationObject = serializePrimitive(torus);
  29827. serializationObject.diameter = torus.diameter;
  29828. serializationObject.thickness = torus.thickness;
  29829. serializationObject.tessellation = torus.tessellation;
  29830. return serializationObject;
  29831. };
  29832. serializeGround = function (ground) {
  29833. var serializationObject = serializePrimitive(ground);
  29834. serializationObject.width = ground.width;
  29835. serializationObject.height = ground.height;
  29836. serializationObject.subdivisions = ground.subdivisions;
  29837. return serializationObject;
  29838. };
  29839. serializePlane = function (plane) {
  29840. var serializationObject = serializePrimitive(plane);
  29841. serializationObject.size = plane.size;
  29842. return serializationObject;
  29843. };
  29844. serializeTorusKnot = function (torusKnot) {
  29845. var serializationObject = serializePrimitive(torusKnot);
  29846. serializationObject.radius = torusKnot.radius;
  29847. serializationObject.tube = torusKnot.tube;
  29848. serializationObject.radialSegments = torusKnot.radialSegments;
  29849. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29850. serializationObject.p = torusKnot.p;
  29851. serializationObject.q = torusKnot.q;
  29852. return serializationObject;
  29853. };
  29854. var serializeMesh = function (mesh, serializationScene) {
  29855. var serializationObject = {};
  29856. serializationObject.name = mesh.name;
  29857. serializationObject.id = mesh.id;
  29858. if (BABYLON.Tags.HasTags(mesh)) {
  29859. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29860. }
  29861. serializationObject.position = mesh.position.asArray();
  29862. if (mesh.rotationQuaternion) {
  29863. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29864. }
  29865. else if (mesh.rotation) {
  29866. serializationObject.rotation = mesh.rotation.asArray();
  29867. }
  29868. serializationObject.scaling = mesh.scaling.asArray();
  29869. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29870. serializationObject.isEnabled = mesh.isEnabled();
  29871. serializationObject.isVisible = mesh.isVisible;
  29872. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29873. serializationObject.pickable = mesh.isPickable;
  29874. serializationObject.receiveShadows = mesh.receiveShadows;
  29875. serializationObject.billboardMode = mesh.billboardMode;
  29876. serializationObject.visibility = mesh.visibility;
  29877. serializationObject.checkCollisions = mesh.checkCollisions;
  29878. // Parent
  29879. if (mesh.parent) {
  29880. serializationObject.parentId = mesh.parent.id;
  29881. }
  29882. // Geometry
  29883. var geometry = mesh._geometry;
  29884. if (geometry) {
  29885. var geometryId = geometry.id;
  29886. serializationObject.geometryId = geometryId;
  29887. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29888. // 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
  29889. serializeGeometry(geometry, serializationScene.geometries);
  29890. }
  29891. // SubMeshes
  29892. serializationObject.subMeshes = [];
  29893. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29894. var subMesh = mesh.subMeshes[subIndex];
  29895. serializationObject.subMeshes.push({
  29896. materialIndex: subMesh.materialIndex,
  29897. verticesStart: subMesh.verticesStart,
  29898. verticesCount: subMesh.verticesCount,
  29899. indexStart: subMesh.indexStart,
  29900. indexCount: subMesh.indexCount
  29901. });
  29902. }
  29903. }
  29904. // Material
  29905. if (mesh.material) {
  29906. serializationObject.materialId = mesh.material.id;
  29907. }
  29908. else {
  29909. mesh.material = null;
  29910. }
  29911. // Skeleton
  29912. if (mesh.skeleton) {
  29913. serializationObject.skeletonId = mesh.skeleton.id;
  29914. }
  29915. // Physics
  29916. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29917. serializationObject.physicsMass = mesh.getPhysicsMass();
  29918. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29919. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29920. switch (mesh.getPhysicsImpostor()) {
  29921. case BABYLON.PhysicsEngine.BoxImpostor:
  29922. serializationObject.physicsImpostor = 1;
  29923. break;
  29924. case BABYLON.PhysicsEngine.SphereImpostor:
  29925. serializationObject.physicsImpostor = 2;
  29926. break;
  29927. }
  29928. }
  29929. // Instances
  29930. serializationObject.instances = [];
  29931. for (var index = 0; index < mesh.instances.length; index++) {
  29932. var instance = mesh.instances[index];
  29933. var serializationInstance = {
  29934. name: instance.name,
  29935. position: instance.position.asArray(),
  29936. rotation: instance.rotation.asArray(),
  29937. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29938. scaling: instance.scaling.asArray()
  29939. };
  29940. serializationObject.instances.push(serializationInstance);
  29941. // Animations
  29942. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29943. }
  29944. // Animations
  29945. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  29946. // Layer mask
  29947. serializationObject.layerMask = mesh.layerMask;
  29948. return serializationObject;
  29949. };
  29950. var finalizeSingleMesh = function (mesh, serializationObject) {
  29951. //only works if the mesh is already loaded
  29952. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29953. //serialize material
  29954. if (mesh.material) {
  29955. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29956. serializationObject.materials = serializationObject.materials || [];
  29957. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29958. serializationObject.materials.push(mesh.material.serialize());
  29959. }
  29960. }
  29961. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29962. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29963. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29964. serializationObject.multiMaterials.push(mesh.material.serialize());
  29965. }
  29966. }
  29967. }
  29968. //serialize geometry
  29969. var geometry = mesh._geometry;
  29970. if (geometry) {
  29971. if (!serializationObject.geometries) {
  29972. serializationObject.geometries = {};
  29973. serializationObject.geometries.boxes = [];
  29974. serializationObject.geometries.spheres = [];
  29975. serializationObject.geometries.cylinders = [];
  29976. serializationObject.geometries.toruses = [];
  29977. serializationObject.geometries.grounds = [];
  29978. serializationObject.geometries.planes = [];
  29979. serializationObject.geometries.torusKnots = [];
  29980. serializationObject.geometries.vertexData = [];
  29981. }
  29982. serializeGeometry(geometry, serializationObject.geometries);
  29983. }
  29984. // Skeletons
  29985. if (mesh.skeleton) {
  29986. serializationObject.skeletons = serializationObject.skeletons || [];
  29987. serializationObject.skeletons.push(mesh.skeleton.serialize());
  29988. }
  29989. //serialize the actual mesh
  29990. serializationObject.meshes = serializationObject.meshes || [];
  29991. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29992. }
  29993. };
  29994. var SceneSerializer = (function () {
  29995. function SceneSerializer() {
  29996. }
  29997. SceneSerializer.Serialize = function (scene) {
  29998. var serializationObject = {};
  29999. // Scene
  30000. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30001. serializationObject.autoClear = scene.autoClear;
  30002. serializationObject.clearColor = scene.clearColor.asArray();
  30003. serializationObject.ambientColor = scene.ambientColor.asArray();
  30004. serializationObject.gravity = scene.gravity.asArray();
  30005. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30006. serializationObject.workerCollisions = scene.workerCollisions;
  30007. // Fog
  30008. if (scene.fogMode && scene.fogMode !== 0) {
  30009. serializationObject.fogMode = scene.fogMode;
  30010. serializationObject.fogColor = scene.fogColor.asArray();
  30011. serializationObject.fogStart = scene.fogStart;
  30012. serializationObject.fogEnd = scene.fogEnd;
  30013. serializationObject.fogDensity = scene.fogDensity;
  30014. }
  30015. //Physics
  30016. if (scene.isPhysicsEnabled()) {
  30017. serializationObject.physicsEnabled = true;
  30018. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30019. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30020. }
  30021. // Lights
  30022. serializationObject.lights = [];
  30023. var index;
  30024. var light;
  30025. for (index = 0; index < scene.lights.length; index++) {
  30026. light = scene.lights[index];
  30027. serializationObject.lights.push(light.serialize());
  30028. }
  30029. // Cameras
  30030. serializationObject.cameras = [];
  30031. for (index = 0; index < scene.cameras.length; index++) {
  30032. var camera = scene.cameras[index];
  30033. serializationObject.cameras.push(camera.serialize());
  30034. }
  30035. if (scene.activeCamera) {
  30036. serializationObject.activeCameraID = scene.activeCamera.id;
  30037. }
  30038. // Materials
  30039. serializationObject.materials = [];
  30040. serializationObject.multiMaterials = [];
  30041. var material;
  30042. for (index = 0; index < scene.materials.length; index++) {
  30043. material = scene.materials[index];
  30044. serializationObject.materials.push(material.serialize());
  30045. }
  30046. // MultiMaterials
  30047. serializationObject.multiMaterials = [];
  30048. for (index = 0; index < scene.multiMaterials.length; index++) {
  30049. var multiMaterial = scene.multiMaterials[index];
  30050. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30051. }
  30052. for (index = 0; index < scene.materials.length; index++) {
  30053. material = scene.materials[index];
  30054. serializationObject.materials.push(material.serialize());
  30055. }
  30056. // Skeletons
  30057. serializationObject.skeletons = [];
  30058. for (index = 0; index < scene.skeletons.length; index++) {
  30059. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30060. }
  30061. // Geometries
  30062. serializationObject.geometries = {};
  30063. serializationObject.geometries.boxes = [];
  30064. serializationObject.geometries.spheres = [];
  30065. serializationObject.geometries.cylinders = [];
  30066. serializationObject.geometries.toruses = [];
  30067. serializationObject.geometries.grounds = [];
  30068. serializationObject.geometries.planes = [];
  30069. serializationObject.geometries.torusKnots = [];
  30070. serializationObject.geometries.vertexData = [];
  30071. serializedGeometries = [];
  30072. var geometries = scene.getGeometries();
  30073. for (index = 0; index < geometries.length; index++) {
  30074. var geometry = geometries[index];
  30075. if (geometry.isReady()) {
  30076. serializeGeometry(geometry, serializationObject.geometries);
  30077. }
  30078. }
  30079. // Meshes
  30080. serializationObject.meshes = [];
  30081. for (index = 0; index < scene.meshes.length; index++) {
  30082. var abstractMesh = scene.meshes[index];
  30083. if (abstractMesh instanceof BABYLON.Mesh) {
  30084. var mesh = abstractMesh;
  30085. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30086. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30087. }
  30088. }
  30089. }
  30090. // Particles Systems
  30091. serializationObject.particleSystems = [];
  30092. for (index = 0; index < scene.particleSystems.length; index++) {
  30093. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30094. }
  30095. // Lens flares
  30096. serializationObject.lensFlareSystems = [];
  30097. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30098. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30099. }
  30100. // Shadows
  30101. serializationObject.shadowGenerators = [];
  30102. for (index = 0; index < scene.lights.length; index++) {
  30103. light = scene.lights[index];
  30104. if (light.getShadowGenerator()) {
  30105. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30106. }
  30107. }
  30108. return serializationObject;
  30109. };
  30110. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30111. if (withParents === void 0) { withParents = false; }
  30112. if (withChildren === void 0) { withChildren = false; }
  30113. var serializationObject = {};
  30114. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30115. if (withParents || withChildren) {
  30116. //deliberate for loop! not for each, appended should be processed as well.
  30117. for (var i = 0; i < toSerialize.length; ++i) {
  30118. if (withChildren) {
  30119. toSerialize[i].getDescendants().forEach(function (node) {
  30120. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30121. toSerialize.push(node);
  30122. }
  30123. });
  30124. }
  30125. //make sure the array doesn't contain the object already
  30126. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30127. toSerialize.push(toSerialize[i].parent);
  30128. }
  30129. }
  30130. }
  30131. toSerialize.forEach(function (mesh) {
  30132. finalizeSingleMesh(mesh, serializationObject);
  30133. });
  30134. return serializationObject;
  30135. };
  30136. return SceneSerializer;
  30137. })();
  30138. BABYLON.SceneSerializer = SceneSerializer;
  30139. })(BABYLON || (BABYLON = {}));
  30140. var BABYLON;
  30141. (function (BABYLON) {
  30142. // Unique ID when we import meshes from Babylon to CSG
  30143. var currentCSGMeshId = 0;
  30144. // # class Vertex
  30145. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30146. // one to provide additional features like texture coordinates and vertex
  30147. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30148. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30149. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30150. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30151. // is not used anywhere else.
  30152. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30153. var Vertex = (function () {
  30154. function Vertex(pos, normal, uv) {
  30155. this.pos = pos;
  30156. this.normal = normal;
  30157. this.uv = uv;
  30158. }
  30159. Vertex.prototype.clone = function () {
  30160. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30161. };
  30162. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30163. // orientation of a polygon is flipped.
  30164. Vertex.prototype.flip = function () {
  30165. this.normal = this.normal.scale(-1);
  30166. };
  30167. // Create a new vertex between this vertex and `other` by linearly
  30168. // interpolating all properties using a parameter of `t`. Subclasses should
  30169. // override this to interpolate additional properties.
  30170. Vertex.prototype.interpolate = function (other, t) {
  30171. 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));
  30172. };
  30173. return Vertex;
  30174. })();
  30175. // # class Plane
  30176. // Represents a plane in 3D space.
  30177. var Plane = (function () {
  30178. function Plane(normal, w) {
  30179. this.normal = normal;
  30180. this.w = w;
  30181. }
  30182. Plane.FromPoints = function (a, b, c) {
  30183. var v0 = c.subtract(a);
  30184. var v1 = b.subtract(a);
  30185. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30186. return null;
  30187. }
  30188. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30189. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30190. };
  30191. Plane.prototype.clone = function () {
  30192. return new Plane(this.normal.clone(), this.w);
  30193. };
  30194. Plane.prototype.flip = function () {
  30195. this.normal.scaleInPlace(-1);
  30196. this.w = -this.w;
  30197. };
  30198. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30199. // fragments in the appropriate lists. Coplanar polygons go into either
  30200. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30201. // respect to this plane. Polygons in front or in back of this plane go into
  30202. // either `front` or `back`.
  30203. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30204. var COPLANAR = 0;
  30205. var FRONT = 1;
  30206. var BACK = 2;
  30207. var SPANNING = 3;
  30208. // Classify each point as well as the entire polygon into one of the above
  30209. // four classes.
  30210. var polygonType = 0;
  30211. var types = [];
  30212. var i;
  30213. var t;
  30214. for (i = 0; i < polygon.vertices.length; i++) {
  30215. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30216. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30217. polygonType |= type;
  30218. types.push(type);
  30219. }
  30220. // Put the polygon in the correct list, splitting it when necessary.
  30221. switch (polygonType) {
  30222. case COPLANAR:
  30223. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30224. break;
  30225. case FRONT:
  30226. front.push(polygon);
  30227. break;
  30228. case BACK:
  30229. back.push(polygon);
  30230. break;
  30231. case SPANNING:
  30232. var f = [], b = [];
  30233. for (i = 0; i < polygon.vertices.length; i++) {
  30234. var j = (i + 1) % polygon.vertices.length;
  30235. var ti = types[i], tj = types[j];
  30236. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30237. if (ti !== BACK)
  30238. f.push(vi);
  30239. if (ti !== FRONT)
  30240. b.push(ti !== BACK ? vi.clone() : vi);
  30241. if ((ti | tj) === SPANNING) {
  30242. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30243. var v = vi.interpolate(vj, t);
  30244. f.push(v);
  30245. b.push(v.clone());
  30246. }
  30247. }
  30248. var poly;
  30249. if (f.length >= 3) {
  30250. poly = new Polygon(f, polygon.shared);
  30251. if (poly.plane)
  30252. front.push(poly);
  30253. }
  30254. if (b.length >= 3) {
  30255. poly = new Polygon(b, polygon.shared);
  30256. if (poly.plane)
  30257. back.push(poly);
  30258. }
  30259. break;
  30260. }
  30261. };
  30262. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30263. // point is on the plane.
  30264. Plane.EPSILON = 1e-5;
  30265. return Plane;
  30266. })();
  30267. // # class Polygon
  30268. // Represents a convex polygon. The vertices used to initialize a polygon must
  30269. // be coplanar and form a convex loop.
  30270. //
  30271. // Each convex polygon has a `shared` property, which is shared between all
  30272. // polygons that are clones of each other or were split from the same polygon.
  30273. // This can be used to define per-polygon properties (such as surface color).
  30274. var Polygon = (function () {
  30275. function Polygon(vertices, shared) {
  30276. this.vertices = vertices;
  30277. this.shared = shared;
  30278. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30279. }
  30280. Polygon.prototype.clone = function () {
  30281. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30282. return new Polygon(vertices, this.shared);
  30283. };
  30284. Polygon.prototype.flip = function () {
  30285. this.vertices.reverse().map(function (v) { v.flip(); });
  30286. this.plane.flip();
  30287. };
  30288. return Polygon;
  30289. })();
  30290. // # class Node
  30291. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30292. // by picking a polygon to split along. That polygon (and all other coplanar
  30293. // polygons) are added directly to that node and the other polygons are added to
  30294. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30295. // no distinction between internal and leaf nodes.
  30296. var Node = (function () {
  30297. function Node(polygons) {
  30298. this.plane = null;
  30299. this.front = null;
  30300. this.back = null;
  30301. this.polygons = [];
  30302. if (polygons) {
  30303. this.build(polygons);
  30304. }
  30305. }
  30306. Node.prototype.clone = function () {
  30307. var node = new Node();
  30308. node.plane = this.plane && this.plane.clone();
  30309. node.front = this.front && this.front.clone();
  30310. node.back = this.back && this.back.clone();
  30311. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30312. return node;
  30313. };
  30314. // Convert solid space to empty space and empty space to solid space.
  30315. Node.prototype.invert = function () {
  30316. for (var i = 0; i < this.polygons.length; i++) {
  30317. this.polygons[i].flip();
  30318. }
  30319. if (this.plane) {
  30320. this.plane.flip();
  30321. }
  30322. if (this.front) {
  30323. this.front.invert();
  30324. }
  30325. if (this.back) {
  30326. this.back.invert();
  30327. }
  30328. var temp = this.front;
  30329. this.front = this.back;
  30330. this.back = temp;
  30331. };
  30332. // Recursively remove all polygons in `polygons` that are inside this BSP
  30333. // tree.
  30334. Node.prototype.clipPolygons = function (polygons) {
  30335. if (!this.plane)
  30336. return polygons.slice();
  30337. var front = [], back = [];
  30338. for (var i = 0; i < polygons.length; i++) {
  30339. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30340. }
  30341. if (this.front) {
  30342. front = this.front.clipPolygons(front);
  30343. }
  30344. if (this.back) {
  30345. back = this.back.clipPolygons(back);
  30346. }
  30347. else {
  30348. back = [];
  30349. }
  30350. return front.concat(back);
  30351. };
  30352. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30353. // `bsp`.
  30354. Node.prototype.clipTo = function (bsp) {
  30355. this.polygons = bsp.clipPolygons(this.polygons);
  30356. if (this.front)
  30357. this.front.clipTo(bsp);
  30358. if (this.back)
  30359. this.back.clipTo(bsp);
  30360. };
  30361. // Return a list of all polygons in this BSP tree.
  30362. Node.prototype.allPolygons = function () {
  30363. var polygons = this.polygons.slice();
  30364. if (this.front)
  30365. polygons = polygons.concat(this.front.allPolygons());
  30366. if (this.back)
  30367. polygons = polygons.concat(this.back.allPolygons());
  30368. return polygons;
  30369. };
  30370. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30371. // new polygons are filtered down to the bottom of the tree and become new
  30372. // nodes there. Each set of polygons is partitioned using the first polygon
  30373. // (no heuristic is used to pick a good split).
  30374. Node.prototype.build = function (polygons) {
  30375. if (!polygons.length)
  30376. return;
  30377. if (!this.plane)
  30378. this.plane = polygons[0].plane.clone();
  30379. var front = [], back = [];
  30380. for (var i = 0; i < polygons.length; i++) {
  30381. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30382. }
  30383. if (front.length) {
  30384. if (!this.front)
  30385. this.front = new Node();
  30386. this.front.build(front);
  30387. }
  30388. if (back.length) {
  30389. if (!this.back)
  30390. this.back = new Node();
  30391. this.back.build(back);
  30392. }
  30393. };
  30394. return Node;
  30395. })();
  30396. var CSG = (function () {
  30397. function CSG() {
  30398. this.polygons = new Array();
  30399. }
  30400. // Convert BABYLON.Mesh to BABYLON.CSG
  30401. CSG.FromMesh = function (mesh) {
  30402. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30403. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30404. if (mesh instanceof BABYLON.Mesh) {
  30405. mesh.computeWorldMatrix(true);
  30406. matrix = mesh.getWorldMatrix();
  30407. meshPosition = mesh.position.clone();
  30408. meshRotation = mesh.rotation.clone();
  30409. if (mesh.rotationQuaternion) {
  30410. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30411. }
  30412. meshScaling = mesh.scaling.clone();
  30413. }
  30414. else {
  30415. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30416. }
  30417. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30418. var subMeshes = mesh.subMeshes;
  30419. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30420. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30421. vertices = [];
  30422. for (var j = 0; j < 3; j++) {
  30423. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30424. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30425. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30426. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30427. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30428. vertex = new Vertex(position, normal, uv);
  30429. vertices.push(vertex);
  30430. }
  30431. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30432. // To handle the case of degenerated triangle
  30433. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30434. if (polygon.plane)
  30435. polygons.push(polygon);
  30436. }
  30437. }
  30438. var csg = CSG.FromPolygons(polygons);
  30439. csg.matrix = matrix;
  30440. csg.position = meshPosition;
  30441. csg.rotation = meshRotation;
  30442. csg.scaling = meshScaling;
  30443. csg.rotationQuaternion = meshRotationQuaternion;
  30444. currentCSGMeshId++;
  30445. return csg;
  30446. };
  30447. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30448. CSG.FromPolygons = function (polygons) {
  30449. var csg = new CSG();
  30450. csg.polygons = polygons;
  30451. return csg;
  30452. };
  30453. CSG.prototype.clone = function () {
  30454. var csg = new CSG();
  30455. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30456. csg.copyTransformAttributes(this);
  30457. return csg;
  30458. };
  30459. CSG.prototype.toPolygons = function () {
  30460. return this.polygons;
  30461. };
  30462. CSG.prototype.union = function (csg) {
  30463. var a = new Node(this.clone().polygons);
  30464. var b = new Node(csg.clone().polygons);
  30465. a.clipTo(b);
  30466. b.clipTo(a);
  30467. b.invert();
  30468. b.clipTo(a);
  30469. b.invert();
  30470. a.build(b.allPolygons());
  30471. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30472. };
  30473. CSG.prototype.unionInPlace = function (csg) {
  30474. var a = new Node(this.polygons);
  30475. var b = new Node(csg.polygons);
  30476. a.clipTo(b);
  30477. b.clipTo(a);
  30478. b.invert();
  30479. b.clipTo(a);
  30480. b.invert();
  30481. a.build(b.allPolygons());
  30482. this.polygons = a.allPolygons();
  30483. };
  30484. CSG.prototype.subtract = function (csg) {
  30485. var a = new Node(this.clone().polygons);
  30486. var b = new Node(csg.clone().polygons);
  30487. a.invert();
  30488. a.clipTo(b);
  30489. b.clipTo(a);
  30490. b.invert();
  30491. b.clipTo(a);
  30492. b.invert();
  30493. a.build(b.allPolygons());
  30494. a.invert();
  30495. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30496. };
  30497. CSG.prototype.subtractInPlace = function (csg) {
  30498. var a = new Node(this.polygons);
  30499. var b = new Node(csg.polygons);
  30500. a.invert();
  30501. a.clipTo(b);
  30502. b.clipTo(a);
  30503. b.invert();
  30504. b.clipTo(a);
  30505. b.invert();
  30506. a.build(b.allPolygons());
  30507. a.invert();
  30508. this.polygons = a.allPolygons();
  30509. };
  30510. CSG.prototype.intersect = function (csg) {
  30511. var a = new Node(this.clone().polygons);
  30512. var b = new Node(csg.clone().polygons);
  30513. a.invert();
  30514. b.clipTo(a);
  30515. b.invert();
  30516. a.clipTo(b);
  30517. b.clipTo(a);
  30518. a.build(b.allPolygons());
  30519. a.invert();
  30520. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30521. };
  30522. CSG.prototype.intersectInPlace = function (csg) {
  30523. var a = new Node(this.polygons);
  30524. var b = new Node(csg.polygons);
  30525. a.invert();
  30526. b.clipTo(a);
  30527. b.invert();
  30528. a.clipTo(b);
  30529. b.clipTo(a);
  30530. a.build(b.allPolygons());
  30531. a.invert();
  30532. this.polygons = a.allPolygons();
  30533. };
  30534. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30535. // not modified.
  30536. CSG.prototype.inverse = function () {
  30537. var csg = this.clone();
  30538. csg.inverseInPlace();
  30539. return csg;
  30540. };
  30541. CSG.prototype.inverseInPlace = function () {
  30542. this.polygons.map(function (p) { p.flip(); });
  30543. };
  30544. // This is used to keep meshes transformations so they can be restored
  30545. // when we build back a Babylon Mesh
  30546. // NB : All CSG operations are performed in world coordinates
  30547. CSG.prototype.copyTransformAttributes = function (csg) {
  30548. this.matrix = csg.matrix;
  30549. this.position = csg.position;
  30550. this.rotation = csg.rotation;
  30551. this.scaling = csg.scaling;
  30552. this.rotationQuaternion = csg.rotationQuaternion;
  30553. return this;
  30554. };
  30555. // Build Raw mesh from CSG
  30556. // Coordinates here are in world space
  30557. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30558. var matrix = this.matrix.clone();
  30559. matrix.invert();
  30560. 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;
  30561. if (keepSubMeshes) {
  30562. // Sort Polygons, since subMeshes are indices range
  30563. polygons.sort(function (a, b) {
  30564. if (a.shared.meshId === b.shared.meshId) {
  30565. return a.shared.subMeshId - b.shared.subMeshId;
  30566. }
  30567. else {
  30568. return a.shared.meshId - b.shared.meshId;
  30569. }
  30570. });
  30571. }
  30572. for (var i = 0, il = polygons.length; i < il; i++) {
  30573. polygon = polygons[i];
  30574. // Building SubMeshes
  30575. if (!subMesh_dict[polygon.shared.meshId]) {
  30576. subMesh_dict[polygon.shared.meshId] = {};
  30577. }
  30578. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30579. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30580. indexStart: +Infinity,
  30581. indexEnd: -Infinity,
  30582. materialIndex: polygon.shared.materialIndex
  30583. };
  30584. }
  30585. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30586. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30587. polygonIndices[0] = 0;
  30588. polygonIndices[1] = j - 1;
  30589. polygonIndices[2] = j;
  30590. for (var k = 0; k < 3; k++) {
  30591. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30592. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30593. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30594. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30595. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30596. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30597. // Check if 2 points can be merged
  30598. if (!(typeof vertex_idx !== 'undefined' &&
  30599. normals[vertex_idx * 3] === localNormal.x &&
  30600. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30601. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30602. uvs[vertex_idx * 2] === uv.x &&
  30603. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30604. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30605. uvs.push(uv.x, uv.y);
  30606. normals.push(normal.x, normal.y, normal.z);
  30607. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30608. }
  30609. indices.push(vertex_idx);
  30610. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30611. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30612. currentIndex++;
  30613. }
  30614. }
  30615. }
  30616. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30617. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30618. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30619. mesh.setIndices(indices);
  30620. if (keepSubMeshes) {
  30621. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30622. var materialIndexOffset = 0, materialMaxIndex;
  30623. mesh.subMeshes = new Array();
  30624. for (var m in subMesh_dict) {
  30625. materialMaxIndex = -1;
  30626. for (var sm in subMesh_dict[m]) {
  30627. subMesh_obj = subMesh_dict[m][sm];
  30628. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30629. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30630. }
  30631. materialIndexOffset += ++materialMaxIndex;
  30632. }
  30633. }
  30634. return mesh;
  30635. };
  30636. // Build Mesh from CSG taking material and transforms into account
  30637. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30638. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30639. mesh.material = material;
  30640. mesh.position.copyFrom(this.position);
  30641. mesh.rotation.copyFrom(this.rotation);
  30642. if (this.rotationQuaternion) {
  30643. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30644. }
  30645. mesh.scaling.copyFrom(this.scaling);
  30646. mesh.computeWorldMatrix(true);
  30647. return mesh;
  30648. };
  30649. return CSG;
  30650. })();
  30651. BABYLON.CSG = CSG;
  30652. })(BABYLON || (BABYLON = {}));
  30653. var BABYLON;
  30654. (function (BABYLON) {
  30655. var VRDistortionCorrectionPostProcess = (function (_super) {
  30656. __extends(VRDistortionCorrectionPostProcess, _super);
  30657. //ANY
  30658. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30659. var _this = this;
  30660. _super.call(this, name, "vrDistortionCorrection", [
  30661. 'LensCenter',
  30662. 'Scale',
  30663. 'ScaleIn',
  30664. 'HmdWarpParam'
  30665. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30666. this._isRightEye = isRightEye;
  30667. this._distortionFactors = vrMetrics.distortionK;
  30668. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30669. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30670. this.onSizeChanged = function () {
  30671. _this.aspectRatio = _this.width * .5 / _this.height;
  30672. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30673. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30674. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30675. };
  30676. this.onApply = function (effect) {
  30677. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30678. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30679. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30680. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30681. };
  30682. }
  30683. return VRDistortionCorrectionPostProcess;
  30684. })(BABYLON.PostProcess);
  30685. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30686. })(BABYLON || (BABYLON = {}));
  30687. // Mainly based on these 2 articles :
  30688. // 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
  30689. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30690. var BABYLON;
  30691. (function (BABYLON) {
  30692. (function (JoystickAxis) {
  30693. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30694. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30695. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30696. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30697. var JoystickAxis = BABYLON.JoystickAxis;
  30698. var VirtualJoystick = (function () {
  30699. function VirtualJoystick(leftJoystick) {
  30700. var _this = this;
  30701. if (leftJoystick) {
  30702. this._leftJoystick = true;
  30703. }
  30704. else {
  30705. this._leftJoystick = false;
  30706. }
  30707. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30708. VirtualJoystick._globalJoystickIndex++;
  30709. // By default left & right arrow keys are moving the X
  30710. // and up & down keys are moving the Y
  30711. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30712. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30713. this.reverseLeftRight = false;
  30714. this.reverseUpDown = false;
  30715. // collections of pointers
  30716. this._touches = new BABYLON.SmartCollection();
  30717. this.deltaPosition = BABYLON.Vector3.Zero();
  30718. this._joystickSensibility = 25;
  30719. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30720. this._rotationSpeed = 25;
  30721. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30722. this._rotateOnAxisRelativeToMesh = false;
  30723. this._onResize = function (evt) {
  30724. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30725. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30726. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30727. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30728. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30729. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30730. };
  30731. // injecting a canvas element on top of the canvas 3D game
  30732. if (!VirtualJoystick.vjCanvas) {
  30733. window.addEventListener("resize", this._onResize, false);
  30734. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30735. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30736. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30737. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30738. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30739. VirtualJoystick.vjCanvas.style.width = "100%";
  30740. VirtualJoystick.vjCanvas.style.height = "100%";
  30741. VirtualJoystick.vjCanvas.style.position = "absolute";
  30742. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30743. VirtualJoystick.vjCanvas.style.top = "0px";
  30744. VirtualJoystick.vjCanvas.style.left = "0px";
  30745. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30746. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30747. // Support for jQuery PEP polyfill
  30748. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30749. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30750. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30751. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30752. document.body.appendChild(VirtualJoystick.vjCanvas);
  30753. }
  30754. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30755. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30756. this.pressed = false;
  30757. // default joystick color
  30758. this._joystickColor = "cyan";
  30759. this._joystickPointerID = -1;
  30760. // current joystick position
  30761. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30762. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30763. // origin joystick position
  30764. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30765. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30766. this._onPointerDownHandlerRef = function (evt) {
  30767. _this._onPointerDown(evt);
  30768. };
  30769. this._onPointerMoveHandlerRef = function (evt) {
  30770. _this._onPointerMove(evt);
  30771. };
  30772. this._onPointerOutHandlerRef = function (evt) {
  30773. _this._onPointerUp(evt);
  30774. };
  30775. this._onPointerUpHandlerRef = function (evt) {
  30776. _this._onPointerUp(evt);
  30777. };
  30778. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30779. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30780. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30781. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30782. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30783. evt.preventDefault(); // Disables system menu
  30784. }, false);
  30785. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30786. }
  30787. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30788. this._joystickSensibility = newJoystickSensibility;
  30789. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30790. };
  30791. VirtualJoystick.prototype._onPointerDown = function (e) {
  30792. var positionOnScreenCondition;
  30793. e.preventDefault();
  30794. if (this._leftJoystick === true) {
  30795. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30796. }
  30797. else {
  30798. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30799. }
  30800. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30801. // First contact will be dedicated to the virtual joystick
  30802. this._joystickPointerID = e.pointerId;
  30803. this._joystickPointerStartPos.x = e.clientX;
  30804. this._joystickPointerStartPos.y = e.clientY;
  30805. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30806. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30807. this._deltaJoystickVector.x = 0;
  30808. this._deltaJoystickVector.y = 0;
  30809. this.pressed = true;
  30810. this._touches.add(e.pointerId.toString(), e);
  30811. }
  30812. else {
  30813. // You can only trigger the action buttons with a joystick declared
  30814. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30815. this._action();
  30816. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30817. }
  30818. }
  30819. };
  30820. VirtualJoystick.prototype._onPointerMove = function (e) {
  30821. // If the current pointer is the one associated to the joystick (first touch contact)
  30822. if (this._joystickPointerID == e.pointerId) {
  30823. this._joystickPointerPos.x = e.clientX;
  30824. this._joystickPointerPos.y = e.clientY;
  30825. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30826. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30827. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30828. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30829. switch (this._axisTargetedByLeftAndRight) {
  30830. case JoystickAxis.X:
  30831. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30832. break;
  30833. case JoystickAxis.Y:
  30834. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30835. break;
  30836. case JoystickAxis.Z:
  30837. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30838. break;
  30839. }
  30840. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30841. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30842. switch (this._axisTargetedByUpAndDown) {
  30843. case JoystickAxis.X:
  30844. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30845. break;
  30846. case JoystickAxis.Y:
  30847. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30848. break;
  30849. case JoystickAxis.Z:
  30850. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30851. break;
  30852. }
  30853. }
  30854. else {
  30855. if (this._touches.item(e.pointerId.toString())) {
  30856. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30857. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30858. }
  30859. }
  30860. };
  30861. VirtualJoystick.prototype._onPointerUp = function (e) {
  30862. if (this._joystickPointerID == e.pointerId) {
  30863. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30864. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30865. this._joystickPointerID = -1;
  30866. this.pressed = false;
  30867. }
  30868. else {
  30869. var touch = this._touches.item(e.pointerId.toString());
  30870. if (touch) {
  30871. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30872. }
  30873. }
  30874. this._deltaJoystickVector.x = 0;
  30875. this._deltaJoystickVector.y = 0;
  30876. this._touches.remove(e.pointerId.toString());
  30877. };
  30878. /**
  30879. * Change the color of the virtual joystick
  30880. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30881. */
  30882. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30883. this._joystickColor = newColor;
  30884. };
  30885. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30886. this._action = action;
  30887. };
  30888. // Define which axis you'd like to control for left & right
  30889. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30890. switch (axis) {
  30891. case JoystickAxis.X:
  30892. case JoystickAxis.Y:
  30893. case JoystickAxis.Z:
  30894. this._axisTargetedByLeftAndRight = axis;
  30895. break;
  30896. default:
  30897. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30898. break;
  30899. }
  30900. };
  30901. // Define which axis you'd like to control for up & down
  30902. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30903. switch (axis) {
  30904. case JoystickAxis.X:
  30905. case JoystickAxis.Y:
  30906. case JoystickAxis.Z:
  30907. this._axisTargetedByUpAndDown = axis;
  30908. break;
  30909. default:
  30910. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30911. break;
  30912. }
  30913. };
  30914. VirtualJoystick.prototype._clearCanvas = function () {
  30915. if (this._leftJoystick) {
  30916. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30917. }
  30918. else {
  30919. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30920. }
  30921. };
  30922. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30923. var _this = this;
  30924. if (this.pressed) {
  30925. this._touches.forEach(function (touch) {
  30926. if (touch.pointerId === _this._joystickPointerID) {
  30927. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30928. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30929. VirtualJoystick.vjCanvasContext.beginPath();
  30930. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30931. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30932. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30933. VirtualJoystick.vjCanvasContext.stroke();
  30934. VirtualJoystick.vjCanvasContext.closePath();
  30935. VirtualJoystick.vjCanvasContext.beginPath();
  30936. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30937. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30938. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30939. VirtualJoystick.vjCanvasContext.stroke();
  30940. VirtualJoystick.vjCanvasContext.closePath();
  30941. VirtualJoystick.vjCanvasContext.beginPath();
  30942. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30943. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30944. VirtualJoystick.vjCanvasContext.stroke();
  30945. VirtualJoystick.vjCanvasContext.closePath();
  30946. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30947. }
  30948. else {
  30949. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30950. VirtualJoystick.vjCanvasContext.beginPath();
  30951. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30952. VirtualJoystick.vjCanvasContext.beginPath();
  30953. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30954. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30955. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30956. VirtualJoystick.vjCanvasContext.stroke();
  30957. VirtualJoystick.vjCanvasContext.closePath();
  30958. touch.prevX = touch.x;
  30959. touch.prevY = touch.y;
  30960. }
  30961. ;
  30962. });
  30963. }
  30964. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30965. };
  30966. VirtualJoystick.prototype.releaseCanvas = function () {
  30967. if (VirtualJoystick.vjCanvas) {
  30968. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30969. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30970. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30971. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30972. window.removeEventListener("resize", this._onResize);
  30973. document.body.removeChild(VirtualJoystick.vjCanvas);
  30974. VirtualJoystick.vjCanvas = null;
  30975. }
  30976. };
  30977. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30978. VirtualJoystick._globalJoystickIndex = 0;
  30979. return VirtualJoystick;
  30980. })();
  30981. BABYLON.VirtualJoystick = VirtualJoystick;
  30982. })(BABYLON || (BABYLON = {}));
  30983. var BABYLON;
  30984. (function (BABYLON) {
  30985. // We're mainly based on the logic defined into the FreeCamera code
  30986. var VirtualJoysticksCamera = (function (_super) {
  30987. __extends(VirtualJoysticksCamera, _super);
  30988. function VirtualJoysticksCamera(name, position, scene) {
  30989. _super.call(this, name, position, scene);
  30990. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30991. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30992. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30993. this._leftjoystick.setJoystickSensibility(0.15);
  30994. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30995. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30996. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30997. this._rightjoystick.reverseUpDown = true;
  30998. this._rightjoystick.setJoystickSensibility(0.05);
  30999. this._rightjoystick.setJoystickColor("yellow");
  31000. }
  31001. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31002. return this._leftjoystick;
  31003. };
  31004. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31005. return this._rightjoystick;
  31006. };
  31007. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31008. var speed = this._computeLocalCameraSpeed() * 50;
  31009. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31010. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31011. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31012. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31013. if (!this._leftjoystick.pressed) {
  31014. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31015. }
  31016. if (!this._rightjoystick.pressed) {
  31017. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31018. }
  31019. _super.prototype._checkInputs.call(this);
  31020. };
  31021. VirtualJoysticksCamera.prototype.dispose = function () {
  31022. this._leftjoystick.releaseCanvas();
  31023. _super.prototype.dispose.call(this);
  31024. };
  31025. return VirtualJoysticksCamera;
  31026. })(BABYLON.FreeCamera);
  31027. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31028. })(BABYLON || (BABYLON = {}));
  31029. var BABYLON;
  31030. (function (BABYLON) {
  31031. var AnaglyphPostProcess = (function (_super) {
  31032. __extends(AnaglyphPostProcess, _super);
  31033. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31034. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31035. }
  31036. return AnaglyphPostProcess;
  31037. })(BABYLON.PostProcess);
  31038. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31039. })(BABYLON || (BABYLON = {}));
  31040. var BABYLON;
  31041. (function (BABYLON) {
  31042. var OutlineRenderer = (function () {
  31043. function OutlineRenderer(scene) {
  31044. this._scene = scene;
  31045. }
  31046. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31047. var _this = this;
  31048. if (useOverlay === void 0) { useOverlay = false; }
  31049. var scene = this._scene;
  31050. var engine = this._scene.getEngine();
  31051. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31052. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31053. return;
  31054. }
  31055. var mesh = subMesh.getRenderingMesh();
  31056. var material = subMesh.getMaterial();
  31057. engine.enableEffect(this._effect);
  31058. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31059. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31060. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31061. // Bones
  31062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31063. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31064. }
  31065. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31066. // Alpha test
  31067. if (material && material.needAlphaTesting()) {
  31068. var alphaTexture = material.getAlphaTestTexture();
  31069. this._effect.setTexture("diffuseSampler", alphaTexture);
  31070. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31071. }
  31072. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31073. };
  31074. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31075. var defines = [];
  31076. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31077. var mesh = subMesh.getMesh();
  31078. var material = subMesh.getMaterial();
  31079. // Alpha test
  31080. if (material && material.needAlphaTesting()) {
  31081. defines.push("#define ALPHATEST");
  31082. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31083. attribs.push(BABYLON.VertexBuffer.UVKind);
  31084. defines.push("#define UV1");
  31085. }
  31086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31088. defines.push("#define UV2");
  31089. }
  31090. }
  31091. // Bones
  31092. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31095. if (mesh.numBoneInfluencers > 4) {
  31096. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31097. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31098. }
  31099. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31101. }
  31102. else {
  31103. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31104. }
  31105. // Instances
  31106. if (useInstances) {
  31107. defines.push("#define INSTANCES");
  31108. attribs.push("world0");
  31109. attribs.push("world1");
  31110. attribs.push("world2");
  31111. attribs.push("world3");
  31112. }
  31113. // Get correct effect
  31114. var join = defines.join("\n");
  31115. if (this._cachedDefines !== join) {
  31116. this._cachedDefines = join;
  31117. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31118. }
  31119. return this._effect.isReady();
  31120. };
  31121. return OutlineRenderer;
  31122. })();
  31123. BABYLON.OutlineRenderer = OutlineRenderer;
  31124. })(BABYLON || (BABYLON = {}));
  31125. var BABYLON;
  31126. (function (BABYLON) {
  31127. var MeshAssetTask = (function () {
  31128. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31129. this.name = name;
  31130. this.meshesNames = meshesNames;
  31131. this.rootUrl = rootUrl;
  31132. this.sceneFilename = sceneFilename;
  31133. this.isCompleted = false;
  31134. }
  31135. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31136. var _this = this;
  31137. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31138. _this.loadedMeshes = meshes;
  31139. _this.loadedParticleSystems = particleSystems;
  31140. _this.loadedSkeletons = skeletons;
  31141. _this.isCompleted = true;
  31142. if (_this.onSuccess) {
  31143. _this.onSuccess(_this);
  31144. }
  31145. onSuccess();
  31146. }, null, function () {
  31147. if (_this.onError) {
  31148. _this.onError(_this);
  31149. }
  31150. onError();
  31151. });
  31152. };
  31153. return MeshAssetTask;
  31154. })();
  31155. BABYLON.MeshAssetTask = MeshAssetTask;
  31156. var TextFileAssetTask = (function () {
  31157. function TextFileAssetTask(name, url) {
  31158. this.name = name;
  31159. this.url = url;
  31160. this.isCompleted = false;
  31161. }
  31162. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31163. var _this = this;
  31164. BABYLON.Tools.LoadFile(this.url, function (data) {
  31165. _this.text = data;
  31166. _this.isCompleted = true;
  31167. if (_this.onSuccess) {
  31168. _this.onSuccess(_this);
  31169. }
  31170. onSuccess();
  31171. }, null, scene.database, false, function () {
  31172. if (_this.onError) {
  31173. _this.onError(_this);
  31174. }
  31175. onError();
  31176. });
  31177. };
  31178. return TextFileAssetTask;
  31179. })();
  31180. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31181. var BinaryFileAssetTask = (function () {
  31182. function BinaryFileAssetTask(name, url) {
  31183. this.name = name;
  31184. this.url = url;
  31185. this.isCompleted = false;
  31186. }
  31187. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31188. var _this = this;
  31189. BABYLON.Tools.LoadFile(this.url, function (data) {
  31190. _this.data = data;
  31191. _this.isCompleted = true;
  31192. if (_this.onSuccess) {
  31193. _this.onSuccess(_this);
  31194. }
  31195. onSuccess();
  31196. }, null, scene.database, true, function () {
  31197. if (_this.onError) {
  31198. _this.onError(_this);
  31199. }
  31200. onError();
  31201. });
  31202. };
  31203. return BinaryFileAssetTask;
  31204. })();
  31205. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31206. var ImageAssetTask = (function () {
  31207. function ImageAssetTask(name, url) {
  31208. this.name = name;
  31209. this.url = url;
  31210. this.isCompleted = false;
  31211. }
  31212. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31213. var _this = this;
  31214. var img = new Image();
  31215. img.onload = function () {
  31216. _this.image = img;
  31217. _this.isCompleted = true;
  31218. if (_this.onSuccess) {
  31219. _this.onSuccess(_this);
  31220. }
  31221. onSuccess();
  31222. };
  31223. img.onerror = function () {
  31224. if (_this.onError) {
  31225. _this.onError(_this);
  31226. }
  31227. onError();
  31228. };
  31229. img.src = this.url;
  31230. };
  31231. return ImageAssetTask;
  31232. })();
  31233. BABYLON.ImageAssetTask = ImageAssetTask;
  31234. var TextureAssetTask = (function () {
  31235. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31237. this.name = name;
  31238. this.url = url;
  31239. this.noMipmap = noMipmap;
  31240. this.invertY = invertY;
  31241. this.samplingMode = samplingMode;
  31242. this.isCompleted = false;
  31243. }
  31244. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31245. var _this = this;
  31246. var onload = function () {
  31247. _this.isCompleted = true;
  31248. if (_this.onSuccess) {
  31249. _this.onSuccess(_this);
  31250. }
  31251. onSuccess();
  31252. };
  31253. var onerror = function () {
  31254. if (_this.onError) {
  31255. _this.onError(_this);
  31256. }
  31257. onError();
  31258. };
  31259. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31260. };
  31261. return TextureAssetTask;
  31262. })();
  31263. BABYLON.TextureAssetTask = TextureAssetTask;
  31264. var AssetsManager = (function () {
  31265. function AssetsManager(scene) {
  31266. this._tasks = new Array();
  31267. this._waitingTasksCount = 0;
  31268. this.useDefaultLoadingScreen = true;
  31269. this._scene = scene;
  31270. }
  31271. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31272. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31273. this._tasks.push(task);
  31274. return task;
  31275. };
  31276. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31277. var task = new TextFileAssetTask(taskName, url);
  31278. this._tasks.push(task);
  31279. return task;
  31280. };
  31281. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31282. var task = new BinaryFileAssetTask(taskName, url);
  31283. this._tasks.push(task);
  31284. return task;
  31285. };
  31286. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31287. var task = new ImageAssetTask(taskName, url);
  31288. this._tasks.push(task);
  31289. return task;
  31290. };
  31291. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31292. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31293. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31294. this._tasks.push(task);
  31295. return task;
  31296. };
  31297. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31298. this._waitingTasksCount--;
  31299. if (this._waitingTasksCount === 0) {
  31300. if (this.onFinish) {
  31301. this.onFinish(this._tasks);
  31302. }
  31303. this._scene.getEngine().hideLoadingUI();
  31304. }
  31305. };
  31306. AssetsManager.prototype._runTask = function (task) {
  31307. var _this = this;
  31308. task.run(this._scene, function () {
  31309. if (_this.onTaskSuccess) {
  31310. _this.onTaskSuccess(task);
  31311. }
  31312. _this._decreaseWaitingTasksCount();
  31313. }, function () {
  31314. if (_this.onTaskError) {
  31315. _this.onTaskError(task);
  31316. }
  31317. _this._decreaseWaitingTasksCount();
  31318. });
  31319. };
  31320. AssetsManager.prototype.reset = function () {
  31321. this._tasks = new Array();
  31322. return this;
  31323. };
  31324. AssetsManager.prototype.load = function () {
  31325. this._waitingTasksCount = this._tasks.length;
  31326. if (this._waitingTasksCount === 0) {
  31327. if (this.onFinish) {
  31328. this.onFinish(this._tasks);
  31329. }
  31330. return this;
  31331. }
  31332. if (this.useDefaultLoadingScreen) {
  31333. this._scene.getEngine().displayLoadingUI();
  31334. }
  31335. for (var index = 0; index < this._tasks.length; index++) {
  31336. var task = this._tasks[index];
  31337. this._runTask(task);
  31338. }
  31339. return this;
  31340. };
  31341. return AssetsManager;
  31342. })();
  31343. BABYLON.AssetsManager = AssetsManager;
  31344. })(BABYLON || (BABYLON = {}));
  31345. var BABYLON;
  31346. (function (BABYLON) {
  31347. var VRDeviceOrientationFreeCamera = (function (_super) {
  31348. __extends(VRDeviceOrientationFreeCamera, _super);
  31349. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31350. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31351. _super.call(this, name, position, scene);
  31352. this._alpha = 0;
  31353. this._beta = 0;
  31354. this._gamma = 0;
  31355. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31356. metrics.compensateDistortion = compensateDistortion;
  31357. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31358. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31359. }
  31360. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31361. this._alpha = +evt.alpha | 0;
  31362. this._beta = +evt.beta | 0;
  31363. this._gamma = +evt.gamma | 0;
  31364. if (this._gamma < 0) {
  31365. this._gamma = 90 + this._gamma;
  31366. }
  31367. else {
  31368. // Incline it in the correct angle.
  31369. this._gamma = 270 - this._gamma;
  31370. }
  31371. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31372. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31373. this.rotation.z = this._beta / 180.0 * Math.PI;
  31374. };
  31375. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31376. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31377. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31378. };
  31379. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31380. _super.prototype.detachControl.call(this, element);
  31381. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31382. };
  31383. return VRDeviceOrientationFreeCamera;
  31384. })(BABYLON.FreeCamera);
  31385. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31386. })(BABYLON || (BABYLON = {}));
  31387. var BABYLON;
  31388. (function (BABYLON) {
  31389. var WebVRFreeCamera = (function (_super) {
  31390. __extends(WebVRFreeCamera, _super);
  31391. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31392. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31393. _super.call(this, name, position, scene);
  31394. this._hmdDevice = null;
  31395. this._sensorDevice = null;
  31396. this._cacheState = null;
  31397. this._cacheQuaternion = new BABYLON.Quaternion();
  31398. this._cacheRotation = BABYLON.Vector3.Zero();
  31399. this._vrEnabled = false;
  31400. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31401. metrics.compensateDistortion = compensateDistortion;
  31402. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31403. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31404. }
  31405. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31406. var size = devices.length;
  31407. var i = 0;
  31408. // Reset devices.
  31409. this._sensorDevice = null;
  31410. this._hmdDevice = null;
  31411. // Search for a HmdDevice.
  31412. while (i < size && this._hmdDevice === null) {
  31413. if (devices[i] instanceof HMDVRDevice) {
  31414. this._hmdDevice = devices[i];
  31415. }
  31416. i++;
  31417. }
  31418. i = 0;
  31419. while (i < size && this._sensorDevice === null) {
  31420. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31421. this._sensorDevice = devices[i];
  31422. }
  31423. i++;
  31424. }
  31425. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31426. };
  31427. WebVRFreeCamera.prototype._checkInputs = function () {
  31428. if (this._vrEnabled) {
  31429. this._cacheState = this._sensorDevice.getState();
  31430. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31431. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31432. this.rotation.x = -this._cacheRotation.z;
  31433. this.rotation.y = -this._cacheRotation.y;
  31434. this.rotation.z = this._cacheRotation.x;
  31435. }
  31436. _super.prototype._checkInputs.call(this);
  31437. };
  31438. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31439. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31440. if (navigator.getVRDevices) {
  31441. navigator.getVRDevices().then(this._getWebVRDevices);
  31442. }
  31443. else if (navigator.mozGetVRDevices) {
  31444. navigator.mozGetVRDevices(this._getWebVRDevices);
  31445. }
  31446. };
  31447. WebVRFreeCamera.prototype.detachControl = function (element) {
  31448. _super.prototype.detachControl.call(this, element);
  31449. this._vrEnabled = false;
  31450. };
  31451. return WebVRFreeCamera;
  31452. })(BABYLON.FreeCamera);
  31453. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31454. })(BABYLON || (BABYLON = {}));
  31455. var BABYLON;
  31456. (function (BABYLON) {
  31457. // Standard optimizations
  31458. var SceneOptimization = (function () {
  31459. function SceneOptimization(priority) {
  31460. if (priority === void 0) { priority = 0; }
  31461. this.priority = priority;
  31462. this.apply = function (scene) {
  31463. return true; // Return true if everything that can be done was applied
  31464. };
  31465. }
  31466. return SceneOptimization;
  31467. })();
  31468. BABYLON.SceneOptimization = SceneOptimization;
  31469. var TextureOptimization = (function (_super) {
  31470. __extends(TextureOptimization, _super);
  31471. function TextureOptimization(priority, maximumSize) {
  31472. var _this = this;
  31473. if (priority === void 0) { priority = 0; }
  31474. if (maximumSize === void 0) { maximumSize = 1024; }
  31475. _super.call(this, priority);
  31476. this.priority = priority;
  31477. this.maximumSize = maximumSize;
  31478. this.apply = function (scene) {
  31479. var allDone = true;
  31480. for (var index = 0; index < scene.textures.length; index++) {
  31481. var texture = scene.textures[index];
  31482. if (!texture.canRescale) {
  31483. continue;
  31484. }
  31485. var currentSize = texture.getSize();
  31486. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31487. if (maxDimension > _this.maximumSize) {
  31488. texture.scale(0.5);
  31489. allDone = false;
  31490. }
  31491. }
  31492. return allDone;
  31493. };
  31494. }
  31495. return TextureOptimization;
  31496. })(SceneOptimization);
  31497. BABYLON.TextureOptimization = TextureOptimization;
  31498. var HardwareScalingOptimization = (function (_super) {
  31499. __extends(HardwareScalingOptimization, _super);
  31500. function HardwareScalingOptimization(priority, maximumScale) {
  31501. var _this = this;
  31502. if (priority === void 0) { priority = 0; }
  31503. if (maximumScale === void 0) { maximumScale = 2; }
  31504. _super.call(this, priority);
  31505. this.priority = priority;
  31506. this.maximumScale = maximumScale;
  31507. this._currentScale = 1;
  31508. this.apply = function (scene) {
  31509. _this._currentScale++;
  31510. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31511. return _this._currentScale >= _this.maximumScale;
  31512. };
  31513. }
  31514. return HardwareScalingOptimization;
  31515. })(SceneOptimization);
  31516. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31517. var ShadowsOptimization = (function (_super) {
  31518. __extends(ShadowsOptimization, _super);
  31519. function ShadowsOptimization() {
  31520. _super.apply(this, arguments);
  31521. this.apply = function (scene) {
  31522. scene.shadowsEnabled = false;
  31523. return true;
  31524. };
  31525. }
  31526. return ShadowsOptimization;
  31527. })(SceneOptimization);
  31528. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31529. var PostProcessesOptimization = (function (_super) {
  31530. __extends(PostProcessesOptimization, _super);
  31531. function PostProcessesOptimization() {
  31532. _super.apply(this, arguments);
  31533. this.apply = function (scene) {
  31534. scene.postProcessesEnabled = false;
  31535. return true;
  31536. };
  31537. }
  31538. return PostProcessesOptimization;
  31539. })(SceneOptimization);
  31540. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31541. var LensFlaresOptimization = (function (_super) {
  31542. __extends(LensFlaresOptimization, _super);
  31543. function LensFlaresOptimization() {
  31544. _super.apply(this, arguments);
  31545. this.apply = function (scene) {
  31546. scene.lensFlaresEnabled = false;
  31547. return true;
  31548. };
  31549. }
  31550. return LensFlaresOptimization;
  31551. })(SceneOptimization);
  31552. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31553. var ParticlesOptimization = (function (_super) {
  31554. __extends(ParticlesOptimization, _super);
  31555. function ParticlesOptimization() {
  31556. _super.apply(this, arguments);
  31557. this.apply = function (scene) {
  31558. scene.particlesEnabled = false;
  31559. return true;
  31560. };
  31561. }
  31562. return ParticlesOptimization;
  31563. })(SceneOptimization);
  31564. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31565. var RenderTargetsOptimization = (function (_super) {
  31566. __extends(RenderTargetsOptimization, _super);
  31567. function RenderTargetsOptimization() {
  31568. _super.apply(this, arguments);
  31569. this.apply = function (scene) {
  31570. scene.renderTargetsEnabled = false;
  31571. return true;
  31572. };
  31573. }
  31574. return RenderTargetsOptimization;
  31575. })(SceneOptimization);
  31576. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31577. var MergeMeshesOptimization = (function (_super) {
  31578. __extends(MergeMeshesOptimization, _super);
  31579. function MergeMeshesOptimization() {
  31580. var _this = this;
  31581. _super.apply(this, arguments);
  31582. this._canBeMerged = function (abstractMesh) {
  31583. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31584. return false;
  31585. }
  31586. var mesh = abstractMesh;
  31587. if (!mesh.isVisible || !mesh.isEnabled()) {
  31588. return false;
  31589. }
  31590. if (mesh.instances.length > 0) {
  31591. return false;
  31592. }
  31593. if (mesh.skeleton || mesh.hasLODLevels) {
  31594. return false;
  31595. }
  31596. if (mesh.parent) {
  31597. return false;
  31598. }
  31599. return true;
  31600. };
  31601. this.apply = function (scene, updateSelectionTree) {
  31602. var globalPool = scene.meshes.slice(0);
  31603. var globalLength = globalPool.length;
  31604. for (var index = 0; index < globalLength; index++) {
  31605. var currentPool = new Array();
  31606. var current = globalPool[index];
  31607. // Checks
  31608. if (!_this._canBeMerged(current)) {
  31609. continue;
  31610. }
  31611. currentPool.push(current);
  31612. // Find compatible meshes
  31613. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31614. var otherMesh = globalPool[subIndex];
  31615. if (!_this._canBeMerged(otherMesh)) {
  31616. continue;
  31617. }
  31618. if (otherMesh.material !== current.material) {
  31619. continue;
  31620. }
  31621. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31622. continue;
  31623. }
  31624. currentPool.push(otherMesh);
  31625. globalLength--;
  31626. globalPool.splice(subIndex, 1);
  31627. subIndex--;
  31628. }
  31629. if (currentPool.length < 2) {
  31630. continue;
  31631. }
  31632. // Merge meshes
  31633. BABYLON.Mesh.MergeMeshes(currentPool);
  31634. }
  31635. if (updateSelectionTree != undefined) {
  31636. if (updateSelectionTree) {
  31637. scene.createOrUpdateSelectionOctree();
  31638. }
  31639. }
  31640. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31641. scene.createOrUpdateSelectionOctree();
  31642. }
  31643. return true;
  31644. };
  31645. }
  31646. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31647. get: function () {
  31648. return MergeMeshesOptimization._UpdateSelectionTree;
  31649. },
  31650. set: function (value) {
  31651. MergeMeshesOptimization._UpdateSelectionTree = value;
  31652. },
  31653. enumerable: true,
  31654. configurable: true
  31655. });
  31656. MergeMeshesOptimization._UpdateSelectionTree = false;
  31657. return MergeMeshesOptimization;
  31658. })(SceneOptimization);
  31659. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31660. // Options
  31661. var SceneOptimizerOptions = (function () {
  31662. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31663. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31664. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31665. this.targetFrameRate = targetFrameRate;
  31666. this.trackerDuration = trackerDuration;
  31667. this.optimizations = new Array();
  31668. }
  31669. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31670. var result = new SceneOptimizerOptions(targetFrameRate);
  31671. var priority = 0;
  31672. result.optimizations.push(new MergeMeshesOptimization(priority));
  31673. result.optimizations.push(new ShadowsOptimization(priority));
  31674. result.optimizations.push(new LensFlaresOptimization(priority));
  31675. // Next priority
  31676. priority++;
  31677. result.optimizations.push(new PostProcessesOptimization(priority));
  31678. result.optimizations.push(new ParticlesOptimization(priority));
  31679. // Next priority
  31680. priority++;
  31681. result.optimizations.push(new TextureOptimization(priority, 1024));
  31682. return result;
  31683. };
  31684. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31685. var result = new SceneOptimizerOptions(targetFrameRate);
  31686. var priority = 0;
  31687. result.optimizations.push(new MergeMeshesOptimization(priority));
  31688. result.optimizations.push(new ShadowsOptimization(priority));
  31689. result.optimizations.push(new LensFlaresOptimization(priority));
  31690. // Next priority
  31691. priority++;
  31692. result.optimizations.push(new PostProcessesOptimization(priority));
  31693. result.optimizations.push(new ParticlesOptimization(priority));
  31694. // Next priority
  31695. priority++;
  31696. result.optimizations.push(new TextureOptimization(priority, 512));
  31697. // Next priority
  31698. priority++;
  31699. result.optimizations.push(new RenderTargetsOptimization(priority));
  31700. // Next priority
  31701. priority++;
  31702. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31703. return result;
  31704. };
  31705. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31706. var result = new SceneOptimizerOptions(targetFrameRate);
  31707. var priority = 0;
  31708. result.optimizations.push(new MergeMeshesOptimization(priority));
  31709. result.optimizations.push(new ShadowsOptimization(priority));
  31710. result.optimizations.push(new LensFlaresOptimization(priority));
  31711. // Next priority
  31712. priority++;
  31713. result.optimizations.push(new PostProcessesOptimization(priority));
  31714. result.optimizations.push(new ParticlesOptimization(priority));
  31715. // Next priority
  31716. priority++;
  31717. result.optimizations.push(new TextureOptimization(priority, 256));
  31718. // Next priority
  31719. priority++;
  31720. result.optimizations.push(new RenderTargetsOptimization(priority));
  31721. // Next priority
  31722. priority++;
  31723. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31724. return result;
  31725. };
  31726. return SceneOptimizerOptions;
  31727. })();
  31728. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31729. // Scene optimizer tool
  31730. var SceneOptimizer = (function () {
  31731. function SceneOptimizer() {
  31732. }
  31733. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31734. // TODO: add an epsilon
  31735. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31736. if (onSuccess) {
  31737. onSuccess();
  31738. }
  31739. return;
  31740. }
  31741. // Apply current level of optimizations
  31742. var allDone = true;
  31743. var noOptimizationApplied = true;
  31744. for (var index = 0; index < options.optimizations.length; index++) {
  31745. var optimization = options.optimizations[index];
  31746. if (optimization.priority === currentPriorityLevel) {
  31747. noOptimizationApplied = false;
  31748. allDone = allDone && optimization.apply(scene);
  31749. }
  31750. }
  31751. // If no optimization was applied, this is a failure :(
  31752. if (noOptimizationApplied) {
  31753. if (onFailure) {
  31754. onFailure();
  31755. }
  31756. return;
  31757. }
  31758. // If all optimizations were done, move to next level
  31759. if (allDone) {
  31760. currentPriorityLevel++;
  31761. }
  31762. // Let's the system running for a specific amount of time before checking FPS
  31763. scene.executeWhenReady(function () {
  31764. setTimeout(function () {
  31765. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31766. }, options.trackerDuration);
  31767. });
  31768. };
  31769. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31770. if (!options) {
  31771. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31772. }
  31773. // Let's the system running for a specific amount of time before checking FPS
  31774. scene.executeWhenReady(function () {
  31775. setTimeout(function () {
  31776. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31777. }, options.trackerDuration);
  31778. });
  31779. };
  31780. return SceneOptimizer;
  31781. })();
  31782. BABYLON.SceneOptimizer = SceneOptimizer;
  31783. })(BABYLON || (BABYLON = {}));
  31784. var BABYLON;
  31785. (function (BABYLON) {
  31786. var Internals;
  31787. (function (Internals) {
  31788. var MeshLODLevel = (function () {
  31789. function MeshLODLevel(distance, mesh) {
  31790. this.distance = distance;
  31791. this.mesh = mesh;
  31792. }
  31793. return MeshLODLevel;
  31794. })();
  31795. Internals.MeshLODLevel = MeshLODLevel;
  31796. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31797. })(BABYLON || (BABYLON = {}));
  31798. var BABYLON;
  31799. (function (BABYLON) {
  31800. var RawTexture = (function (_super) {
  31801. __extends(RawTexture, _super);
  31802. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31803. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31804. if (invertY === void 0) { invertY = false; }
  31805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31806. _super.call(this, null, scene, !generateMipMaps, invertY);
  31807. this.format = format;
  31808. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31809. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31810. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31811. }
  31812. RawTexture.prototype.update = function (data) {
  31813. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31814. };
  31815. // Statics
  31816. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31817. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31818. if (invertY === void 0) { invertY = false; }
  31819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31820. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31821. };
  31822. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31823. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31824. if (invertY === void 0) { invertY = false; }
  31825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31826. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31827. };
  31828. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31830. if (invertY === void 0) { invertY = false; }
  31831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31832. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31833. };
  31834. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31835. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31836. if (invertY === void 0) { invertY = false; }
  31837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31838. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31839. };
  31840. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31841. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31842. if (invertY === void 0) { invertY = false; }
  31843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31844. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31845. };
  31846. return RawTexture;
  31847. })(BABYLON.Texture);
  31848. BABYLON.RawTexture = RawTexture;
  31849. })(BABYLON || (BABYLON = {}));
  31850. var BABYLON;
  31851. (function (BABYLON) {
  31852. var IndexedVector2 = (function (_super) {
  31853. __extends(IndexedVector2, _super);
  31854. function IndexedVector2(original, index) {
  31855. _super.call(this, original.x, original.y);
  31856. this.index = index;
  31857. }
  31858. return IndexedVector2;
  31859. })(BABYLON.Vector2);
  31860. var PolygonPoints = (function () {
  31861. function PolygonPoints() {
  31862. this.elements = new Array();
  31863. }
  31864. PolygonPoints.prototype.add = function (originalPoints) {
  31865. var _this = this;
  31866. var result = new Array();
  31867. originalPoints.forEach(function (point) {
  31868. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31869. var newPoint = new IndexedVector2(point, _this.elements.length);
  31870. result.push(newPoint);
  31871. _this.elements.push(newPoint);
  31872. }
  31873. });
  31874. return result;
  31875. };
  31876. PolygonPoints.prototype.computeBounds = function () {
  31877. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31878. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31879. this.elements.forEach(function (point) {
  31880. // x
  31881. if (point.x < lmin.x) {
  31882. lmin.x = point.x;
  31883. }
  31884. else if (point.x > lmax.x) {
  31885. lmax.x = point.x;
  31886. }
  31887. // y
  31888. if (point.y < lmin.y) {
  31889. lmin.y = point.y;
  31890. }
  31891. else if (point.y > lmax.y) {
  31892. lmax.y = point.y;
  31893. }
  31894. });
  31895. return {
  31896. min: lmin,
  31897. max: lmax,
  31898. width: lmax.x - lmin.x,
  31899. height: lmax.y - lmin.y
  31900. };
  31901. };
  31902. return PolygonPoints;
  31903. })();
  31904. var Polygon = (function () {
  31905. function Polygon() {
  31906. }
  31907. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31908. return [
  31909. new BABYLON.Vector2(xmin, ymin),
  31910. new BABYLON.Vector2(xmax, ymin),
  31911. new BABYLON.Vector2(xmax, ymax),
  31912. new BABYLON.Vector2(xmin, ymax)
  31913. ];
  31914. };
  31915. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31916. if (cx === void 0) { cx = 0; }
  31917. if (cy === void 0) { cy = 0; }
  31918. if (numberOfSides === void 0) { numberOfSides = 32; }
  31919. var result = new Array();
  31920. var angle = 0;
  31921. var increment = (Math.PI * 2) / numberOfSides;
  31922. for (var i = 0; i < numberOfSides; i++) {
  31923. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31924. angle -= increment;
  31925. }
  31926. return result;
  31927. };
  31928. Polygon.Parse = function (input) {
  31929. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31930. var i, result = [];
  31931. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31932. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31933. }
  31934. return result;
  31935. };
  31936. Polygon.StartingAt = function (x, y) {
  31937. return BABYLON.Path2.StartingAt(x, y);
  31938. };
  31939. return Polygon;
  31940. })();
  31941. BABYLON.Polygon = Polygon;
  31942. var PolygonMeshBuilder = (function () {
  31943. function PolygonMeshBuilder(name, contours, scene) {
  31944. this._points = new PolygonPoints();
  31945. this._outlinepoints = new PolygonPoints();
  31946. this._holes = [];
  31947. if (!("poly2tri" in window)) {
  31948. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31949. }
  31950. this._name = name;
  31951. this._scene = scene;
  31952. var points;
  31953. if (contours instanceof BABYLON.Path2) {
  31954. points = contours.getPoints();
  31955. }
  31956. else {
  31957. points = contours;
  31958. }
  31959. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31960. this._outlinepoints.add(points);
  31961. }
  31962. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31963. this._swctx.addHole(this._points.add(hole));
  31964. var holepoints = new PolygonPoints();
  31965. holepoints.add(hole);
  31966. this._holes.push(holepoints);
  31967. return this;
  31968. };
  31969. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31970. var _this = this;
  31971. if (updatable === void 0) { updatable = false; }
  31972. var result = new BABYLON.Mesh(this._name, this._scene);
  31973. var normals = [];
  31974. var positions = [];
  31975. var uvs = [];
  31976. var bounds = this._points.computeBounds();
  31977. this._points.elements.forEach(function (p) {
  31978. normals.push(0, 1.0, 0);
  31979. positions.push(p.x, 0, p.y);
  31980. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31981. });
  31982. var indices = [];
  31983. this._swctx.triangulate();
  31984. this._swctx.getTriangles().forEach(function (triangle) {
  31985. triangle.getPoints().forEach(function (point) {
  31986. indices.push(point.index);
  31987. });
  31988. });
  31989. if (depth > 0) {
  31990. var positionscount = (positions.length / 3); //get the current pointcount
  31991. this._points.elements.forEach(function (p) {
  31992. normals.push(0, -1.0, 0);
  31993. positions.push(p.x, -depth, p.y);
  31994. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31995. });
  31996. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31997. var p2;
  31998. var poscounter = 0;
  31999. this._swctx.getTriangles().forEach(function (triangle) {
  32000. triangle.getPoints().forEach(function (point) {
  32001. switch (poscounter) {
  32002. case 0:
  32003. p1 = point;
  32004. break;
  32005. case 1:
  32006. p2 = point;
  32007. break;
  32008. case 2:
  32009. indices.push(point.index + positionscount);
  32010. indices.push(p2.index + positionscount);
  32011. indices.push(p1.index + positionscount);
  32012. poscounter = -1;
  32013. break;
  32014. }
  32015. poscounter++;
  32016. //indices.push((<IndexedVector2>point).index + positionscount);
  32017. });
  32018. });
  32019. //Add the sides
  32020. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32021. this._holes.forEach(function (hole) {
  32022. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32023. });
  32024. }
  32025. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32026. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32027. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32028. result.setIndices(indices);
  32029. return result;
  32030. };
  32031. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32032. var StartIndex = positions.length / 3;
  32033. var ulength = 0;
  32034. for (var i = 0; i < points.elements.length; i++) {
  32035. var p = points.elements[i];
  32036. var p1;
  32037. if ((i + 1) > points.elements.length - 1) {
  32038. p1 = points.elements[0];
  32039. }
  32040. else {
  32041. p1 = points.elements[i + 1];
  32042. }
  32043. positions.push(p.x, 0, p.y);
  32044. positions.push(p.x, -depth, p.y);
  32045. positions.push(p1.x, 0, p1.y);
  32046. positions.push(p1.x, -depth, p1.y);
  32047. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32048. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32049. var v3 = v2.subtract(v1);
  32050. var v4 = new BABYLON.Vector3(0, 1, 0);
  32051. var vn = BABYLON.Vector3.Cross(v3, v4);
  32052. vn = vn.normalize();
  32053. uvs.push(ulength / bounds.width, 0);
  32054. uvs.push(ulength / bounds.width, 1);
  32055. ulength += v3.length();
  32056. uvs.push((ulength / bounds.width), 0);
  32057. uvs.push((ulength / bounds.width), 1);
  32058. if (!flip) {
  32059. normals.push(-vn.x, -vn.y, -vn.z);
  32060. normals.push(-vn.x, -vn.y, -vn.z);
  32061. normals.push(-vn.x, -vn.y, -vn.z);
  32062. normals.push(-vn.x, -vn.y, -vn.z);
  32063. indices.push(StartIndex);
  32064. indices.push(StartIndex + 1);
  32065. indices.push(StartIndex + 2);
  32066. indices.push(StartIndex + 1);
  32067. indices.push(StartIndex + 3);
  32068. indices.push(StartIndex + 2);
  32069. }
  32070. else {
  32071. normals.push(vn.x, vn.y, vn.z);
  32072. normals.push(vn.x, vn.y, vn.z);
  32073. normals.push(vn.x, vn.y, vn.z);
  32074. normals.push(vn.x, vn.y, vn.z);
  32075. indices.push(StartIndex);
  32076. indices.push(StartIndex + 2);
  32077. indices.push(StartIndex + 1);
  32078. indices.push(StartIndex + 1);
  32079. indices.push(StartIndex + 2);
  32080. indices.push(StartIndex + 3);
  32081. }
  32082. StartIndex += 4;
  32083. }
  32084. ;
  32085. };
  32086. return PolygonMeshBuilder;
  32087. })();
  32088. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32089. })(BABYLON || (BABYLON = {}));
  32090. var BABYLON;
  32091. (function (BABYLON) {
  32092. var Octree = (function () {
  32093. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32094. if (maxDepth === void 0) { maxDepth = 2; }
  32095. this.maxDepth = maxDepth;
  32096. this.dynamicContent = new Array();
  32097. this._maxBlockCapacity = maxBlockCapacity || 64;
  32098. this._selectionContent = new BABYLON.SmartArray(1024);
  32099. this._creationFunc = creationFunc;
  32100. }
  32101. // Methods
  32102. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32103. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32104. };
  32105. Octree.prototype.addMesh = function (entry) {
  32106. for (var index = 0; index < this.blocks.length; index++) {
  32107. var block = this.blocks[index];
  32108. block.addEntry(entry);
  32109. }
  32110. };
  32111. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32112. this._selectionContent.reset();
  32113. for (var index = 0; index < this.blocks.length; index++) {
  32114. var block = this.blocks[index];
  32115. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32116. }
  32117. if (allowDuplicate) {
  32118. this._selectionContent.concat(this.dynamicContent);
  32119. }
  32120. else {
  32121. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32122. }
  32123. return this._selectionContent;
  32124. };
  32125. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32126. this._selectionContent.reset();
  32127. for (var index = 0; index < this.blocks.length; index++) {
  32128. var block = this.blocks[index];
  32129. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32130. }
  32131. if (allowDuplicate) {
  32132. this._selectionContent.concat(this.dynamicContent);
  32133. }
  32134. else {
  32135. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32136. }
  32137. return this._selectionContent;
  32138. };
  32139. Octree.prototype.intersectsRay = function (ray) {
  32140. this._selectionContent.reset();
  32141. for (var index = 0; index < this.blocks.length; index++) {
  32142. var block = this.blocks[index];
  32143. block.intersectsRay(ray, this._selectionContent);
  32144. }
  32145. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32146. return this._selectionContent;
  32147. };
  32148. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32149. target.blocks = new Array();
  32150. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32151. // Segmenting space
  32152. for (var x = 0; x < 2; x++) {
  32153. for (var y = 0; y < 2; y++) {
  32154. for (var z = 0; z < 2; z++) {
  32155. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32156. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32157. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32158. block.addEntries(entries);
  32159. target.blocks.push(block);
  32160. }
  32161. }
  32162. }
  32163. };
  32164. Octree.CreationFuncForMeshes = function (entry, block) {
  32165. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32166. block.entries.push(entry);
  32167. }
  32168. };
  32169. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32170. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32171. block.entries.push(entry);
  32172. }
  32173. };
  32174. return Octree;
  32175. })();
  32176. BABYLON.Octree = Octree;
  32177. })(BABYLON || (BABYLON = {}));
  32178. var BABYLON;
  32179. (function (BABYLON) {
  32180. var OctreeBlock = (function () {
  32181. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32182. this.entries = new Array();
  32183. this._boundingVectors = new Array();
  32184. this._capacity = capacity;
  32185. this._depth = depth;
  32186. this._maxDepth = maxDepth;
  32187. this._creationFunc = creationFunc;
  32188. this._minPoint = minPoint;
  32189. this._maxPoint = maxPoint;
  32190. this._boundingVectors.push(minPoint.clone());
  32191. this._boundingVectors.push(maxPoint.clone());
  32192. this._boundingVectors.push(minPoint.clone());
  32193. this._boundingVectors[2].x = maxPoint.x;
  32194. this._boundingVectors.push(minPoint.clone());
  32195. this._boundingVectors[3].y = maxPoint.y;
  32196. this._boundingVectors.push(minPoint.clone());
  32197. this._boundingVectors[4].z = maxPoint.z;
  32198. this._boundingVectors.push(maxPoint.clone());
  32199. this._boundingVectors[5].z = minPoint.z;
  32200. this._boundingVectors.push(maxPoint.clone());
  32201. this._boundingVectors[6].x = minPoint.x;
  32202. this._boundingVectors.push(maxPoint.clone());
  32203. this._boundingVectors[7].y = minPoint.y;
  32204. }
  32205. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32206. // Property
  32207. get: function () {
  32208. return this._capacity;
  32209. },
  32210. enumerable: true,
  32211. configurable: true
  32212. });
  32213. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32214. get: function () {
  32215. return this._minPoint;
  32216. },
  32217. enumerable: true,
  32218. configurable: true
  32219. });
  32220. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32221. get: function () {
  32222. return this._maxPoint;
  32223. },
  32224. enumerable: true,
  32225. configurable: true
  32226. });
  32227. // Methods
  32228. OctreeBlock.prototype.addEntry = function (entry) {
  32229. if (this.blocks) {
  32230. for (var index = 0; index < this.blocks.length; index++) {
  32231. var block = this.blocks[index];
  32232. block.addEntry(entry);
  32233. }
  32234. return;
  32235. }
  32236. this._creationFunc(entry, this);
  32237. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32238. this.createInnerBlocks();
  32239. }
  32240. };
  32241. OctreeBlock.prototype.addEntries = function (entries) {
  32242. for (var index = 0; index < entries.length; index++) {
  32243. var mesh = entries[index];
  32244. this.addEntry(mesh);
  32245. }
  32246. };
  32247. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32248. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32249. if (this.blocks) {
  32250. for (var index = 0; index < this.blocks.length; index++) {
  32251. var block = this.blocks[index];
  32252. block.select(frustumPlanes, selection, allowDuplicate);
  32253. }
  32254. return;
  32255. }
  32256. if (allowDuplicate) {
  32257. selection.concat(this.entries);
  32258. }
  32259. else {
  32260. selection.concatWithNoDuplicate(this.entries);
  32261. }
  32262. }
  32263. };
  32264. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32265. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32266. if (this.blocks) {
  32267. for (var index = 0; index < this.blocks.length; index++) {
  32268. var block = this.blocks[index];
  32269. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32270. }
  32271. return;
  32272. }
  32273. if (allowDuplicate) {
  32274. selection.concat(this.entries);
  32275. }
  32276. else {
  32277. selection.concatWithNoDuplicate(this.entries);
  32278. }
  32279. }
  32280. };
  32281. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32282. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32283. if (this.blocks) {
  32284. for (var index = 0; index < this.blocks.length; index++) {
  32285. var block = this.blocks[index];
  32286. block.intersectsRay(ray, selection);
  32287. }
  32288. return;
  32289. }
  32290. selection.concatWithNoDuplicate(this.entries);
  32291. }
  32292. };
  32293. OctreeBlock.prototype.createInnerBlocks = function () {
  32294. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32295. };
  32296. return OctreeBlock;
  32297. })();
  32298. BABYLON.OctreeBlock = OctreeBlock;
  32299. })(BABYLON || (BABYLON = {}));
  32300. var BABYLON;
  32301. (function (BABYLON) {
  32302. var BlurPostProcess = (function (_super) {
  32303. __extends(BlurPostProcess, _super);
  32304. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32305. var _this = this;
  32306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32307. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32308. this.direction = direction;
  32309. this.blurWidth = blurWidth;
  32310. this.onApply = function (effect) {
  32311. effect.setFloat2("screenSize", _this.width, _this.height);
  32312. effect.setVector2("direction", _this.direction);
  32313. effect.setFloat("blurWidth", _this.blurWidth);
  32314. };
  32315. }
  32316. return BlurPostProcess;
  32317. })(BABYLON.PostProcess);
  32318. BABYLON.BlurPostProcess = BlurPostProcess;
  32319. })(BABYLON || (BABYLON = {}));
  32320. var BABYLON;
  32321. (function (BABYLON) {
  32322. var RefractionPostProcess = (function (_super) {
  32323. __extends(RefractionPostProcess, _super);
  32324. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32325. var _this = this;
  32326. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32327. this.color = color;
  32328. this.depth = depth;
  32329. this.colorLevel = colorLevel;
  32330. this.onActivate = function (cam) {
  32331. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32332. };
  32333. this.onApply = function (effect) {
  32334. effect.setColor3("baseColor", _this.color);
  32335. effect.setFloat("depth", _this.depth);
  32336. effect.setFloat("colorLevel", _this.colorLevel);
  32337. effect.setTexture("refractionSampler", _this._refRexture);
  32338. };
  32339. }
  32340. // Methods
  32341. RefractionPostProcess.prototype.dispose = function (camera) {
  32342. if (this._refRexture) {
  32343. this._refRexture.dispose();
  32344. }
  32345. _super.prototype.dispose.call(this, camera);
  32346. };
  32347. return RefractionPostProcess;
  32348. })(BABYLON.PostProcess);
  32349. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32350. })(BABYLON || (BABYLON = {}));
  32351. var BABYLON;
  32352. (function (BABYLON) {
  32353. var BlackAndWhitePostProcess = (function (_super) {
  32354. __extends(BlackAndWhitePostProcess, _super);
  32355. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32356. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32357. }
  32358. return BlackAndWhitePostProcess;
  32359. })(BABYLON.PostProcess);
  32360. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32361. })(BABYLON || (BABYLON = {}));
  32362. var BABYLON;
  32363. (function (BABYLON) {
  32364. var ConvolutionPostProcess = (function (_super) {
  32365. __extends(ConvolutionPostProcess, _super);
  32366. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32367. var _this = this;
  32368. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32369. this.kernel = kernel;
  32370. this.onApply = function (effect) {
  32371. effect.setFloat2("screenSize", _this.width, _this.height);
  32372. effect.setArray("kernel", _this.kernel);
  32373. };
  32374. }
  32375. // Statics
  32376. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32377. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32378. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32379. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32380. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32381. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32382. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32383. return ConvolutionPostProcess;
  32384. })(BABYLON.PostProcess);
  32385. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32386. })(BABYLON || (BABYLON = {}));
  32387. var BABYLON;
  32388. (function (BABYLON) {
  32389. var FilterPostProcess = (function (_super) {
  32390. __extends(FilterPostProcess, _super);
  32391. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32392. var _this = this;
  32393. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32394. this.kernelMatrix = kernelMatrix;
  32395. this.onApply = function (effect) {
  32396. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32397. };
  32398. }
  32399. return FilterPostProcess;
  32400. })(BABYLON.PostProcess);
  32401. BABYLON.FilterPostProcess = FilterPostProcess;
  32402. })(BABYLON || (BABYLON = {}));
  32403. var BABYLON;
  32404. (function (BABYLON) {
  32405. var FxaaPostProcess = (function (_super) {
  32406. __extends(FxaaPostProcess, _super);
  32407. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32408. var _this = this;
  32409. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32410. this.onSizeChanged = function () {
  32411. _this.texelWidth = 1.0 / _this.width;
  32412. _this.texelHeight = 1.0 / _this.height;
  32413. };
  32414. this.onApply = function (effect) {
  32415. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32416. };
  32417. }
  32418. return FxaaPostProcess;
  32419. })(BABYLON.PostProcess);
  32420. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32421. })(BABYLON || (BABYLON = {}));
  32422. var BABYLON;
  32423. (function (BABYLON) {
  32424. var StereoscopicInterlacePostProcess = (function (_super) {
  32425. __extends(StereoscopicInterlacePostProcess, _super);
  32426. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32427. var _this = this;
  32428. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32429. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32430. this.onSizeChanged = function () {
  32431. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32432. };
  32433. this.onApply = function (effect) {
  32434. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32435. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32436. };
  32437. }
  32438. return StereoscopicInterlacePostProcess;
  32439. })(BABYLON.PostProcess);
  32440. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32441. })(BABYLON || (BABYLON = {}));
  32442. var BABYLON;
  32443. (function (BABYLON) {
  32444. var LensFlare = (function () {
  32445. function LensFlare(size, position, color, imgUrl, system) {
  32446. this.size = size;
  32447. this.position = position;
  32448. this.dispose = function () {
  32449. if (this.texture) {
  32450. this.texture.dispose();
  32451. }
  32452. // Remove from scene
  32453. var index = this._system.lensFlares.indexOf(this);
  32454. this._system.lensFlares.splice(index, 1);
  32455. };
  32456. this.color = color || new BABYLON.Color3(1, 1, 1);
  32457. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32458. this._system = system;
  32459. system.lensFlares.push(this);
  32460. }
  32461. return LensFlare;
  32462. })();
  32463. BABYLON.LensFlare = LensFlare;
  32464. })(BABYLON || (BABYLON = {}));
  32465. var BABYLON;
  32466. (function (BABYLON) {
  32467. var LensFlareSystem = (function () {
  32468. function LensFlareSystem(name, emitter, scene) {
  32469. this.name = name;
  32470. this.lensFlares = new Array();
  32471. this.borderLimit = 300;
  32472. this.layerMask = 0x0FFFFFFF;
  32473. this._vertexDeclaration = [2];
  32474. this._vertexStrideSize = 2 * 4;
  32475. this._isEnabled = true;
  32476. this._scene = scene;
  32477. this._emitter = emitter;
  32478. scene.lensFlareSystems.push(this);
  32479. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32480. // VBO
  32481. var vertices = [];
  32482. vertices.push(1, 1);
  32483. vertices.push(-1, 1);
  32484. vertices.push(-1, -1);
  32485. vertices.push(1, -1);
  32486. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32487. // Indices
  32488. var indices = [];
  32489. indices.push(0);
  32490. indices.push(1);
  32491. indices.push(2);
  32492. indices.push(0);
  32493. indices.push(2);
  32494. indices.push(3);
  32495. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32496. // Effects
  32497. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32498. }
  32499. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32500. get: function () {
  32501. return this._isEnabled;
  32502. },
  32503. set: function (value) {
  32504. this._isEnabled = value;
  32505. },
  32506. enumerable: true,
  32507. configurable: true
  32508. });
  32509. LensFlareSystem.prototype.getScene = function () {
  32510. return this._scene;
  32511. };
  32512. LensFlareSystem.prototype.getEmitter = function () {
  32513. return this._emitter;
  32514. };
  32515. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32516. this._emitter = newEmitter;
  32517. };
  32518. LensFlareSystem.prototype.getEmitterPosition = function () {
  32519. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32520. };
  32521. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32522. var position = this.getEmitterPosition();
  32523. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32524. this._positionX = position.x;
  32525. this._positionY = position.y;
  32526. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32527. if (position.z > 0) {
  32528. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32529. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32530. return true;
  32531. }
  32532. }
  32533. return false;
  32534. };
  32535. LensFlareSystem.prototype._isVisible = function () {
  32536. if (!this._isEnabled) {
  32537. return false;
  32538. }
  32539. var emitterPosition = this.getEmitterPosition();
  32540. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32541. var distance = direction.length();
  32542. direction.normalize();
  32543. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32544. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32545. return !pickInfo.hit || pickInfo.distance > distance;
  32546. };
  32547. LensFlareSystem.prototype.render = function () {
  32548. if (!this._effect.isReady())
  32549. return false;
  32550. var engine = this._scene.getEngine();
  32551. var viewport = this._scene.activeCamera.viewport;
  32552. var globalViewport = viewport.toGlobal(engine);
  32553. // Position
  32554. if (!this.computeEffectivePosition(globalViewport)) {
  32555. return false;
  32556. }
  32557. // Visibility
  32558. if (!this._isVisible()) {
  32559. return false;
  32560. }
  32561. // Intensity
  32562. var awayX;
  32563. var awayY;
  32564. if (this._positionX < this.borderLimit + globalViewport.x) {
  32565. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32566. }
  32567. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32568. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32569. }
  32570. else {
  32571. awayX = 0;
  32572. }
  32573. if (this._positionY < this.borderLimit + globalViewport.y) {
  32574. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32575. }
  32576. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32577. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32578. }
  32579. else {
  32580. awayY = 0;
  32581. }
  32582. var away = (awayX > awayY) ? awayX : awayY;
  32583. if (away > this.borderLimit) {
  32584. away = this.borderLimit;
  32585. }
  32586. var intensity = 1.0 - (away / this.borderLimit);
  32587. if (intensity < 0) {
  32588. return false;
  32589. }
  32590. if (intensity > 1.0) {
  32591. intensity = 1.0;
  32592. }
  32593. // Position
  32594. var centerX = globalViewport.x + globalViewport.width / 2;
  32595. var centerY = globalViewport.y + globalViewport.height / 2;
  32596. var distX = centerX - this._positionX;
  32597. var distY = centerY - this._positionY;
  32598. // Effects
  32599. engine.enableEffect(this._effect);
  32600. engine.setState(false);
  32601. engine.setDepthBuffer(false);
  32602. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32603. // VBOs
  32604. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32605. // Flares
  32606. for (var index = 0; index < this.lensFlares.length; index++) {
  32607. var flare = this.lensFlares[index];
  32608. var x = centerX - (distX * flare.position);
  32609. var y = centerY - (distY * flare.position);
  32610. var cw = flare.size;
  32611. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32612. var cx = 2 * (x / globalViewport.width) - 1.0;
  32613. var cy = 1.0 - 2 * (y / globalViewport.height);
  32614. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32615. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32616. // Texture
  32617. this._effect.setTexture("textureSampler", flare.texture);
  32618. // Color
  32619. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32620. // Draw order
  32621. engine.draw(true, 0, 6);
  32622. }
  32623. engine.setDepthBuffer(true);
  32624. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32625. return true;
  32626. };
  32627. LensFlareSystem.prototype.dispose = function () {
  32628. if (this._vertexBuffer) {
  32629. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32630. this._vertexBuffer = null;
  32631. }
  32632. if (this._indexBuffer) {
  32633. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32634. this._indexBuffer = null;
  32635. }
  32636. while (this.lensFlares.length) {
  32637. this.lensFlares[0].dispose();
  32638. }
  32639. // Remove from scene
  32640. var index = this._scene.lensFlareSystems.indexOf(this);
  32641. this._scene.lensFlareSystems.splice(index, 1);
  32642. };
  32643. LensFlareSystem.ParseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  32644. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32645. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32646. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32647. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32648. var parsedFlare = parsedLensFlareSystem.flares[index];
  32649. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32650. }
  32651. return lensFlareSystem;
  32652. };
  32653. LensFlareSystem.prototype.serialize = function () {
  32654. var serializationObject = {};
  32655. serializationObject.emitterId = this.getEmitter().id;
  32656. serializationObject.borderLimit = this.borderLimit;
  32657. serializationObject.flares = [];
  32658. for (var index = 0; index < this.lensFlares.length; index++) {
  32659. var flare = this.lensFlares[index];
  32660. serializationObject.flares.push({
  32661. size: flare.size,
  32662. position: flare.position,
  32663. color: flare.color.asArray(),
  32664. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32665. });
  32666. }
  32667. return serializationObject;
  32668. };
  32669. return LensFlareSystem;
  32670. })();
  32671. BABYLON.LensFlareSystem = LensFlareSystem;
  32672. })(BABYLON || (BABYLON = {}));
  32673. var BABYLON;
  32674. (function (BABYLON) {
  32675. // We're mainly based on the logic defined into the FreeCamera code
  32676. var DeviceOrientationCamera = (function (_super) {
  32677. __extends(DeviceOrientationCamera, _super);
  32678. function DeviceOrientationCamera(name, position, scene) {
  32679. var _this = this;
  32680. _super.call(this, name, position, scene);
  32681. this._offsetX = null;
  32682. this._offsetY = null;
  32683. this._orientationGamma = 0;
  32684. this._orientationBeta = 0;
  32685. this._initialOrientationGamma = 0;
  32686. this._initialOrientationBeta = 0;
  32687. this.angularSensibility = 10000.0;
  32688. this.moveSensibility = 50.0;
  32689. window.addEventListener("resize", function () {
  32690. _this._initialOrientationGamma = null;
  32691. }, false);
  32692. }
  32693. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32694. var _this = this;
  32695. if (this._attachedCanvas) {
  32696. return;
  32697. }
  32698. this._attachedCanvas = canvas;
  32699. if (!this._orientationChanged) {
  32700. this._orientationChanged = function (evt) {
  32701. if (!_this._initialOrientationGamma) {
  32702. _this._initialOrientationGamma = evt.gamma;
  32703. _this._initialOrientationBeta = evt.beta;
  32704. }
  32705. _this._orientationGamma = evt.gamma;
  32706. _this._orientationBeta = evt.beta;
  32707. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32708. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32709. };
  32710. }
  32711. window.addEventListener("deviceorientation", this._orientationChanged);
  32712. };
  32713. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32714. if (this._attachedCanvas !== canvas) {
  32715. return;
  32716. }
  32717. window.removeEventListener("deviceorientation", this._orientationChanged);
  32718. this._attachedCanvas = null;
  32719. this._orientationGamma = 0;
  32720. this._orientationBeta = 0;
  32721. this._initialOrientationGamma = 0;
  32722. this._initialOrientationBeta = 0;
  32723. };
  32724. DeviceOrientationCamera.prototype._checkInputs = function () {
  32725. if (!this._offsetX) {
  32726. return;
  32727. }
  32728. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32729. var speed = this._computeLocalCameraSpeed();
  32730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32732. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32733. _super.prototype._checkInputs.call(this);
  32734. };
  32735. return DeviceOrientationCamera;
  32736. })(BABYLON.FreeCamera);
  32737. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32738. })(BABYLON || (BABYLON = {}));
  32739. var BABYLON;
  32740. (function (BABYLON) {
  32741. var Gamepads = (function () {
  32742. function Gamepads(ongamedpadconnected) {
  32743. var _this = this;
  32744. this.babylonGamepads = [];
  32745. this.oneGamepadConnected = false;
  32746. this.isMonitoring = false;
  32747. this.gamepadEventSupported = 'GamepadEvent' in window;
  32748. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32749. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32750. 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=";
  32751. this._callbackGamepadConnected = ongamedpadconnected;
  32752. if (this.gamepadSupportAvailable) {
  32753. // Checking if the gamepad connected event is supported (like in Firefox)
  32754. if (this.gamepadEventSupported) {
  32755. window.addEventListener('gamepadconnected', function (evt) {
  32756. _this._onGamepadConnected(evt);
  32757. }, false);
  32758. window.addEventListener('gamepaddisconnected', function (evt) {
  32759. _this._onGamepadDisconnected(evt);
  32760. }, false);
  32761. }
  32762. else {
  32763. this._startMonitoringGamepads();
  32764. }
  32765. if (!this.oneGamepadConnected) {
  32766. this._insertGamepadDOMInstructions();
  32767. }
  32768. }
  32769. else {
  32770. this._insertGamepadDOMNotSupported();
  32771. }
  32772. }
  32773. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32774. Gamepads.gamepadDOMInfo = document.createElement("div");
  32775. var buttonAImage = document.createElement("img");
  32776. buttonAImage.src = this.buttonADataURL;
  32777. var spanMessage = document.createElement("span");
  32778. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32779. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32780. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32781. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32782. Gamepads.gamepadDOMInfo.style.width = "100%";
  32783. Gamepads.gamepadDOMInfo.style.height = "48px";
  32784. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32785. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32786. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32787. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32788. buttonAImage.style.position = "relative";
  32789. buttonAImage.style.bottom = "8px";
  32790. spanMessage.style.position = "relative";
  32791. spanMessage.style.fontSize = "32px";
  32792. spanMessage.style.bottom = "32px";
  32793. spanMessage.style.color = "green";
  32794. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32795. };
  32796. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32797. Gamepads.gamepadDOMInfo = document.createElement("div");
  32798. var spanMessage = document.createElement("span");
  32799. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32800. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32801. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32802. Gamepads.gamepadDOMInfo.style.width = "100%";
  32803. Gamepads.gamepadDOMInfo.style.height = "40px";
  32804. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32805. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32806. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32807. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32808. spanMessage.style.position = "relative";
  32809. spanMessage.style.fontSize = "32px";
  32810. spanMessage.style.color = "red";
  32811. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32812. };
  32813. Gamepads.prototype.dispose = function () {
  32814. if (Gamepads.gamepadDOMInfo) {
  32815. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32816. }
  32817. };
  32818. Gamepads.prototype._onGamepadConnected = function (evt) {
  32819. var newGamepad = this._addNewGamepad(evt.gamepad);
  32820. if (this._callbackGamepadConnected)
  32821. this._callbackGamepadConnected(newGamepad);
  32822. this._startMonitoringGamepads();
  32823. };
  32824. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32825. if (!this.oneGamepadConnected) {
  32826. this.oneGamepadConnected = true;
  32827. if (Gamepads.gamepadDOMInfo) {
  32828. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32829. Gamepads.gamepadDOMInfo = null;
  32830. }
  32831. }
  32832. var newGamepad;
  32833. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32834. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32835. }
  32836. else {
  32837. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32838. }
  32839. this.babylonGamepads.push(newGamepad);
  32840. return newGamepad;
  32841. };
  32842. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32843. // Remove the gamepad from the list of gamepads to monitor.
  32844. for (var i in this.babylonGamepads) {
  32845. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32846. this.babylonGamepads.splice(i, 1);
  32847. break;
  32848. }
  32849. }
  32850. // If no gamepads are left, stop the polling loop.
  32851. if (this.babylonGamepads.length == 0) {
  32852. this._stopMonitoringGamepads();
  32853. }
  32854. };
  32855. Gamepads.prototype._startMonitoringGamepads = function () {
  32856. if (!this.isMonitoring) {
  32857. this.isMonitoring = true;
  32858. this._checkGamepadsStatus();
  32859. }
  32860. };
  32861. Gamepads.prototype._stopMonitoringGamepads = function () {
  32862. this.isMonitoring = false;
  32863. };
  32864. Gamepads.prototype._checkGamepadsStatus = function () {
  32865. var _this = this;
  32866. // updating gamepad objects
  32867. this._updateGamepadObjects();
  32868. for (var i in this.babylonGamepads) {
  32869. this.babylonGamepads[i].update();
  32870. }
  32871. if (this.isMonitoring) {
  32872. if (window.requestAnimationFrame) {
  32873. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32874. }
  32875. else if (window.mozRequestAnimationFrame) {
  32876. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32877. }
  32878. else if (window.webkitRequestAnimationFrame) {
  32879. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32880. }
  32881. }
  32882. };
  32883. // This function is called only on Chrome, which does not yet support
  32884. // connection/disconnection events, but requires you to monitor
  32885. // an array for changes.
  32886. Gamepads.prototype._updateGamepadObjects = function () {
  32887. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32888. for (var i = 0; i < gamepads.length; i++) {
  32889. if (gamepads[i]) {
  32890. if (!(gamepads[i].index in this.babylonGamepads)) {
  32891. var newGamepad = this._addNewGamepad(gamepads[i]);
  32892. if (this._callbackGamepadConnected) {
  32893. this._callbackGamepadConnected(newGamepad);
  32894. }
  32895. }
  32896. else {
  32897. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32898. }
  32899. }
  32900. }
  32901. };
  32902. return Gamepads;
  32903. })();
  32904. BABYLON.Gamepads = Gamepads;
  32905. var StickValues = (function () {
  32906. function StickValues(x, y) {
  32907. this.x = x;
  32908. this.y = y;
  32909. }
  32910. return StickValues;
  32911. })();
  32912. BABYLON.StickValues = StickValues;
  32913. var Gamepad = (function () {
  32914. function Gamepad(id, index, browserGamepad) {
  32915. this.id = id;
  32916. this.index = index;
  32917. this.browserGamepad = browserGamepad;
  32918. if (this.browserGamepad.axes.length >= 2) {
  32919. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32920. }
  32921. if (this.browserGamepad.axes.length >= 4) {
  32922. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32923. }
  32924. }
  32925. Gamepad.prototype.onleftstickchanged = function (callback) {
  32926. this._onleftstickchanged = callback;
  32927. };
  32928. Gamepad.prototype.onrightstickchanged = function (callback) {
  32929. this._onrightstickchanged = callback;
  32930. };
  32931. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32932. get: function () {
  32933. return this._leftStick;
  32934. },
  32935. set: function (newValues) {
  32936. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32937. this._onleftstickchanged(newValues);
  32938. }
  32939. this._leftStick = newValues;
  32940. },
  32941. enumerable: true,
  32942. configurable: true
  32943. });
  32944. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32945. get: function () {
  32946. return this._rightStick;
  32947. },
  32948. set: function (newValues) {
  32949. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32950. this._onrightstickchanged(newValues);
  32951. }
  32952. this._rightStick = newValues;
  32953. },
  32954. enumerable: true,
  32955. configurable: true
  32956. });
  32957. Gamepad.prototype.update = function () {
  32958. if (this._leftStick) {
  32959. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32960. }
  32961. if (this._rightStick) {
  32962. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32963. }
  32964. };
  32965. return Gamepad;
  32966. })();
  32967. BABYLON.Gamepad = Gamepad;
  32968. var GenericPad = (function (_super) {
  32969. __extends(GenericPad, _super);
  32970. function GenericPad(id, index, gamepad) {
  32971. _super.call(this, id, index, gamepad);
  32972. this.id = id;
  32973. this.index = index;
  32974. this.gamepad = gamepad;
  32975. this._buttons = new Array(gamepad.buttons.length);
  32976. }
  32977. GenericPad.prototype.onbuttondown = function (callback) {
  32978. this._onbuttondown = callback;
  32979. };
  32980. GenericPad.prototype.onbuttonup = function (callback) {
  32981. this._onbuttonup = callback;
  32982. };
  32983. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32984. if (newValue !== currentValue) {
  32985. if (this._onbuttondown && newValue === 1) {
  32986. this._onbuttondown(buttonIndex);
  32987. }
  32988. if (this._onbuttonup && newValue === 0) {
  32989. this._onbuttonup(buttonIndex);
  32990. }
  32991. }
  32992. return newValue;
  32993. };
  32994. GenericPad.prototype.update = function () {
  32995. _super.prototype.update.call(this);
  32996. for (var index = 0; index < this._buttons.length; index++) {
  32997. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32998. }
  32999. };
  33000. return GenericPad;
  33001. })(Gamepad);
  33002. BABYLON.GenericPad = GenericPad;
  33003. (function (Xbox360Button) {
  33004. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33005. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33006. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33007. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33008. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33009. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33010. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33011. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33012. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33013. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33014. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33015. var Xbox360Button = BABYLON.Xbox360Button;
  33016. (function (Xbox360Dpad) {
  33017. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33018. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33019. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33020. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33021. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33022. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33023. var Xbox360Pad = (function (_super) {
  33024. __extends(Xbox360Pad, _super);
  33025. function Xbox360Pad() {
  33026. _super.apply(this, arguments);
  33027. this._leftTrigger = 0;
  33028. this._rightTrigger = 0;
  33029. this._buttonA = 0;
  33030. this._buttonB = 0;
  33031. this._buttonX = 0;
  33032. this._buttonY = 0;
  33033. this._buttonBack = 0;
  33034. this._buttonStart = 0;
  33035. this._buttonLB = 0;
  33036. this._buttonRB = 0;
  33037. this._buttonLeftStick = 0;
  33038. this._buttonRightStick = 0;
  33039. this._dPadUp = 0;
  33040. this._dPadDown = 0;
  33041. this._dPadLeft = 0;
  33042. this._dPadRight = 0;
  33043. }
  33044. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33045. this._onlefttriggerchanged = callback;
  33046. };
  33047. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33048. this._onrighttriggerchanged = callback;
  33049. };
  33050. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33051. get: function () {
  33052. return this._leftTrigger;
  33053. },
  33054. set: function (newValue) {
  33055. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33056. this._onlefttriggerchanged(newValue);
  33057. }
  33058. this._leftTrigger = newValue;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33064. get: function () {
  33065. return this._rightTrigger;
  33066. },
  33067. set: function (newValue) {
  33068. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33069. this._onrighttriggerchanged(newValue);
  33070. }
  33071. this._rightTrigger = newValue;
  33072. },
  33073. enumerable: true,
  33074. configurable: true
  33075. });
  33076. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33077. this._onbuttondown = callback;
  33078. };
  33079. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33080. this._onbuttonup = callback;
  33081. };
  33082. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33083. this._ondpaddown = callback;
  33084. };
  33085. Xbox360Pad.prototype.ondpadup = function (callback) {
  33086. this._ondpadup = callback;
  33087. };
  33088. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33089. if (newValue !== currentValue) {
  33090. if (this._onbuttondown && newValue === 1) {
  33091. this._onbuttondown(buttonType);
  33092. }
  33093. if (this._onbuttonup && newValue === 0) {
  33094. this._onbuttonup(buttonType);
  33095. }
  33096. }
  33097. return newValue;
  33098. };
  33099. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33100. if (newValue !== currentValue) {
  33101. if (this._ondpaddown && newValue === 1) {
  33102. this._ondpaddown(buttonType);
  33103. }
  33104. if (this._ondpadup && newValue === 0) {
  33105. this._ondpadup(buttonType);
  33106. }
  33107. }
  33108. return newValue;
  33109. };
  33110. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33111. get: function () {
  33112. return this._buttonA;
  33113. },
  33114. set: function (value) {
  33115. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33116. },
  33117. enumerable: true,
  33118. configurable: true
  33119. });
  33120. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33121. get: function () {
  33122. return this._buttonB;
  33123. },
  33124. set: function (value) {
  33125. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33126. },
  33127. enumerable: true,
  33128. configurable: true
  33129. });
  33130. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33131. get: function () {
  33132. return this._buttonX;
  33133. },
  33134. set: function (value) {
  33135. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33136. },
  33137. enumerable: true,
  33138. configurable: true
  33139. });
  33140. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33141. get: function () {
  33142. return this._buttonY;
  33143. },
  33144. set: function (value) {
  33145. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33146. },
  33147. enumerable: true,
  33148. configurable: true
  33149. });
  33150. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33151. get: function () {
  33152. return this._buttonStart;
  33153. },
  33154. set: function (value) {
  33155. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33156. },
  33157. enumerable: true,
  33158. configurable: true
  33159. });
  33160. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33161. get: function () {
  33162. return this._buttonBack;
  33163. },
  33164. set: function (value) {
  33165. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33166. },
  33167. enumerable: true,
  33168. configurable: true
  33169. });
  33170. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33171. get: function () {
  33172. return this._buttonLB;
  33173. },
  33174. set: function (value) {
  33175. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33176. },
  33177. enumerable: true,
  33178. configurable: true
  33179. });
  33180. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33181. get: function () {
  33182. return this._buttonRB;
  33183. },
  33184. set: function (value) {
  33185. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33186. },
  33187. enumerable: true,
  33188. configurable: true
  33189. });
  33190. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33191. get: function () {
  33192. return this._buttonLeftStick;
  33193. },
  33194. set: function (value) {
  33195. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33196. },
  33197. enumerable: true,
  33198. configurable: true
  33199. });
  33200. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33201. get: function () {
  33202. return this._buttonRightStick;
  33203. },
  33204. set: function (value) {
  33205. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33206. },
  33207. enumerable: true,
  33208. configurable: true
  33209. });
  33210. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33211. get: function () {
  33212. return this._dPadUp;
  33213. },
  33214. set: function (value) {
  33215. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33216. },
  33217. enumerable: true,
  33218. configurable: true
  33219. });
  33220. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33221. get: function () {
  33222. return this._dPadDown;
  33223. },
  33224. set: function (value) {
  33225. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33226. },
  33227. enumerable: true,
  33228. configurable: true
  33229. });
  33230. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33231. get: function () {
  33232. return this._dPadLeft;
  33233. },
  33234. set: function (value) {
  33235. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33236. },
  33237. enumerable: true,
  33238. configurable: true
  33239. });
  33240. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33241. get: function () {
  33242. return this._dPadRight;
  33243. },
  33244. set: function (value) {
  33245. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33246. },
  33247. enumerable: true,
  33248. configurable: true
  33249. });
  33250. Xbox360Pad.prototype.update = function () {
  33251. _super.prototype.update.call(this);
  33252. this.buttonA = this.browserGamepad.buttons[0].value;
  33253. this.buttonB = this.browserGamepad.buttons[1].value;
  33254. this.buttonX = this.browserGamepad.buttons[2].value;
  33255. this.buttonY = this.browserGamepad.buttons[3].value;
  33256. this.buttonLB = this.browserGamepad.buttons[4].value;
  33257. this.buttonRB = this.browserGamepad.buttons[5].value;
  33258. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33259. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33260. this.buttonBack = this.browserGamepad.buttons[8].value;
  33261. this.buttonStart = this.browserGamepad.buttons[9].value;
  33262. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33263. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33264. this.dPadUp = this.browserGamepad.buttons[12].value;
  33265. this.dPadDown = this.browserGamepad.buttons[13].value;
  33266. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33267. this.dPadRight = this.browserGamepad.buttons[15].value;
  33268. };
  33269. return Xbox360Pad;
  33270. })(Gamepad);
  33271. BABYLON.Xbox360Pad = Xbox360Pad;
  33272. })(BABYLON || (BABYLON = {}));
  33273. var BABYLON;
  33274. (function (BABYLON) {
  33275. // We're mainly based on the logic defined into the FreeCamera code
  33276. var GamepadCamera = (function (_super) {
  33277. __extends(GamepadCamera, _super);
  33278. function GamepadCamera(name, position, scene) {
  33279. var _this = this;
  33280. _super.call(this, name, position, scene);
  33281. this.angularSensibility = 200;
  33282. this.moveSensibility = 75;
  33283. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33284. }
  33285. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33286. // Only the first gamepad can control the camera
  33287. if (gamepad.index === 0) {
  33288. this._gamepad = gamepad;
  33289. }
  33290. };
  33291. GamepadCamera.prototype._checkInputs = function () {
  33292. if (this._gamepad) {
  33293. var LSValues = this._gamepad.leftStick;
  33294. var normalizedLX = LSValues.x / this.moveSensibility;
  33295. var normalizedLY = LSValues.y / this.moveSensibility;
  33296. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33297. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33298. var RSValues = this._gamepad.rightStick;
  33299. var normalizedRX = RSValues.x / this.angularSensibility;
  33300. var normalizedRY = RSValues.y / this.angularSensibility;
  33301. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33302. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33303. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33304. var speed = this._computeLocalCameraSpeed() * 50.0;
  33305. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33306. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33307. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33308. }
  33309. _super.prototype._checkInputs.call(this);
  33310. };
  33311. GamepadCamera.prototype.dispose = function () {
  33312. this._gamepads.dispose();
  33313. _super.prototype.dispose.call(this);
  33314. };
  33315. return GamepadCamera;
  33316. })(BABYLON.FreeCamera);
  33317. BABYLON.GamepadCamera = GamepadCamera;
  33318. })(BABYLON || (BABYLON = {}));
  33319. var BABYLON;
  33320. (function (BABYLON) {
  33321. var Analyser = (function () {
  33322. function Analyser(scene) {
  33323. this.SMOOTHING = 0.75;
  33324. this.FFT_SIZE = 512;
  33325. this.BARGRAPHAMPLITUDE = 256;
  33326. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33327. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33328. this._scene = scene;
  33329. this._audioEngine = BABYLON.Engine.audioEngine;
  33330. if (this._audioEngine.canUseWebAudio) {
  33331. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33332. this._webAudioAnalyser.minDecibels = -140;
  33333. this._webAudioAnalyser.maxDecibels = 0;
  33334. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33335. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33336. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33337. }
  33338. }
  33339. Analyser.prototype.getFrequencyBinCount = function () {
  33340. if (this._audioEngine.canUseWebAudio) {
  33341. return this._webAudioAnalyser.frequencyBinCount;
  33342. }
  33343. else {
  33344. return 0;
  33345. }
  33346. };
  33347. Analyser.prototype.getByteFrequencyData = function () {
  33348. if (this._audioEngine.canUseWebAudio) {
  33349. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33350. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33351. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33352. }
  33353. return this._byteFreqs;
  33354. };
  33355. Analyser.prototype.getByteTimeDomainData = function () {
  33356. if (this._audioEngine.canUseWebAudio) {
  33357. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33358. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33359. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33360. }
  33361. return this._byteTime;
  33362. };
  33363. Analyser.prototype.getFloatFrequencyData = function () {
  33364. if (this._audioEngine.canUseWebAudio) {
  33365. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33366. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33367. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33368. }
  33369. return this._floatFreqs;
  33370. };
  33371. Analyser.prototype.drawDebugCanvas = function () {
  33372. var _this = this;
  33373. if (this._audioEngine.canUseWebAudio) {
  33374. if (!this._debugCanvas) {
  33375. this._debugCanvas = document.createElement("canvas");
  33376. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33377. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33378. this._debugCanvas.style.position = "absolute";
  33379. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33380. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33381. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33382. document.body.appendChild(this._debugCanvas);
  33383. this._registerFunc = function () {
  33384. _this.drawDebugCanvas();
  33385. };
  33386. this._scene.registerBeforeRender(this._registerFunc);
  33387. }
  33388. if (this._registerFunc) {
  33389. var workingArray = this.getByteFrequencyData();
  33390. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33391. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33392. // Draw the frequency domain chart.
  33393. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33394. var value = workingArray[i];
  33395. var percent = value / this.BARGRAPHAMPLITUDE;
  33396. var height = this.DEBUGCANVASSIZE.height * percent;
  33397. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33398. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33399. var hue = i / this.getFrequencyBinCount() * 360;
  33400. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33401. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33402. }
  33403. }
  33404. }
  33405. };
  33406. Analyser.prototype.stopDebugCanvas = function () {
  33407. if (this._debugCanvas) {
  33408. this._scene.unregisterBeforeRender(this._registerFunc);
  33409. this._registerFunc = null;
  33410. document.body.removeChild(this._debugCanvas);
  33411. this._debugCanvas = null;
  33412. this._debugCanvasContext = null;
  33413. }
  33414. };
  33415. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33416. if (this._audioEngine.canUseWebAudio) {
  33417. inputAudioNode.connect(this._webAudioAnalyser);
  33418. this._webAudioAnalyser.connect(outputAudioNode);
  33419. }
  33420. };
  33421. Analyser.prototype.dispose = function () {
  33422. if (this._audioEngine.canUseWebAudio) {
  33423. this._webAudioAnalyser.disconnect();
  33424. }
  33425. };
  33426. return Analyser;
  33427. })();
  33428. BABYLON.Analyser = Analyser;
  33429. })(BABYLON || (BABYLON = {}));
  33430. var BABYLON;
  33431. (function (BABYLON) {
  33432. var AudioEngine = (function () {
  33433. function AudioEngine() {
  33434. this._audioContext = null;
  33435. this._audioContextInitialized = false;
  33436. this.canUseWebAudio = false;
  33437. this.WarnedWebAudioUnsupported = false;
  33438. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33439. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33440. this.canUseWebAudio = true;
  33441. }
  33442. }
  33443. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33444. get: function () {
  33445. if (!this._audioContextInitialized) {
  33446. this._initializeAudioContext();
  33447. }
  33448. return this._audioContext;
  33449. },
  33450. enumerable: true,
  33451. configurable: true
  33452. });
  33453. AudioEngine.prototype._initializeAudioContext = function () {
  33454. try {
  33455. if (this.canUseWebAudio) {
  33456. this._audioContext = new AudioContext();
  33457. // create a global volume gain node
  33458. this.masterGain = this._audioContext.createGain();
  33459. this.masterGain.gain.value = 1;
  33460. this.masterGain.connect(this._audioContext.destination);
  33461. this._audioContextInitialized = true;
  33462. }
  33463. }
  33464. catch (e) {
  33465. this.canUseWebAudio = false;
  33466. BABYLON.Tools.Error("Web Audio: " + e.message);
  33467. }
  33468. };
  33469. AudioEngine.prototype.dispose = function () {
  33470. if (this.canUseWebAudio && this._audioContextInitialized) {
  33471. if (this._connectedAnalyser) {
  33472. this._connectedAnalyser.stopDebugCanvas();
  33473. this._connectedAnalyser.dispose();
  33474. this.masterGain.disconnect();
  33475. this.masterGain.connect(this._audioContext.destination);
  33476. this._connectedAnalyser = null;
  33477. }
  33478. this.masterGain.gain.value = 1;
  33479. }
  33480. this.WarnedWebAudioUnsupported = false;
  33481. };
  33482. AudioEngine.prototype.getGlobalVolume = function () {
  33483. if (this.canUseWebAudio && this._audioContextInitialized) {
  33484. return this.masterGain.gain.value;
  33485. }
  33486. else {
  33487. return -1;
  33488. }
  33489. };
  33490. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33491. if (this.canUseWebAudio && this._audioContextInitialized) {
  33492. this.masterGain.gain.value = newVolume;
  33493. }
  33494. };
  33495. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33496. if (this._connectedAnalyser) {
  33497. this._connectedAnalyser.stopDebugCanvas();
  33498. }
  33499. if (this.canUseWebAudio && this._audioContextInitialized) {
  33500. this._connectedAnalyser = analyser;
  33501. this.masterGain.disconnect();
  33502. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33503. }
  33504. };
  33505. return AudioEngine;
  33506. })();
  33507. BABYLON.AudioEngine = AudioEngine;
  33508. })(BABYLON || (BABYLON = {}));
  33509. var BABYLON;
  33510. (function (BABYLON) {
  33511. var Sound = (function () {
  33512. /**
  33513. * Create a sound and attach it to a scene
  33514. * @param name Name of your sound
  33515. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33516. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33517. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33518. */
  33519. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33520. var _this = this;
  33521. this.autoplay = false;
  33522. this.loop = false;
  33523. this.useCustomAttenuation = false;
  33524. this.spatialSound = false;
  33525. this.refDistance = 1;
  33526. this.rolloffFactor = 1;
  33527. this.maxDistance = 100;
  33528. this.distanceModel = "linear";
  33529. this._panningModel = "equalpower";
  33530. this._playbackRate = 1;
  33531. this._streaming = false;
  33532. this._startTime = 0;
  33533. this._startOffset = 0;
  33534. this._position = BABYLON.Vector3.Zero();
  33535. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33536. this._volume = 1;
  33537. this._isLoaded = false;
  33538. this._isReadyToPlay = false;
  33539. this.isPlaying = false;
  33540. this.isPaused = false;
  33541. this._isDirectional = false;
  33542. // Used if you'd like to create a directional sound.
  33543. // If not set, the sound will be omnidirectional
  33544. this._coneInnerAngle = 360;
  33545. this._coneOuterAngle = 360;
  33546. this._coneOuterGain = 0;
  33547. this._isOutputConnected = false;
  33548. this.name = name;
  33549. this._scene = scene;
  33550. this._readyToPlayCallback = readyToPlayCallback;
  33551. // Default custom attenuation function is a linear attenuation
  33552. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33553. if (currentDistance < maxDistance) {
  33554. return currentVolume * (1 - currentDistance / maxDistance);
  33555. }
  33556. else {
  33557. return 0;
  33558. }
  33559. };
  33560. if (options) {
  33561. this.autoplay = options.autoplay || false;
  33562. this.loop = options.loop || false;
  33563. // if volume === 0, we need another way to check this option
  33564. if (options.volume !== undefined) {
  33565. this._volume = options.volume;
  33566. }
  33567. this.spatialSound = options.spatialSound || false;
  33568. this.maxDistance = options.maxDistance || 100;
  33569. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33570. this.rolloffFactor = options.rolloffFactor || 1;
  33571. this.refDistance = options.refDistance || 1;
  33572. this.distanceModel = options.distanceModel || "linear";
  33573. this._playbackRate = options.playbackRate || 1;
  33574. this._streaming = options.streaming || false;
  33575. }
  33576. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33577. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33578. this._soundGain.gain.value = this._volume;
  33579. this._inputAudioNode = this._soundGain;
  33580. this._ouputAudioNode = this._soundGain;
  33581. if (this.spatialSound) {
  33582. this._createSpatialParameters();
  33583. }
  33584. this._scene.mainSoundTrack.AddSound(this);
  33585. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33586. if (urlOrArrayBuffer) {
  33587. // If it's an URL
  33588. if (typeof (urlOrArrayBuffer) === "string") {
  33589. // Loading sound using XHR2
  33590. if (!this._streaming) {
  33591. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33592. }
  33593. else {
  33594. this._htmlAudioElement = new Audio();
  33595. this._htmlAudioElement.src = urlOrArrayBuffer;
  33596. this._htmlAudioElement.controls = false;
  33597. this._htmlAudioElement.loop = this.loop;
  33598. this._htmlAudioElement.crossOrigin = "anonymous";
  33599. this._isReadyToPlay = true;
  33600. document.body.appendChild(this._htmlAudioElement);
  33601. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33602. if (this._readyToPlayCallback) {
  33603. window.setTimeout(function () {
  33604. _this._readyToPlayCallback();
  33605. }, 1000);
  33606. }
  33607. if (this.autoplay) {
  33608. this.play();
  33609. }
  33610. }
  33611. }
  33612. else {
  33613. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33614. this._soundLoaded(urlOrArrayBuffer);
  33615. }
  33616. else {
  33617. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33618. }
  33619. }
  33620. }
  33621. }
  33622. else {
  33623. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33624. this._scene.mainSoundTrack.AddSound(this);
  33625. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33626. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33627. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33628. }
  33629. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33630. if (this._readyToPlayCallback) {
  33631. window.setTimeout(function () {
  33632. _this._readyToPlayCallback();
  33633. }, 1000);
  33634. }
  33635. }
  33636. }
  33637. Sound.prototype.dispose = function () {
  33638. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33639. if (this.isPlaying) {
  33640. this.stop();
  33641. }
  33642. this._isReadyToPlay = false;
  33643. if (this.soundTrackId === -1) {
  33644. this._scene.mainSoundTrack.RemoveSound(this);
  33645. }
  33646. else {
  33647. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33648. }
  33649. if (this._soundGain) {
  33650. this._soundGain.disconnect();
  33651. this._soundGain = null;
  33652. }
  33653. if (this._soundPanner) {
  33654. this._soundPanner.disconnect();
  33655. this._soundPanner = null;
  33656. }
  33657. if (this._soundSource) {
  33658. this._soundSource.disconnect();
  33659. this._soundSource = null;
  33660. }
  33661. this._audioBuffer = null;
  33662. if (this._htmlAudioElement) {
  33663. this._htmlAudioElement.pause();
  33664. this._htmlAudioElement.src = "";
  33665. document.body.removeChild(this._htmlAudioElement);
  33666. }
  33667. if (this._connectedMesh) {
  33668. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33669. this._connectedMesh = null;
  33670. }
  33671. }
  33672. };
  33673. Sound.prototype._soundLoaded = function (audioData) {
  33674. var _this = this;
  33675. this._isLoaded = true;
  33676. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33677. _this._audioBuffer = buffer;
  33678. _this._isReadyToPlay = true;
  33679. if (_this.autoplay) {
  33680. _this.play();
  33681. }
  33682. if (_this._readyToPlayCallback) {
  33683. _this._readyToPlayCallback();
  33684. }
  33685. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33686. };
  33687. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33689. this._audioBuffer = audioBuffer;
  33690. this._isReadyToPlay = true;
  33691. }
  33692. };
  33693. Sound.prototype.updateOptions = function (options) {
  33694. if (options) {
  33695. this.loop = options.loop || this.loop;
  33696. this.maxDistance = options.maxDistance || this.maxDistance;
  33697. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33698. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33699. this.refDistance = options.refDistance || this.refDistance;
  33700. this.distanceModel = options.distanceModel || this.distanceModel;
  33701. this._playbackRate = options.playbackRate || this._playbackRate;
  33702. this._updateSpatialParameters();
  33703. if (this.isPlaying) {
  33704. if (this._streaming) {
  33705. this._htmlAudioElement.playbackRate = this._playbackRate;
  33706. }
  33707. else {
  33708. this._soundSource.playbackRate.value = this._playbackRate;
  33709. }
  33710. }
  33711. }
  33712. };
  33713. Sound.prototype._createSpatialParameters = function () {
  33714. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33715. if (this._scene.headphone) {
  33716. this._panningModel = "HRTF";
  33717. }
  33718. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33719. this._updateSpatialParameters();
  33720. this._soundPanner.connect(this._ouputAudioNode);
  33721. this._inputAudioNode = this._soundPanner;
  33722. }
  33723. };
  33724. Sound.prototype._updateSpatialParameters = function () {
  33725. if (this.spatialSound) {
  33726. if (this.useCustomAttenuation) {
  33727. // Tricks to disable in a way embedded Web Audio attenuation
  33728. this._soundPanner.distanceModel = "linear";
  33729. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33730. this._soundPanner.refDistance = 1;
  33731. this._soundPanner.rolloffFactor = 1;
  33732. this._soundPanner.panningModel = this._panningModel;
  33733. }
  33734. else {
  33735. this._soundPanner.distanceModel = this.distanceModel;
  33736. this._soundPanner.maxDistance = this.maxDistance;
  33737. this._soundPanner.refDistance = this.refDistance;
  33738. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33739. this._soundPanner.panningModel = this._panningModel;
  33740. }
  33741. }
  33742. };
  33743. Sound.prototype.switchPanningModelToHRTF = function () {
  33744. this._panningModel = "HRTF";
  33745. this._switchPanningModel();
  33746. };
  33747. Sound.prototype.switchPanningModelToEqualPower = function () {
  33748. this._panningModel = "equalpower";
  33749. this._switchPanningModel();
  33750. };
  33751. Sound.prototype._switchPanningModel = function () {
  33752. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33753. this._soundPanner.panningModel = this._panningModel;
  33754. }
  33755. };
  33756. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33758. if (this._isOutputConnected) {
  33759. this._ouputAudioNode.disconnect();
  33760. }
  33761. this._ouputAudioNode.connect(soundTrackAudioNode);
  33762. this._isOutputConnected = true;
  33763. }
  33764. };
  33765. /**
  33766. * Transform this sound into a directional source
  33767. * @param coneInnerAngle Size of the inner cone in degree
  33768. * @param coneOuterAngle Size of the outer cone in degree
  33769. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33770. */
  33771. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33772. if (coneOuterAngle < coneInnerAngle) {
  33773. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33774. return;
  33775. }
  33776. this._coneInnerAngle = coneInnerAngle;
  33777. this._coneOuterAngle = coneOuterAngle;
  33778. this._coneOuterGain = coneOuterGain;
  33779. this._isDirectional = true;
  33780. if (this.isPlaying && this.loop) {
  33781. this.stop();
  33782. this.play();
  33783. }
  33784. };
  33785. Sound.prototype.setPosition = function (newPosition) {
  33786. this._position = newPosition;
  33787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33788. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33789. }
  33790. };
  33791. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33792. this._localDirection = newLocalDirection;
  33793. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33794. this._updateDirection();
  33795. }
  33796. };
  33797. Sound.prototype._updateDirection = function () {
  33798. var mat = this._connectedMesh.getWorldMatrix();
  33799. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33800. direction.normalize();
  33801. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33802. };
  33803. Sound.prototype.updateDistanceFromListener = function () {
  33804. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33805. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33806. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33807. }
  33808. };
  33809. Sound.prototype.setAttenuationFunction = function (callback) {
  33810. this._customAttenuationFunction = callback;
  33811. };
  33812. /**
  33813. * Play the sound
  33814. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33815. */
  33816. Sound.prototype.play = function (time) {
  33817. var _this = this;
  33818. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33819. try {
  33820. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33821. if (!this._soundSource || !this._streamingSource) {
  33822. if (this.spatialSound) {
  33823. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33824. if (this._isDirectional) {
  33825. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33826. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33827. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33828. if (this._connectedMesh) {
  33829. this._updateDirection();
  33830. }
  33831. else {
  33832. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33833. }
  33834. }
  33835. }
  33836. }
  33837. if (this._streaming) {
  33838. if (!this._streamingSource) {
  33839. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33840. this._htmlAudioElement.onended = function () { _this._onended(); };
  33841. this._htmlAudioElement.playbackRate = this._playbackRate;
  33842. }
  33843. this._streamingSource.disconnect();
  33844. this._streamingSource.connect(this._inputAudioNode);
  33845. this._htmlAudioElement.play();
  33846. }
  33847. else {
  33848. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33849. this._soundSource.buffer = this._audioBuffer;
  33850. this._soundSource.connect(this._inputAudioNode);
  33851. this._soundSource.loop = this.loop;
  33852. this._soundSource.playbackRate.value = this._playbackRate;
  33853. this._soundSource.onended = function () { _this._onended(); };
  33854. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33855. }
  33856. this._startTime = startTime;
  33857. this.isPlaying = true;
  33858. this.isPaused = false;
  33859. }
  33860. catch (ex) {
  33861. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33862. }
  33863. }
  33864. };
  33865. Sound.prototype._onended = function () {
  33866. this.isPlaying = false;
  33867. if (this.onended) {
  33868. this.onended();
  33869. }
  33870. };
  33871. /**
  33872. * Stop the sound
  33873. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33874. */
  33875. Sound.prototype.stop = function (time) {
  33876. if (this.isPlaying) {
  33877. if (this._streaming) {
  33878. this._htmlAudioElement.pause();
  33879. // Test needed for Firefox or it will generate an Invalid State Error
  33880. if (this._htmlAudioElement.currentTime > 0) {
  33881. this._htmlAudioElement.currentTime = 0;
  33882. }
  33883. }
  33884. else {
  33885. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33886. this._soundSource.stop(stopTime);
  33887. }
  33888. this.isPlaying = false;
  33889. }
  33890. };
  33891. Sound.prototype.pause = function () {
  33892. if (this.isPlaying) {
  33893. if (this._streaming) {
  33894. this._htmlAudioElement.pause();
  33895. }
  33896. else {
  33897. this.stop(0);
  33898. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33899. }
  33900. this.isPaused = true;
  33901. }
  33902. };
  33903. Sound.prototype.setVolume = function (newVolume, time) {
  33904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33905. if (time) {
  33906. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33907. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33908. }
  33909. else {
  33910. this._soundGain.gain.value = newVolume;
  33911. }
  33912. }
  33913. this._volume = newVolume;
  33914. };
  33915. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33916. this._playbackRate = newPlaybackRate;
  33917. if (this.isPlaying) {
  33918. if (this._streaming) {
  33919. this._htmlAudioElement.playbackRate = this._playbackRate;
  33920. }
  33921. else {
  33922. this._soundSource.playbackRate.value = this._playbackRate;
  33923. }
  33924. }
  33925. };
  33926. Sound.prototype.getVolume = function () {
  33927. return this._volume;
  33928. };
  33929. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33930. var _this = this;
  33931. this._connectedMesh = meshToConnectTo;
  33932. if (!this.spatialSound) {
  33933. this.spatialSound = true;
  33934. this._createSpatialParameters();
  33935. if (this.isPlaying && this.loop) {
  33936. this.stop();
  33937. this.play();
  33938. }
  33939. }
  33940. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33941. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33942. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33943. };
  33944. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33945. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33946. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33947. this._updateDirection();
  33948. }
  33949. };
  33950. Sound.ParseSound = function (parsedSound, scene, rootUrl) {
  33951. var soundName = parsedSound.name;
  33952. var soundUrl = rootUrl + soundName;
  33953. var options = {
  33954. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33955. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33956. rolloffFactor: parsedSound.rolloffFactor,
  33957. refDistance: parsedSound.refDistance,
  33958. distanceModel: parsedSound.distanceModel,
  33959. playbackRate: parsedSound.playbackRate
  33960. };
  33961. var newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33962. scene._addPendingData(newSound);
  33963. if (parsedSound.position) {
  33964. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33965. newSound.setPosition(soundPosition);
  33966. }
  33967. if (parsedSound.isDirectional) {
  33968. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33969. if (parsedSound.localDirectionToMesh) {
  33970. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33971. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33972. }
  33973. }
  33974. if (parsedSound.connectedMeshId) {
  33975. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33976. if (connectedMesh) {
  33977. newSound.attachToMesh(connectedMesh);
  33978. }
  33979. }
  33980. return newSound;
  33981. };
  33982. return Sound;
  33983. })();
  33984. BABYLON.Sound = Sound;
  33985. })(BABYLON || (BABYLON = {}));
  33986. var BABYLON;
  33987. (function (BABYLON) {
  33988. var SoundTrack = (function () {
  33989. function SoundTrack(scene, options) {
  33990. this.id = -1;
  33991. this._isMainTrack = false;
  33992. this._isInitialized = false;
  33993. this._scene = scene;
  33994. this.soundCollection = new Array();
  33995. this._options = options;
  33996. if (!this._isMainTrack) {
  33997. this._scene.soundTracks.push(this);
  33998. this.id = this._scene.soundTracks.length - 1;
  33999. }
  34000. }
  34001. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34002. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34003. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34004. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34005. if (this._options) {
  34006. if (this._options.volume) {
  34007. this._outputAudioNode.gain.value = this._options.volume;
  34008. }
  34009. if (this._options.mainTrack) {
  34010. this._isMainTrack = this._options.mainTrack;
  34011. }
  34012. }
  34013. this._isInitialized = true;
  34014. }
  34015. };
  34016. SoundTrack.prototype.dispose = function () {
  34017. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34018. if (this._connectedAnalyser) {
  34019. this._connectedAnalyser.stopDebugCanvas();
  34020. }
  34021. while (this.soundCollection.length) {
  34022. this.soundCollection[0].dispose();
  34023. }
  34024. if (this._outputAudioNode) {
  34025. this._outputAudioNode.disconnect();
  34026. }
  34027. this._outputAudioNode = null;
  34028. }
  34029. };
  34030. SoundTrack.prototype.AddSound = function (sound) {
  34031. if (!this._isInitialized) {
  34032. this._initializeSoundTrackAudioGraph();
  34033. }
  34034. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34035. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34036. }
  34037. if (sound.soundTrackId) {
  34038. if (sound.soundTrackId === -1) {
  34039. this._scene.mainSoundTrack.RemoveSound(sound);
  34040. }
  34041. else {
  34042. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34043. }
  34044. }
  34045. this.soundCollection.push(sound);
  34046. sound.soundTrackId = this.id;
  34047. };
  34048. SoundTrack.prototype.RemoveSound = function (sound) {
  34049. var index = this.soundCollection.indexOf(sound);
  34050. if (index !== -1) {
  34051. this.soundCollection.splice(index, 1);
  34052. }
  34053. };
  34054. SoundTrack.prototype.setVolume = function (newVolume) {
  34055. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34056. this._outputAudioNode.gain.value = newVolume;
  34057. }
  34058. };
  34059. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34060. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34061. for (var i = 0; i < this.soundCollection.length; i++) {
  34062. this.soundCollection[i].switchPanningModelToHRTF();
  34063. }
  34064. }
  34065. };
  34066. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34067. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34068. for (var i = 0; i < this.soundCollection.length; i++) {
  34069. this.soundCollection[i].switchPanningModelToEqualPower();
  34070. }
  34071. }
  34072. };
  34073. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34074. if (this._connectedAnalyser) {
  34075. this._connectedAnalyser.stopDebugCanvas();
  34076. }
  34077. this._connectedAnalyser = analyser;
  34078. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34079. this._outputAudioNode.disconnect();
  34080. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34081. }
  34082. };
  34083. return SoundTrack;
  34084. })();
  34085. BABYLON.SoundTrack = SoundTrack;
  34086. })(BABYLON || (BABYLON = {}));
  34087. var BABYLON;
  34088. (function (BABYLON) {
  34089. var DepthRenderer = (function () {
  34090. function DepthRenderer(scene, type) {
  34091. var _this = this;
  34092. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34093. this._viewMatrix = BABYLON.Matrix.Zero();
  34094. this._projectionMatrix = BABYLON.Matrix.Zero();
  34095. this._transformMatrix = BABYLON.Matrix.Zero();
  34096. this._worldViewProjection = BABYLON.Matrix.Zero();
  34097. this._scene = scene;
  34098. var engine = scene.getEngine();
  34099. // Render target
  34100. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34101. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34102. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34103. this._depthMap.refreshRate = 1;
  34104. this._depthMap.renderParticles = false;
  34105. this._depthMap.renderList = null;
  34106. // set default depth value to 1.0 (far away)
  34107. this._depthMap.onClear = function (engine) {
  34108. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34109. };
  34110. // Custom render function
  34111. var renderSubMesh = function (subMesh) {
  34112. var mesh = subMesh.getRenderingMesh();
  34113. var scene = _this._scene;
  34114. var engine = scene.getEngine();
  34115. // Culling
  34116. engine.setState(subMesh.getMaterial().backFaceCulling);
  34117. // Managing instances
  34118. var batch = mesh._getInstancesRenderList(subMesh._id);
  34119. if (batch.mustReturn) {
  34120. return;
  34121. }
  34122. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34123. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34124. engine.enableEffect(_this._effect);
  34125. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34126. var material = subMesh.getMaterial();
  34127. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34128. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34129. // Alpha test
  34130. if (material && material.needAlphaTesting()) {
  34131. var alphaTexture = material.getAlphaTestTexture();
  34132. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34133. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34134. }
  34135. // Bones
  34136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34137. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34138. }
  34139. // Draw
  34140. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34141. }
  34142. };
  34143. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34144. var index;
  34145. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34146. renderSubMesh(opaqueSubMeshes.data[index]);
  34147. }
  34148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34149. renderSubMesh(alphaTestSubMeshes.data[index]);
  34150. }
  34151. };
  34152. }
  34153. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34154. var defines = [];
  34155. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34156. var mesh = subMesh.getMesh();
  34157. var scene = mesh.getScene();
  34158. var material = subMesh.getMaterial();
  34159. // Alpha test
  34160. if (material && material.needAlphaTesting()) {
  34161. defines.push("#define ALPHATEST");
  34162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34163. attribs.push(BABYLON.VertexBuffer.UVKind);
  34164. defines.push("#define UV1");
  34165. }
  34166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34167. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34168. defines.push("#define UV2");
  34169. }
  34170. }
  34171. // Bones
  34172. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34173. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34174. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34175. if (mesh.numBoneInfluencers > 4) {
  34176. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34177. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34178. }
  34179. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34180. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34181. }
  34182. else {
  34183. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34184. }
  34185. // Instances
  34186. if (useInstances) {
  34187. defines.push("#define INSTANCES");
  34188. attribs.push("world0");
  34189. attribs.push("world1");
  34190. attribs.push("world2");
  34191. attribs.push("world3");
  34192. }
  34193. // Get correct effect
  34194. var join = defines.join("\n");
  34195. if (this._cachedDefines !== join) {
  34196. this._cachedDefines = join;
  34197. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34198. }
  34199. return this._effect.isReady();
  34200. };
  34201. DepthRenderer.prototype.getDepthMap = function () {
  34202. return this._depthMap;
  34203. };
  34204. // Methods
  34205. DepthRenderer.prototype.dispose = function () {
  34206. this._depthMap.dispose();
  34207. };
  34208. return DepthRenderer;
  34209. })();
  34210. BABYLON.DepthRenderer = DepthRenderer;
  34211. })(BABYLON || (BABYLON = {}));
  34212. var BABYLON;
  34213. (function (BABYLON) {
  34214. var SSAORenderingPipeline = (function (_super) {
  34215. __extends(SSAORenderingPipeline, _super);
  34216. /**
  34217. * @constructor
  34218. * @param {string} name - The rendering pipeline name
  34219. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34220. * @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 }
  34221. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34222. */
  34223. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34224. var _this = this;
  34225. _super.call(this, scene.getEngine(), name);
  34226. // Members
  34227. /**
  34228. * The PassPostProcess id in the pipeline that contains the original scene color
  34229. * @type {string}
  34230. */
  34231. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34232. /**
  34233. * The SSAO PostProcess id in the pipeline
  34234. * @type {string}
  34235. */
  34236. this.SSAORenderEffect = "SSAORenderEffect";
  34237. /**
  34238. * The horizontal blur PostProcess id in the pipeline
  34239. * @type {string}
  34240. */
  34241. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34242. /**
  34243. * The vertical blur PostProcess id in the pipeline
  34244. * @type {string}
  34245. */
  34246. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34247. /**
  34248. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34249. * @type {string}
  34250. */
  34251. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34252. /**
  34253. * The output strength of the SSAO post-process. Default value is 1.0.
  34254. * @type {number}
  34255. */
  34256. this.totalStrength = 1.0;
  34257. /**
  34258. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34259. * @type {number}
  34260. */
  34261. this.radius = 0.0001;
  34262. /**
  34263. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34264. * Must not be equal to fallOff and superior to fallOff.
  34265. * Default value is 0.975
  34266. * @type {number}
  34267. */
  34268. this.area = 0.0075;
  34269. /**
  34270. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34271. * Must not be equal to area and inferior to area.
  34272. * Default value is 0.0
  34273. * @type {number}
  34274. */
  34275. this.fallOff = 0.000001;
  34276. /**
  34277. * The base color of the SSAO post-process
  34278. * The final result is "base + ssao" between [0, 1]
  34279. * @type {number}
  34280. */
  34281. this.base = 0.5;
  34282. this._firstUpdate = true;
  34283. this._scene = scene;
  34284. // Set up assets
  34285. this._createRandomTexture();
  34286. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34287. var ssaoRatio = ratio.ssaoRatio || ratio;
  34288. var combineRatio = ratio.combineRatio || ratio;
  34289. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34290. this._createSSAOPostProcess(ssaoRatio);
  34291. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34292. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34293. this._createSSAOCombinePostProcess(combineRatio);
  34294. // Set up pipeline
  34295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34300. // Finish
  34301. scene.postProcessRenderPipelineManager.addPipeline(this);
  34302. if (cameras)
  34303. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34304. }
  34305. // Public Methods
  34306. /**
  34307. * Returns the horizontal blur PostProcess
  34308. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34309. */
  34310. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34311. return this._blurHPostProcess;
  34312. };
  34313. /**
  34314. * Returns the vertical blur PostProcess
  34315. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34316. */
  34317. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34318. return this._blurVPostProcess;
  34319. };
  34320. /**
  34321. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34322. */
  34323. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34324. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34325. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34326. this._originalColorPostProcess = undefined;
  34327. this._ssaoPostProcess = undefined;
  34328. this._blurHPostProcess = undefined;
  34329. this._blurVPostProcess = undefined;
  34330. this._ssaoCombinePostProcess = undefined;
  34331. this._randomTexture.dispose();
  34332. if (disableDepthRender)
  34333. this._scene.disableDepthRenderer();
  34334. };
  34335. // Private Methods
  34336. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34337. var _this = this;
  34338. var numSamples = 16;
  34339. var sampleSphere = [
  34340. 0.5381, 0.1856, -0.4319,
  34341. 0.1379, 0.2486, 0.4430,
  34342. 0.3371, 0.5679, -0.0057,
  34343. -0.6999, -0.0451, -0.0019,
  34344. 0.0689, -0.1598, -0.8547,
  34345. 0.0560, 0.0069, -0.1843,
  34346. -0.0146, 0.1402, 0.0762,
  34347. 0.0100, -0.1924, -0.0344,
  34348. -0.3577, -0.5301, -0.4358,
  34349. -0.3169, 0.1063, 0.0158,
  34350. 0.0103, -0.5869, 0.0046,
  34351. -0.0897, -0.4940, 0.3287,
  34352. 0.7119, -0.0154, -0.0918,
  34353. -0.0533, 0.0596, -0.5411,
  34354. 0.0352, -0.0631, 0.5460,
  34355. -0.4776, 0.2847, -0.0271
  34356. ];
  34357. var samplesFactor = 1.0 / numSamples;
  34358. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34359. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34360. "area", "fallOff", "base"
  34361. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34362. this._ssaoPostProcess.onApply = function (effect) {
  34363. if (_this._firstUpdate) {
  34364. effect.setArray3("sampleSphere", sampleSphere);
  34365. effect.setFloat("samplesFactor", samplesFactor);
  34366. effect.setFloat("randTextureTiles", 4.0);
  34367. _this._firstUpdate = false;
  34368. }
  34369. effect.setFloat("totalStrength", _this.totalStrength);
  34370. effect.setFloat("radius", _this.radius);
  34371. effect.setFloat("area", _this.area);
  34372. effect.setFloat("fallOff", _this.fallOff);
  34373. effect.setFloat("base", _this.base);
  34374. effect.setTexture("textureSampler", _this._depthTexture);
  34375. effect.setTexture("randomSampler", _this._randomTexture);
  34376. };
  34377. };
  34378. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34379. var _this = this;
  34380. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34381. this._ssaoCombinePostProcess.onApply = function (effect) {
  34382. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34383. };
  34384. };
  34385. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34386. var size = 512;
  34387. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34388. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34389. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34390. var context = this._randomTexture.getContext();
  34391. var rand = function (min, max) {
  34392. return Math.random() * (max - min) + min;
  34393. };
  34394. var randVector = BABYLON.Vector3.Zero();
  34395. for (var x = 0; x < size; x++) {
  34396. for (var y = 0; y < size; y++) {
  34397. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34398. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34399. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34400. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34401. context.fillRect(x, y, 1, 1);
  34402. }
  34403. }
  34404. this._randomTexture.update(false);
  34405. };
  34406. return SSAORenderingPipeline;
  34407. })(BABYLON.PostProcessRenderPipeline);
  34408. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34409. })(BABYLON || (BABYLON = {}));
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34413. var VolumetricLightScatteringPostProcess = (function (_super) {
  34414. __extends(VolumetricLightScatteringPostProcess, _super);
  34415. /**
  34416. * @constructor
  34417. * @param {string} name - The post-process name
  34418. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  34419. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34420. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34421. * @param {number} samples - The post-process quality, default 100
  34422. * @param {number} samplingMode - The post-process filtering mode
  34423. * @param {BABYLON.Engine} engine - The babylon engine
  34424. * @param {boolean} reusable - If the post-process is reusable
  34425. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34426. */
  34427. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34428. var _this = this;
  34429. if (samples === void 0) { samples = 100; }
  34430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34431. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34432. this._screenCoordinates = BABYLON.Vector2.Zero();
  34433. /**
  34434. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34435. * @type {boolean}
  34436. */
  34437. this.useCustomMeshPosition = false;
  34438. /**
  34439. * If the post-process should inverse the light scattering direction
  34440. * @type {boolean}
  34441. */
  34442. this.invert = true;
  34443. /**
  34444. * Set to true to use the diffuseColor instead of the diffuseTexture
  34445. * @type {boolean}
  34446. */
  34447. this.useDiffuseColor = false;
  34448. /**
  34449. * Array containing the excluded meshes not rendered in the internal pass
  34450. */
  34451. this.excludedMeshes = new Array();
  34452. /**
  34453. * Controls the overall intensity of the post-process
  34454. * @type {number}
  34455. */
  34456. this.exposure = 0.3;
  34457. /**
  34458. * Dissipates each sample's contribution in range [0, 1]
  34459. * @type {number}
  34460. */
  34461. this.decay = 0.96815;
  34462. /**
  34463. * Controls the overall intensity of each sample
  34464. * @type {number}
  34465. */
  34466. this.weight = 0.58767;
  34467. /**
  34468. * Controls the density of each sample
  34469. * @type {number}
  34470. */
  34471. this.density = 0.926;
  34472. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34473. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34474. // Configure mesh
  34475. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34476. // Configure
  34477. this._createPass(scene, ratio.passRatio || ratio);
  34478. this.onActivate = function (camera) {
  34479. if (!_this.isSupported) {
  34480. _this.dispose(camera);
  34481. }
  34482. _this.onActivate = null;
  34483. };
  34484. this.onApply = function (effect) {
  34485. _this._updateMeshScreenCoordinates(scene);
  34486. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34487. effect.setFloat("exposure", _this.exposure);
  34488. effect.setFloat("decay", _this.decay);
  34489. effect.setFloat("weight", _this.weight);
  34490. effect.setFloat("density", _this.density);
  34491. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34492. };
  34493. }
  34494. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34495. var mesh = subMesh.getMesh();
  34496. var defines = [];
  34497. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34498. var material = subMesh.getMaterial();
  34499. var needUV = false;
  34500. // Render this.mesh as default
  34501. if (mesh === this.mesh) {
  34502. if (this.useDiffuseColor) {
  34503. defines.push("#define DIFFUSE_COLOR_RENDER");
  34504. }
  34505. else if (material) {
  34506. if (material.diffuseTexture !== undefined) {
  34507. defines.push("#define BASIC_RENDER");
  34508. }
  34509. else {
  34510. defines.push("#define DIFFUSE_COLOR_RENDER");
  34511. }
  34512. }
  34513. defines.push("#define NEED_UV");
  34514. needUV = true;
  34515. }
  34516. // Alpha test
  34517. if (material) {
  34518. if (material.needAlphaTesting()) {
  34519. defines.push("#define ALPHATEST");
  34520. }
  34521. if (material.opacityTexture !== undefined) {
  34522. defines.push("#define OPACITY");
  34523. if (material.opacityTexture.getAlphaFromRGB) {
  34524. defines.push("#define OPACITYRGB");
  34525. }
  34526. if (!needUV) {
  34527. defines.push("#define NEED_UV");
  34528. }
  34529. }
  34530. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34531. attribs.push(BABYLON.VertexBuffer.UVKind);
  34532. defines.push("#define UV1");
  34533. }
  34534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34535. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34536. defines.push("#define UV2");
  34537. }
  34538. }
  34539. // Bones
  34540. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34545. }
  34546. else {
  34547. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34548. }
  34549. // Instances
  34550. if (useInstances) {
  34551. defines.push("#define INSTANCES");
  34552. attribs.push("world0");
  34553. attribs.push("world1");
  34554. attribs.push("world2");
  34555. attribs.push("world3");
  34556. }
  34557. // Get correct effect
  34558. var join = defines.join("\n");
  34559. if (this._cachedDefines !== join) {
  34560. this._cachedDefines = join;
  34561. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34562. }
  34563. return this._volumetricLightScatteringPass.isReady();
  34564. };
  34565. /**
  34566. * Sets the new light position for light scattering effect
  34567. * @param {BABYLON.Vector3} The new custom light position
  34568. */
  34569. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34570. this._customMeshPosition = position;
  34571. };
  34572. /**
  34573. * Returns the light position for light scattering effect
  34574. * @return {BABYLON.Vector3} The custom light position
  34575. */
  34576. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34577. return this._customMeshPosition;
  34578. };
  34579. /**
  34580. * Disposes the internal assets and detaches the post-process from the camera
  34581. */
  34582. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34583. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34584. if (rttIndex !== -1) {
  34585. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34586. }
  34587. this._volumetricLightScatteringRTT.dispose();
  34588. _super.prototype.dispose.call(this, camera);
  34589. };
  34590. /**
  34591. * Returns the render target texture used by the post-process
  34592. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34593. */
  34594. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34595. return this._volumetricLightScatteringRTT;
  34596. };
  34597. // Private methods
  34598. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34599. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34600. return true;
  34601. }
  34602. return false;
  34603. };
  34604. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34605. var _this = this;
  34606. var engine = scene.getEngine();
  34607. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34608. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34609. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34610. this._volumetricLightScatteringRTT.renderList = null;
  34611. this._volumetricLightScatteringRTT.renderParticles = false;
  34612. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34613. // Custom render function for submeshes
  34614. var renderSubMesh = function (subMesh) {
  34615. var mesh = subMesh.getRenderingMesh();
  34616. if (_this._meshExcluded(mesh)) {
  34617. return;
  34618. }
  34619. var scene = mesh.getScene();
  34620. var engine = scene.getEngine();
  34621. // Culling
  34622. engine.setState(subMesh.getMaterial().backFaceCulling);
  34623. // Managing instances
  34624. var batch = mesh._getInstancesRenderList(subMesh._id);
  34625. if (batch.mustReturn) {
  34626. return;
  34627. }
  34628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34629. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34630. engine.enableEffect(_this._volumetricLightScatteringPass);
  34631. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34632. var material = subMesh.getMaterial();
  34633. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34634. // Alpha test
  34635. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34636. var alphaTexture = material.getAlphaTestTexture();
  34637. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34638. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34639. }
  34640. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34641. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34642. if (alphaTexture) {
  34643. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34644. }
  34645. }
  34646. if (material.opacityTexture !== undefined) {
  34647. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34648. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34649. }
  34650. }
  34651. // Bones
  34652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34653. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34654. }
  34655. // Draw
  34656. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34657. }
  34658. };
  34659. // Render target texture callbacks
  34660. var savedSceneClearColor;
  34661. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34662. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34663. savedSceneClearColor = scene.clearColor;
  34664. scene.clearColor = sceneClearColor;
  34665. };
  34666. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34667. scene.clearColor = savedSceneClearColor;
  34668. };
  34669. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34670. var engine = scene.getEngine();
  34671. var index;
  34672. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34673. renderSubMesh(opaqueSubMeshes.data[index]);
  34674. }
  34675. engine.setAlphaTesting(true);
  34676. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34677. renderSubMesh(alphaTestSubMeshes.data[index]);
  34678. }
  34679. engine.setAlphaTesting(false);
  34680. if (transparentSubMeshes.length) {
  34681. // Sort sub meshes
  34682. for (index = 0; index < transparentSubMeshes.length; index++) {
  34683. var submesh = transparentSubMeshes.data[index];
  34684. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34685. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34686. }
  34687. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34688. sortedArray.sort(function (a, b) {
  34689. // Alpha index first
  34690. if (a._alphaIndex > b._alphaIndex) {
  34691. return 1;
  34692. }
  34693. if (a._alphaIndex < b._alphaIndex) {
  34694. return -1;
  34695. }
  34696. // Then distance to camera
  34697. if (a._distanceToCamera < b._distanceToCamera) {
  34698. return 1;
  34699. }
  34700. if (a._distanceToCamera > b._distanceToCamera) {
  34701. return -1;
  34702. }
  34703. return 0;
  34704. });
  34705. // Render sub meshes
  34706. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34707. for (index = 0; index < sortedArray.length; index++) {
  34708. renderSubMesh(sortedArray[index]);
  34709. }
  34710. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34711. }
  34712. };
  34713. };
  34714. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34715. var transform = scene.getTransformMatrix();
  34716. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34717. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34718. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34719. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34720. if (this.invert)
  34721. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34722. };
  34723. // Static methods
  34724. /**
  34725. * Creates a default mesh for the Volumeric Light Scattering post-process
  34726. * @param {string} The mesh name
  34727. * @param {BABYLON.Scene} The scene where to create the mesh
  34728. * @return {BABYLON.Mesh} the default mesh
  34729. */
  34730. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34731. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34732. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34733. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34734. return mesh;
  34735. };
  34736. return VolumetricLightScatteringPostProcess;
  34737. })(BABYLON.PostProcess);
  34738. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34739. })(BABYLON || (BABYLON = {}));
  34740. // BABYLON.JS Chromatic Aberration GLSL Shader
  34741. // Author: Olivier Guyot
  34742. // Separates very slightly R, G and B colors on the edges of the screen
  34743. // Inspired by Francois Tarlier & Martins Upitis
  34744. var BABYLON;
  34745. (function (BABYLON) {
  34746. var LensRenderingPipeline = (function (_super) {
  34747. __extends(LensRenderingPipeline, _super);
  34748. /**
  34749. * @constructor
  34750. *
  34751. * Effect parameters are as follow:
  34752. * {
  34753. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34754. * edge_blur: number; // from 0 to x (1 for realism)
  34755. * distortion: number; // from 0 to x (1 for realism)
  34756. * grain_amount: number; // from 0 to 1
  34757. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34758. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34759. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34760. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34761. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34762. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34763. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34764. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34765. * }
  34766. * Note: if an effect parameter is unset, effect is disabled
  34767. *
  34768. * @param {string} name - The rendering pipeline name
  34769. * @param {object} parameters - An object containing all parameters (see above)
  34770. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34771. * @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)
  34772. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34773. */
  34774. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34775. var _this = this;
  34776. if (ratio === void 0) { ratio = 1.0; }
  34777. _super.call(this, scene.getEngine(), name);
  34778. // Lens effects can be of the following:
  34779. // - chromatic aberration (slight shift of RGB colors)
  34780. // - blur on the edge of the lens
  34781. // - lens distortion
  34782. // - depth-of-field blur & highlights enhancing
  34783. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34784. // - grain effect (noise or custom texture)
  34785. // Two additional texture samplers are needed:
  34786. // - depth map (for depth-of-field)
  34787. // - grain texture
  34788. /**
  34789. * The chromatic aberration PostProcess id in the pipeline
  34790. * @type {string}
  34791. */
  34792. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34793. /**
  34794. * The highlights enhancing PostProcess id in the pipeline
  34795. * @type {string}
  34796. */
  34797. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34798. /**
  34799. * The depth-of-field PostProcess id in the pipeline
  34800. * @type {string}
  34801. */
  34802. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34803. this._scene = scene;
  34804. // Fetch texture samplers
  34805. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34806. if (parameters.grain_texture) {
  34807. this._grainTexture = parameters.grain_texture;
  34808. }
  34809. else {
  34810. this._createGrainTexture();
  34811. }
  34812. // save parameters
  34813. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34814. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34815. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34816. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34817. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34818. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34819. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34820. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34821. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34822. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34823. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34824. // Create effects
  34825. this._createChromaticAberrationPostProcess(ratio);
  34826. this._createHighlightsPostProcess(ratio);
  34827. this._createDepthOfFieldPostProcess(ratio / 4);
  34828. // Set up pipeline
  34829. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34831. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34832. if (this._highlightsGain === -1) {
  34833. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34834. }
  34835. // Finish
  34836. scene.postProcessRenderPipelineManager.addPipeline(this);
  34837. if (cameras) {
  34838. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34839. }
  34840. }
  34841. // public methods (self explanatory)
  34842. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34843. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34844. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34845. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34846. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34847. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34848. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34849. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34850. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34851. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34852. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34853. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34854. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34855. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34856. };
  34857. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34858. this._highlightsPostProcess.updateEffect();
  34859. };
  34860. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34861. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34862. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34863. this._highlightsGain = amount;
  34864. };
  34865. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34866. if (this._highlightsGain === -1) {
  34867. this._highlightsGain = 1.0;
  34868. }
  34869. this._highlightsThreshold = amount;
  34870. };
  34871. LensRenderingPipeline.prototype.disableHighlights = function () {
  34872. this._highlightsGain = -1;
  34873. };
  34874. /**
  34875. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34876. */
  34877. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34878. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34879. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34880. this._chromaticAberrationPostProcess = undefined;
  34881. this._highlightsPostProcess = undefined;
  34882. this._depthOfFieldPostProcess = undefined;
  34883. this._grainTexture.dispose();
  34884. if (disableDepthRender)
  34885. this._scene.disableDepthRenderer();
  34886. };
  34887. // colors shifting and distortion
  34888. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34889. var _this = this;
  34890. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34891. [], // samplers
  34892. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34893. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34894. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34895. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34896. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34897. };
  34898. };
  34899. // highlights enhancing
  34900. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34901. var _this = this;
  34902. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34903. [], // samplers
  34904. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34905. this._highlightsPostProcess.onApply = function (effect) {
  34906. effect.setFloat('gain', _this._highlightsGain);
  34907. effect.setFloat('threshold', _this._highlightsThreshold);
  34908. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34909. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34910. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34911. };
  34912. };
  34913. // colors shifting and distortion
  34914. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34915. var _this = this;
  34916. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34917. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34918. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34919. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34920. this._depthOfFieldPostProcess.onApply = function (effect) {
  34921. effect.setTexture("depthSampler", _this._depthTexture);
  34922. effect.setTexture("grainSampler", _this._grainTexture);
  34923. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34924. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34925. effect.setFloat('grain_amount', _this._grainAmount);
  34926. effect.setBool('blur_noise', _this._blurNoise);
  34927. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34928. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34929. effect.setFloat('distortion', _this._distortion);
  34930. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34931. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34932. effect.setFloat('aperture', _this._dofAperture);
  34933. effect.setFloat('darken', _this._dofDarken);
  34934. effect.setFloat('edge_blur', _this._edgeBlur);
  34935. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34936. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34937. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34938. };
  34939. };
  34940. // creates a black and white random noise texture, 512x512
  34941. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34942. var size = 512;
  34943. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34944. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34945. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34946. var context = this._grainTexture.getContext();
  34947. var rand = function (min, max) {
  34948. return Math.random() * (max - min) + min;
  34949. };
  34950. var value;
  34951. for (var x = 0; x < size; x++) {
  34952. for (var y = 0; y < size; y++) {
  34953. value = Math.floor(rand(0.42, 0.58) * 255);
  34954. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34955. context.fillRect(x, y, 1, 1);
  34956. }
  34957. }
  34958. this._grainTexture.update(false);
  34959. };
  34960. return LensRenderingPipeline;
  34961. })(BABYLON.PostProcessRenderPipeline);
  34962. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34963. })(BABYLON || (BABYLON = {}));
  34964. //
  34965. // This post-process allows the modification of rendered colors by using
  34966. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34967. //
  34968. // The object needs to be provided an url to a texture containing the color
  34969. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34970. // Use an image editing software to tweak the LUT to match your needs.
  34971. //
  34972. // For an example of a color LUT, see here:
  34973. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34974. // For explanations on color grading, see here:
  34975. // http://udn.epicgames.com/Three/ColorGrading.html
  34976. //
  34977. var BABYLON;
  34978. (function (BABYLON) {
  34979. var ColorCorrectionPostProcess = (function (_super) {
  34980. __extends(ColorCorrectionPostProcess, _super);
  34981. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34982. var _this = this;
  34983. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34984. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34985. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34986. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34987. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34988. this.onApply = function (effect) {
  34989. effect.setTexture("colorTable", _this._colorTableTexture);
  34990. };
  34991. }
  34992. return ColorCorrectionPostProcess;
  34993. })(BABYLON.PostProcess);
  34994. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34995. })(BABYLON || (BABYLON = {}));
  34996. var BABYLON;
  34997. (function (BABYLON) {
  34998. var AnaglyphFreeCamera = (function (_super) {
  34999. __extends(AnaglyphFreeCamera, _super);
  35000. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35001. _super.call(this, name, position, scene);
  35002. this.interaxialDistance = interaxialDistance;
  35003. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35004. }
  35005. return AnaglyphFreeCamera;
  35006. })(BABYLON.FreeCamera);
  35007. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35008. var AnaglyphArcRotateCamera = (function (_super) {
  35009. __extends(AnaglyphArcRotateCamera, _super);
  35010. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35011. _super.call(this, name, alpha, beta, radius, target, scene);
  35012. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35013. }
  35014. return AnaglyphArcRotateCamera;
  35015. })(BABYLON.ArcRotateCamera);
  35016. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35017. var AnaglyphGamepadCamera = (function (_super) {
  35018. __extends(AnaglyphGamepadCamera, _super);
  35019. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35020. _super.call(this, name, position, scene);
  35021. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35022. }
  35023. return AnaglyphGamepadCamera;
  35024. })(BABYLON.GamepadCamera);
  35025. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35026. var StereoscopicFreeCamera = (function (_super) {
  35027. __extends(StereoscopicFreeCamera, _super);
  35028. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35029. _super.call(this, name, position, scene);
  35030. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35031. }
  35032. return StereoscopicFreeCamera;
  35033. })(BABYLON.FreeCamera);
  35034. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35035. var StereoscopicArcRotateCamera = (function (_super) {
  35036. __extends(StereoscopicArcRotateCamera, _super);
  35037. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35038. _super.call(this, name, alpha, beta, radius, target, scene);
  35039. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35040. }
  35041. return StereoscopicArcRotateCamera;
  35042. })(BABYLON.ArcRotateCamera);
  35043. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35044. var StereoscopicGamepadCamera = (function (_super) {
  35045. __extends(StereoscopicGamepadCamera, _super);
  35046. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35047. _super.call(this, name, position, scene);
  35048. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35049. }
  35050. return StereoscopicGamepadCamera;
  35051. })(BABYLON.GamepadCamera);
  35052. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35053. })(BABYLON || (BABYLON = {}));
  35054. var BABYLON;
  35055. (function (BABYLON) {
  35056. var HDRRenderingPipeline = (function (_super) {
  35057. __extends(HDRRenderingPipeline, _super);
  35058. /**
  35059. * @constructor
  35060. * @param {string} name - The rendering pipeline name
  35061. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35062. * @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)
  35063. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35064. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35065. */
  35066. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35067. var _this = this;
  35068. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35069. _super.call(this, scene.getEngine(), name);
  35070. /**
  35071. * Public members
  35072. */
  35073. // Gaussian Blur
  35074. /**
  35075. * Gaussian blur coefficient
  35076. * @type {number}
  35077. */
  35078. this.gaussCoeff = 0.3;
  35079. /**
  35080. * Gaussian blur mean
  35081. * @type {number}
  35082. */
  35083. this.gaussMean = 1.0;
  35084. /**
  35085. * Gaussian blur standard deviation
  35086. * @type {number}
  35087. */
  35088. this.gaussStandDev = 0.8;
  35089. /**
  35090. * Gaussian blur multiplier. Multiplies the blur effect
  35091. * @type {number}
  35092. */
  35093. this.gaussMultiplier = 4.0;
  35094. // HDR
  35095. /**
  35096. * Exposure, controls the overall intensity of the pipeline
  35097. * @type {number}
  35098. */
  35099. this.exposure = 1.0;
  35100. /**
  35101. * Minimum luminance that the post-process can output. Luminance is >= 0
  35102. * @type {number}
  35103. */
  35104. this.minimumLuminance = 1.0;
  35105. /**
  35106. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35107. * @type {number}
  35108. */
  35109. this.maximumLuminance = 1e20;
  35110. /**
  35111. * Increase rate for luminance: eye adaptation speed to dark
  35112. * @type {number}
  35113. */
  35114. this.luminanceIncreaserate = 0.5;
  35115. /**
  35116. * Decrease rate for luminance: eye adaptation speed to bright
  35117. * @type {number}
  35118. */
  35119. this.luminanceDecreaseRate = 0.5;
  35120. // Bright pass
  35121. /**
  35122. * Minimum luminance needed to compute HDR
  35123. * @type {number}
  35124. */
  35125. this.brightThreshold = 0.8;
  35126. this._needUpdate = true;
  35127. this._scene = scene;
  35128. // Bright pass
  35129. this._createBrightPassPostProcess(scene, ratio);
  35130. // Down sample X4
  35131. this._createDownSampleX4PostProcess(scene, ratio);
  35132. // Create gaussian blur post-processes
  35133. this._createGaussianBlurPostProcess(scene, ratio);
  35134. // Texture adder
  35135. this._createTextureAdderPostProcess(scene, ratio);
  35136. // Luminance generator
  35137. this._createLuminanceGeneratorPostProcess(scene);
  35138. // HDR
  35139. this._createHDRPostProcess(scene, ratio);
  35140. // Pass postprocess
  35141. if (originalPostProcess === null) {
  35142. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35143. }
  35144. else {
  35145. this._originalPostProcess = originalPostProcess;
  35146. }
  35147. // Configure pipeline
  35148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35154. var addDownSamplerPostProcess = function (id) {
  35155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35156. };
  35157. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35158. addDownSamplerPostProcess(i);
  35159. }
  35160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35161. // Finish
  35162. scene.postProcessRenderPipelineManager.addPipeline(this);
  35163. if (cameras !== null) {
  35164. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35165. }
  35166. this.update();
  35167. }
  35168. /**
  35169. * Tells the pipeline to update its post-processes
  35170. */
  35171. HDRRenderingPipeline.prototype.update = function () {
  35172. this._needUpdate = true;
  35173. };
  35174. /**
  35175. * Returns the current calculated luminance
  35176. */
  35177. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35178. return this._hdrCurrentLuminance;
  35179. };
  35180. /**
  35181. * Returns the currently drawn luminance
  35182. */
  35183. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35184. return this._hdrOutputLuminance;
  35185. };
  35186. /**
  35187. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35188. */
  35189. HDRRenderingPipeline.prototype.dispose = function () {
  35190. this._originalPostProcess = undefined;
  35191. this._brightPassPostProcess = undefined;
  35192. this._downSampleX4PostProcess = undefined;
  35193. this._guassianBlurHPostProcess = undefined;
  35194. this._guassianBlurVPostProcess = undefined;
  35195. this._textureAdderPostProcess = undefined;
  35196. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35197. this._downSamplePostProcesses[i] = undefined;
  35198. }
  35199. this._hdrPostProcess = undefined;
  35200. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35201. };
  35202. /**
  35203. * Creates the HDR post-process and computes the luminance adaptation
  35204. */
  35205. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35206. var _this = this;
  35207. var hdrLastLuminance = 0.0;
  35208. this._hdrOutputLuminance = -1.0;
  35209. this._hdrCurrentLuminance = 1.0;
  35210. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35211. this._hdrPostProcess.onApply = function (effect) {
  35212. if (_this._hdrOutputLuminance < 0.0) {
  35213. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35214. }
  35215. else {
  35216. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35217. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35218. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35219. }
  35220. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35221. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35222. }
  35223. else {
  35224. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35225. }
  35226. }
  35227. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35228. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35229. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35230. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35231. effect.setFloat("exposure", _this.exposure);
  35232. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35233. _this._needUpdate = false;
  35234. };
  35235. };
  35236. /**
  35237. * Texture Adder post-process
  35238. */
  35239. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35240. var _this = this;
  35241. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35242. this._textureAdderPostProcess.onApply = function (effect) {
  35243. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35244. };
  35245. };
  35246. /**
  35247. * Down sample X4 post-process
  35248. */
  35249. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35250. var _this = this;
  35251. var downSampleX4Offsets = new Array(32);
  35252. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35253. this._downSampleX4PostProcess.onApply = function (effect) {
  35254. if (_this._needUpdate) {
  35255. var id = 0;
  35256. for (var i = -2; i < 2; i++) {
  35257. for (var j = -2; j < 2; j++) {
  35258. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35259. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35260. id += 2;
  35261. }
  35262. }
  35263. }
  35264. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35265. };
  35266. };
  35267. /**
  35268. * Bright pass post-process
  35269. */
  35270. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35271. var _this = this;
  35272. var brightOffsets = new Array(8);
  35273. var brightPassCallback = function (effect) {
  35274. if (_this._needUpdate) {
  35275. var sU = (1.0 / _this._brightPassPostProcess.width);
  35276. var sV = (1.0 / _this._brightPassPostProcess.height);
  35277. brightOffsets[0] = -0.5 * sU;
  35278. brightOffsets[1] = 0.5 * sV;
  35279. brightOffsets[2] = 0.5 * sU;
  35280. brightOffsets[3] = 0.5 * sV;
  35281. brightOffsets[4] = -0.5 * sU;
  35282. brightOffsets[5] = -0.5 * sV;
  35283. brightOffsets[6] = 0.5 * sU;
  35284. brightOffsets[7] = -0.5 * sV;
  35285. }
  35286. effect.setArray2("dsOffsets", brightOffsets);
  35287. effect.setFloat("brightThreshold", _this.brightThreshold);
  35288. };
  35289. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35290. this._brightPassPostProcess.onApply = brightPassCallback;
  35291. };
  35292. /**
  35293. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35294. */
  35295. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35296. var _this = this;
  35297. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35298. var luminanceOffsets = new Array(8);
  35299. var downSampleOffsets = new Array(18);
  35300. var halfDestPixelSize;
  35301. this._downSamplePostProcesses = new Array(lumSteps);
  35302. // Utils for luminance
  35303. var luminanceUpdateSourceOffsets = function (width, height) {
  35304. var sU = (1.0 / width);
  35305. var sV = (1.0 / height);
  35306. luminanceOffsets[0] = -0.5 * sU;
  35307. luminanceOffsets[1] = 0.5 * sV;
  35308. luminanceOffsets[2] = 0.5 * sU;
  35309. luminanceOffsets[3] = 0.5 * sV;
  35310. luminanceOffsets[4] = -0.5 * sU;
  35311. luminanceOffsets[5] = -0.5 * sV;
  35312. luminanceOffsets[6] = 0.5 * sU;
  35313. luminanceOffsets[7] = -0.5 * sV;
  35314. };
  35315. var luminanceUpdateDestOffsets = function (width, height) {
  35316. var id = 0;
  35317. for (var x = -1; x < 2; x++) {
  35318. for (var y = -1; y < 2; y++) {
  35319. downSampleOffsets[id] = (x) / width;
  35320. downSampleOffsets[id + 1] = (y) / height;
  35321. id += 2;
  35322. }
  35323. }
  35324. };
  35325. // Luminance callback
  35326. var luminanceCallback = function (effect) {
  35327. if (_this._needUpdate) {
  35328. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35329. }
  35330. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35331. effect.setArray2("lumOffsets", luminanceOffsets);
  35332. };
  35333. // Down sample callbacks
  35334. var downSampleCallback = function (indice) {
  35335. var i = indice;
  35336. return function (effect) {
  35337. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35338. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35339. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35340. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35341. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35342. effect.setArray2("dsOffsets", downSampleOffsets);
  35343. };
  35344. };
  35345. var downSampleAfterRenderCallback = function (effect) {
  35346. // Unpack result
  35347. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35348. 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);
  35349. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35350. };
  35351. // Create luminance post-process
  35352. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35353. 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);
  35354. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35355. // Create down sample post-processes
  35356. for (var i = lumSteps - 2; i >= 0; i--) {
  35357. var length = Math.pow(3, i);
  35358. ratio = { width: length, height: length };
  35359. var defines = "#define DOWN_SAMPLE\n";
  35360. if (i === 0) {
  35361. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35362. }
  35363. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35364. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35365. if (i === 0) {
  35366. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35367. }
  35368. }
  35369. };
  35370. /**
  35371. * Gaussian blur post-processes. Horizontal and Vertical
  35372. */
  35373. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35374. var _this = this;
  35375. var blurOffsetsW = new Array(9);
  35376. var blurOffsetsH = new Array(9);
  35377. var blurWeights = new Array(9);
  35378. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35379. // Utils for gaussian blur
  35380. var calculateBlurOffsets = function (height) {
  35381. var lastOutputDimensions = {
  35382. width: scene.getEngine().getRenderWidth(),
  35383. height: scene.getEngine().getRenderHeight()
  35384. };
  35385. for (var i = 0; i < 9; i++) {
  35386. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35387. if (height) {
  35388. blurOffsetsH[i] = value;
  35389. }
  35390. else {
  35391. blurOffsetsW[i] = value;
  35392. }
  35393. }
  35394. };
  35395. var calculateWeights = function () {
  35396. var x = 0.0;
  35397. for (var i = 0; i < 9; i++) {
  35398. x = (i - 4.0) / 4.0;
  35399. 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));
  35400. }
  35401. };
  35402. // Callback
  35403. var gaussianBlurCallback = function (height) {
  35404. return function (effect) {
  35405. if (_this._needUpdate) {
  35406. calculateWeights();
  35407. calculateBlurOffsets(height);
  35408. }
  35409. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35410. effect.setArray("blurWeights", blurWeights);
  35411. effect.setFloat("multiplier", _this.gaussMultiplier);
  35412. };
  35413. };
  35414. // Create horizontal gaussian blur post-processes
  35415. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35416. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35417. // Create vertical gaussian blur post-process
  35418. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35419. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35420. };
  35421. // Luminance generator
  35422. HDRRenderingPipeline.LUM_STEPS = 6;
  35423. return HDRRenderingPipeline;
  35424. })(BABYLON.PostProcessRenderPipeline);
  35425. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35426. })(BABYLON || (BABYLON = {}));
  35427. var BABYLON;
  35428. (function (BABYLON) {
  35429. var FaceAdjacencies = (function () {
  35430. function FaceAdjacencies() {
  35431. this.edges = new Array();
  35432. this.edgesConnectedCount = 0;
  35433. }
  35434. return FaceAdjacencies;
  35435. })();
  35436. var EdgesRenderer = (function () {
  35437. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35438. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35439. if (epsilon === void 0) { epsilon = 0.95; }
  35440. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35441. this._linesPositions = new Array();
  35442. this._linesNormals = new Array();
  35443. this._linesIndices = new Array();
  35444. this._buffers = new Array();
  35445. this._checkVerticesInsteadOfIndices = false;
  35446. this._source = source;
  35447. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35448. this._epsilon = epsilon;
  35449. this._prepareRessources();
  35450. this._generateEdgesLines();
  35451. }
  35452. EdgesRenderer.prototype._prepareRessources = function () {
  35453. if (this._lineShader) {
  35454. return;
  35455. }
  35456. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35457. attributes: ["position", "normal"],
  35458. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35459. });
  35460. this._lineShader.disableDepthWrite = true;
  35461. this._lineShader.backFaceCulling = false;
  35462. };
  35463. EdgesRenderer.prototype.dispose = function () {
  35464. this._vb0.dispose();
  35465. this._vb1.dispose();
  35466. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35467. this._lineShader.dispose();
  35468. };
  35469. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35470. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35471. return 0;
  35472. }
  35473. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35474. return 1;
  35475. }
  35476. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35477. return 2;
  35478. }
  35479. return -1;
  35480. };
  35481. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35482. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35483. return 0;
  35484. }
  35485. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35486. return 1;
  35487. }
  35488. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35489. return 2;
  35490. }
  35491. return -1;
  35492. };
  35493. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35494. var needToCreateLine;
  35495. if (edge === undefined) {
  35496. needToCreateLine = true;
  35497. }
  35498. else {
  35499. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35500. needToCreateLine = dotProduct < this._epsilon;
  35501. }
  35502. if (needToCreateLine) {
  35503. var offset = this._linesPositions.length / 3;
  35504. var normal = p0.subtract(p1);
  35505. normal.normalize();
  35506. // Positions
  35507. this._linesPositions.push(p0.x);
  35508. this._linesPositions.push(p0.y);
  35509. this._linesPositions.push(p0.z);
  35510. this._linesPositions.push(p0.x);
  35511. this._linesPositions.push(p0.y);
  35512. this._linesPositions.push(p0.z);
  35513. this._linesPositions.push(p1.x);
  35514. this._linesPositions.push(p1.y);
  35515. this._linesPositions.push(p1.z);
  35516. this._linesPositions.push(p1.x);
  35517. this._linesPositions.push(p1.y);
  35518. this._linesPositions.push(p1.z);
  35519. // Normals
  35520. this._linesNormals.push(p1.x);
  35521. this._linesNormals.push(p1.y);
  35522. this._linesNormals.push(p1.z);
  35523. this._linesNormals.push(-1);
  35524. this._linesNormals.push(p1.x);
  35525. this._linesNormals.push(p1.y);
  35526. this._linesNormals.push(p1.z);
  35527. this._linesNormals.push(1);
  35528. this._linesNormals.push(p0.x);
  35529. this._linesNormals.push(p0.y);
  35530. this._linesNormals.push(p0.z);
  35531. this._linesNormals.push(-1);
  35532. this._linesNormals.push(p0.x);
  35533. this._linesNormals.push(p0.y);
  35534. this._linesNormals.push(p0.z);
  35535. this._linesNormals.push(1);
  35536. // Indices
  35537. this._linesIndices.push(offset);
  35538. this._linesIndices.push(offset + 1);
  35539. this._linesIndices.push(offset + 2);
  35540. this._linesIndices.push(offset);
  35541. this._linesIndices.push(offset + 2);
  35542. this._linesIndices.push(offset + 3);
  35543. }
  35544. };
  35545. EdgesRenderer.prototype._generateEdgesLines = function () {
  35546. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35547. var indices = this._source.getIndices();
  35548. // First let's find adjacencies
  35549. var adjacencies = new Array();
  35550. var faceNormals = new Array();
  35551. var index;
  35552. var faceAdjacencies;
  35553. // Prepare faces
  35554. for (index = 0; index < indices.length; index += 3) {
  35555. faceAdjacencies = new FaceAdjacencies();
  35556. var p0Index = indices[index];
  35557. var p1Index = indices[index + 1];
  35558. var p2Index = indices[index + 2];
  35559. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35560. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35561. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35562. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35563. faceNormal.normalize();
  35564. faceNormals.push(faceNormal);
  35565. adjacencies.push(faceAdjacencies);
  35566. }
  35567. // Scan
  35568. for (index = 0; index < adjacencies.length; index++) {
  35569. faceAdjacencies = adjacencies[index];
  35570. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35571. var otherFaceAdjacencies = adjacencies[otherIndex];
  35572. if (faceAdjacencies.edgesConnectedCount === 3) {
  35573. break;
  35574. }
  35575. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35576. continue;
  35577. }
  35578. var otherP0 = indices[otherIndex * 3];
  35579. var otherP1 = indices[otherIndex * 3 + 1];
  35580. var otherP2 = indices[otherIndex * 3 + 2];
  35581. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35582. var otherEdgeIndex;
  35583. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35584. continue;
  35585. }
  35586. switch (edgeIndex) {
  35587. case 0:
  35588. if (this._checkVerticesInsteadOfIndices) {
  35589. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35590. }
  35591. else {
  35592. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35593. }
  35594. break;
  35595. case 1:
  35596. if (this._checkVerticesInsteadOfIndices) {
  35597. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35598. }
  35599. else {
  35600. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35601. }
  35602. break;
  35603. case 2:
  35604. if (this._checkVerticesInsteadOfIndices) {
  35605. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35606. }
  35607. else {
  35608. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35609. }
  35610. break;
  35611. }
  35612. if (otherEdgeIndex === -1) {
  35613. continue;
  35614. }
  35615. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35616. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35617. faceAdjacencies.edgesConnectedCount++;
  35618. otherFaceAdjacencies.edgesConnectedCount++;
  35619. if (faceAdjacencies.edgesConnectedCount === 3) {
  35620. break;
  35621. }
  35622. }
  35623. }
  35624. }
  35625. // Create lines
  35626. for (index = 0; index < adjacencies.length; index++) {
  35627. // 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
  35628. var current = adjacencies[index];
  35629. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35630. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35631. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35632. }
  35633. // Merge into a single mesh
  35634. var engine = this._source.getScene().getEngine();
  35635. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35636. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35637. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35638. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35639. this._ib = engine.createIndexBuffer(this._linesIndices);
  35640. this._indicesCount = this._linesIndices.length;
  35641. };
  35642. EdgesRenderer.prototype.render = function () {
  35643. if (!this._lineShader.isReady()) {
  35644. return;
  35645. }
  35646. var scene = this._source.getScene();
  35647. var engine = scene.getEngine();
  35648. this._lineShader._preBind();
  35649. // VBOs
  35650. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35651. scene.resetCachedMaterial();
  35652. this._lineShader.setColor4("color", this._source.edgesColor);
  35653. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35654. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35655. this._lineShader.bind(this._source.getWorldMatrix());
  35656. // Draw order
  35657. engine.draw(true, 0, this._indicesCount);
  35658. this._lineShader.unbind();
  35659. engine.setDepthWrite(true);
  35660. };
  35661. return EdgesRenderer;
  35662. })();
  35663. BABYLON.EdgesRenderer = EdgesRenderer;
  35664. })(BABYLON || (BABYLON = {}));
  35665. var BABYLON;
  35666. (function (BABYLON) {
  35667. (function (TonemappingOperator) {
  35668. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35669. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35670. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35671. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35672. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35673. var TonemappingOperator = BABYLON.TonemappingOperator;
  35674. ;
  35675. var TonemapPostProcess = (function (_super) {
  35676. __extends(TonemapPostProcess, _super);
  35677. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35678. var _this = this;
  35679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35680. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35681. this._operator = operator;
  35682. this._exposureAdjustment = exposureAdjustment;
  35683. var params = ["_ExposureAdjustment"];
  35684. var defines = "#define ";
  35685. if (operator === TonemappingOperator.Hable)
  35686. defines += "HABLE_TONEMAPPING";
  35687. else if (operator === TonemappingOperator.Reinhard)
  35688. defines += "REINHARD_TONEMAPPING";
  35689. else if (operator === TonemappingOperator.HejiDawson)
  35690. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35691. else if (operator === TonemappingOperator.Photographic)
  35692. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35693. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35694. this.onApply = function (effect) {
  35695. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35696. };
  35697. }
  35698. return TonemapPostProcess;
  35699. })(BABYLON.PostProcess);
  35700. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35701. })(BABYLON || (BABYLON = {}));
  35702. var BABYLON;
  35703. (function (BABYLON) {
  35704. var ReflectionProbe = (function () {
  35705. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35706. var _this = this;
  35707. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35708. this.name = name;
  35709. this._viewMatrix = BABYLON.Matrix.Identity();
  35710. this._target = BABYLON.Vector3.Zero();
  35711. this._add = BABYLON.Vector3.Zero();
  35712. this.position = BABYLON.Vector3.Zero();
  35713. this._scene = scene;
  35714. this._scene.reflectionProbes.push(this);
  35715. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35716. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35717. switch (faceIndex) {
  35718. case 0:
  35719. _this._add.copyFromFloats(1, 0, 0);
  35720. break;
  35721. case 1:
  35722. _this._add.copyFromFloats(-1, 0, 0);
  35723. break;
  35724. case 2:
  35725. _this._add.copyFromFloats(0, -1, 0);
  35726. break;
  35727. case 3:
  35728. _this._add.copyFromFloats(0, 1, 0);
  35729. break;
  35730. case 4:
  35731. _this._add.copyFromFloats(0, 0, 1);
  35732. break;
  35733. case 5:
  35734. _this._add.copyFromFloats(0, 0, -1);
  35735. break;
  35736. }
  35737. if (_this._attachedMesh) {
  35738. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35739. }
  35740. _this.position.addToRef(_this._add, _this._target);
  35741. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35742. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35743. };
  35744. this._renderTargetTexture.onAfterUnbind = function () {
  35745. scene.updateTransformMatrix(true);
  35746. };
  35747. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35748. }
  35749. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35750. get: function () {
  35751. return this._renderTargetTexture.refreshRate;
  35752. },
  35753. set: function (value) {
  35754. this._renderTargetTexture.refreshRate = value;
  35755. },
  35756. enumerable: true,
  35757. configurable: true
  35758. });
  35759. ReflectionProbe.prototype.getScene = function () {
  35760. return this._scene;
  35761. };
  35762. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35763. get: function () {
  35764. return this._renderTargetTexture;
  35765. },
  35766. enumerable: true,
  35767. configurable: true
  35768. });
  35769. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35770. get: function () {
  35771. return this._renderTargetTexture.renderList;
  35772. },
  35773. enumerable: true,
  35774. configurable: true
  35775. });
  35776. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35777. this._attachedMesh = mesh;
  35778. };
  35779. ReflectionProbe.prototype.dispose = function () {
  35780. var index = this._scene.reflectionProbes.indexOf(this);
  35781. if (index !== -1) {
  35782. // Remove from the scene if found
  35783. this._scene.reflectionProbes.splice(index, 1);
  35784. }
  35785. };
  35786. return ReflectionProbe;
  35787. })();
  35788. BABYLON.ReflectionProbe = ReflectionProbe;
  35789. })(BABYLON || (BABYLON = {}));
  35790. var BABYLON;
  35791. (function (BABYLON) {
  35792. var SolidParticle = (function () {
  35793. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35794. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35795. this.position = BABYLON.Vector3.Zero(); // position
  35796. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35797. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35798. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35799. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35800. this.alive = true; // alive
  35801. this.idx = particleIndex;
  35802. this._pos = positionIndex;
  35803. this._model = model;
  35804. this.shapeId = shapeId;
  35805. this.idxInShape = idxInShape;
  35806. }
  35807. return SolidParticle;
  35808. })();
  35809. BABYLON.SolidParticle = SolidParticle;
  35810. var ModelShape = (function () {
  35811. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35812. this.shapeID = id;
  35813. this._shape = shape;
  35814. this._shapeUV = shapeUV;
  35815. this._positionFunction = posFunction;
  35816. this._vertexFunction = vtxFunction;
  35817. }
  35818. return ModelShape;
  35819. })();
  35820. BABYLON.ModelShape = ModelShape;
  35821. })(BABYLON || (BABYLON = {}));
  35822. var BABYLON;
  35823. (function (BABYLON) {
  35824. var SolidParticleSystem = (function () {
  35825. function SolidParticleSystem(name, scene, options) {
  35826. // public members
  35827. this.particles = new Array();
  35828. this.nbParticles = 0;
  35829. this.billboard = false;
  35830. this.counter = 0;
  35831. this.vars = {};
  35832. this._positions = new Array();
  35833. this._indices = new Array();
  35834. this._normals = new Array();
  35835. this._colors = new Array();
  35836. this._uvs = new Array();
  35837. this._index = 0; // indices index
  35838. this._updatable = true;
  35839. this._pickable = false;
  35840. this._alwaysVisible = false;
  35841. this._shapeCounter = 0;
  35842. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35843. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35844. this._computeParticleColor = true;
  35845. this._computeParticleTexture = true;
  35846. this._computeParticleRotation = true;
  35847. this._computeParticleVertex = false;
  35848. this._cam_axisZ = BABYLON.Vector3.Zero();
  35849. this._cam_axisY = BABYLON.Vector3.Zero();
  35850. this._cam_axisX = BABYLON.Vector3.Zero();
  35851. this._axisX = BABYLON.Axis.X;
  35852. this._axisY = BABYLON.Axis.Y;
  35853. this._axisZ = BABYLON.Axis.Z;
  35854. this._fakeCamPos = BABYLON.Vector3.Zero();
  35855. this._rotMatrix = new BABYLON.Matrix();
  35856. this._invertMatrix = new BABYLON.Matrix();
  35857. this._rotated = BABYLON.Vector3.Zero();
  35858. this._quaternion = new BABYLON.Quaternion();
  35859. this._vertex = BABYLON.Vector3.Zero();
  35860. this._normal = BABYLON.Vector3.Zero();
  35861. this._yaw = 0.0;
  35862. this._pitch = 0.0;
  35863. this._roll = 0.0;
  35864. this._halfroll = 0.0;
  35865. this._halfpitch = 0.0;
  35866. this._halfyaw = 0.0;
  35867. this._sinRoll = 0.0;
  35868. this._cosRoll = 0.0;
  35869. this._sinPitch = 0.0;
  35870. this._cosPitch = 0.0;
  35871. this._sinYaw = 0.0;
  35872. this._cosYaw = 0.0;
  35873. this._w = 0.0;
  35874. this.name = name;
  35875. this._scene = scene;
  35876. this._camera = scene.activeCamera;
  35877. this._pickable = options ? options.isPickable : false;
  35878. if (options && options.updatable) {
  35879. this._updatable = options.updatable;
  35880. }
  35881. else {
  35882. this._updatable = true;
  35883. }
  35884. if (this._pickable) {
  35885. this.pickedParticles = [];
  35886. }
  35887. }
  35888. // build the SPS mesh : returns the mesh
  35889. SolidParticleSystem.prototype.buildMesh = function () {
  35890. if (this.nbParticles === 0) {
  35891. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35892. this.addShape(triangle, 1);
  35893. triangle.dispose();
  35894. }
  35895. this._positions32 = new Float32Array(this._positions);
  35896. this._uvs32 = new Float32Array(this._uvs);
  35897. this._colors32 = new Float32Array(this._colors);
  35898. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35899. this._normals32 = new Float32Array(this._normals);
  35900. this._fixedNormal32 = new Float32Array(this._normals);
  35901. var vertexData = new BABYLON.VertexData();
  35902. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35903. vertexData.indices = this._indices;
  35904. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35905. if (this._uvs32) {
  35906. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35907. ;
  35908. }
  35909. if (this._colors32) {
  35910. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35911. }
  35912. var mesh = new BABYLON.Mesh(name, this._scene);
  35913. vertexData.applyToMesh(mesh, this._updatable);
  35914. this.mesh = mesh;
  35915. this.mesh.isPickable = this._pickable;
  35916. // free memory
  35917. this._positions = null;
  35918. this._normals = null;
  35919. this._uvs = null;
  35920. this._colors = null;
  35921. if (!this._updatable) {
  35922. this.particles.length = 0;
  35923. }
  35924. return mesh;
  35925. };
  35926. //reset copy
  35927. SolidParticleSystem.prototype._resetCopy = function () {
  35928. this._copy.position.x = 0;
  35929. this._copy.position.y = 0;
  35930. this._copy.position.z = 0;
  35931. this._copy.rotation.x = 0;
  35932. this._copy.rotation.y = 0;
  35933. this._copy.rotation.z = 0;
  35934. this._copy.quaternion = null;
  35935. this._copy.scale.x = 1;
  35936. this._copy.scale.y = 1;
  35937. this._copy.scale.z = 1;
  35938. this._copy.uvs.x = 0;
  35939. this._copy.uvs.y = 0;
  35940. this._copy.uvs.z = 1;
  35941. this._copy.uvs.w = 1;
  35942. this._copy.color = null;
  35943. };
  35944. // _meshBuilder : inserts the shape model in the global SPS mesh
  35945. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35946. var i;
  35947. var u = 0;
  35948. var c = 0;
  35949. this._resetCopy();
  35950. if (options && options.positionFunction) {
  35951. options.positionFunction(this._copy, idx, idxInShape);
  35952. }
  35953. if (this._copy.quaternion) {
  35954. this._quaternion.x = this._copy.quaternion.x;
  35955. this._quaternion.y = this._copy.quaternion.y;
  35956. this._quaternion.z = this._copy.quaternion.z;
  35957. this._quaternion.w = this._copy.quaternion.w;
  35958. }
  35959. else {
  35960. this._yaw = this._copy.rotation.y;
  35961. this._pitch = this._copy.rotation.x;
  35962. this._roll = this._copy.rotation.z;
  35963. this._quaternionRotationYPR();
  35964. }
  35965. this._quaternionToRotationMatrix();
  35966. for (i = 0; i < shape.length; i++) {
  35967. this._vertex.x = shape[i].x;
  35968. this._vertex.y = shape[i].y;
  35969. this._vertex.z = shape[i].z;
  35970. if (options && options.vertexFunction) {
  35971. options.vertexFunction(this._copy, this._vertex, i);
  35972. }
  35973. this._vertex.x *= this._copy.scale.x;
  35974. this._vertex.y *= this._copy.scale.y;
  35975. this._vertex.z *= this._copy.scale.z;
  35976. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35977. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35978. if (meshUV) {
  35979. 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);
  35980. u += 2;
  35981. }
  35982. if (this._copy.color) {
  35983. this._color = this._copy.color;
  35984. }
  35985. else if (meshCol && meshCol[c]) {
  35986. this._color.r = meshCol[c];
  35987. this._color.g = meshCol[c + 1];
  35988. this._color.b = meshCol[c + 2];
  35989. this._color.a = meshCol[c + 3];
  35990. }
  35991. else {
  35992. this._color.r = 1;
  35993. this._color.g = 1;
  35994. this._color.b = 1;
  35995. this._color.a = 1;
  35996. }
  35997. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35998. c += 4;
  35999. }
  36000. for (i = 0; i < meshInd.length; i++) {
  36001. indices.push(p + meshInd[i]);
  36002. }
  36003. if (this._pickable) {
  36004. var nbfaces = meshInd.length / 3;
  36005. for (i = 0; i < nbfaces; i++) {
  36006. this.pickedParticles.push({ idx: idx, faceId: i });
  36007. }
  36008. }
  36009. };
  36010. // returns a shape array from positions array
  36011. SolidParticleSystem.prototype._posToShape = function (positions) {
  36012. var shape = [];
  36013. for (var i = 0; i < positions.length; i += 3) {
  36014. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36015. }
  36016. return shape;
  36017. };
  36018. // returns a shapeUV array from a Vector4 uvs
  36019. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36020. var shapeUV = [];
  36021. if (uvs) {
  36022. for (var i = 0; i < uvs.length; i++)
  36023. shapeUV.push(uvs[i]);
  36024. }
  36025. return shapeUV;
  36026. };
  36027. // adds a new particle object in the particles array
  36028. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36029. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36030. };
  36031. // add solid particles from a shape model in the particles array
  36032. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36033. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36034. var meshInd = mesh.getIndices();
  36035. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36036. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36037. var shape = this._posToShape(meshPos);
  36038. var shapeUV = this._uvsToShapeUV(meshUV);
  36039. var posfunc = options ? options.positionFunction : null;
  36040. var vtxfunc = options ? options.vertexFunction : null;
  36041. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36042. // particles
  36043. var idx = this.nbParticles;
  36044. for (var i = 0; i < nb; i++) {
  36045. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36046. if (this._updatable) {
  36047. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36048. }
  36049. this._index += shape.length;
  36050. idx++;
  36051. }
  36052. this.nbParticles += nb;
  36053. this._shapeCounter++;
  36054. return this._shapeCounter;
  36055. };
  36056. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36057. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36058. this._resetCopy();
  36059. if (particle._model._positionFunction) {
  36060. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36061. }
  36062. if (this._copy.quaternion) {
  36063. this._quaternion.x = this._copy.quaternion.x;
  36064. this._quaternion.y = this._copy.quaternion.y;
  36065. this._quaternion.z = this._copy.quaternion.z;
  36066. this._quaternion.w = this._copy.quaternion.w;
  36067. }
  36068. else {
  36069. this._yaw = this._copy.rotation.y;
  36070. this._pitch = this._copy.rotation.x;
  36071. this._roll = this._copy.rotation.z;
  36072. this._quaternionRotationYPR();
  36073. }
  36074. this._quaternionToRotationMatrix();
  36075. this._shape = particle._model._shape;
  36076. for (var pt = 0; pt < this._shape.length; pt++) {
  36077. this._vertex.x = this._shape[pt].x;
  36078. this._vertex.y = this._shape[pt].y;
  36079. this._vertex.z = this._shape[pt].z;
  36080. if (particle._model._vertexFunction) {
  36081. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36082. }
  36083. this._vertex.x *= this._copy.scale.x;
  36084. this._vertex.y *= this._copy.scale.y;
  36085. this._vertex.z *= this._copy.scale.z;
  36086. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36087. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36088. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36089. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36090. }
  36091. particle.position.x = 0;
  36092. particle.position.y = 0;
  36093. particle.position.z = 0;
  36094. particle.rotation.x = 0;
  36095. particle.rotation.y = 0;
  36096. particle.rotation.z = 0;
  36097. particle.quaternion = null;
  36098. particle.scale.x = 1;
  36099. particle.scale.y = 1;
  36100. particle.scale.z = 1;
  36101. };
  36102. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36103. SolidParticleSystem.prototype.rebuildMesh = function () {
  36104. for (var p = 0; p < this.particles.length; p++) {
  36105. this._rebuildParticle(this.particles[p]);
  36106. }
  36107. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36108. };
  36109. // sets all the particles : updates the VBO
  36110. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36111. if (start === void 0) { start = 0; }
  36112. if (end === void 0) { end = this.nbParticles - 1; }
  36113. if (update === void 0) { update = true; }
  36114. if (!this._updatable) {
  36115. return;
  36116. }
  36117. // custom beforeUpdate
  36118. this.beforeUpdateParticles(start, end, update);
  36119. this._cam_axisX.x = 1;
  36120. this._cam_axisX.y = 0;
  36121. this._cam_axisX.z = 0;
  36122. this._cam_axisY.x = 0;
  36123. this._cam_axisY.y = 1;
  36124. this._cam_axisY.z = 0;
  36125. this._cam_axisZ.x = 0;
  36126. this._cam_axisZ.y = 0;
  36127. this._cam_axisZ.z = 1;
  36128. // if the particles will always face the camera
  36129. if (this.billboard) {
  36130. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36131. this._yaw = this.mesh.rotation.y;
  36132. this._pitch = this.mesh.rotation.x;
  36133. this._roll = this.mesh.rotation.z;
  36134. this._quaternionRotationYPR();
  36135. this._quaternionToRotationMatrix();
  36136. this._rotMatrix.invertToRef(this._invertMatrix);
  36137. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36138. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36139. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36140. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36141. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36142. this._cam_axisY.normalize();
  36143. this._cam_axisX.normalize();
  36144. this._cam_axisZ.normalize();
  36145. }
  36146. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36147. var idx = 0;
  36148. var index = 0;
  36149. var colidx = 0;
  36150. var colorIndex = 0;
  36151. var uvidx = 0;
  36152. var uvIndex = 0;
  36153. // particle loop
  36154. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36155. for (var p = start; p <= end; p++) {
  36156. this._particle = this.particles[p];
  36157. this._shape = this._particle._model._shape;
  36158. this._shapeUV = this._particle._model._shapeUV;
  36159. // call to custom user function to update the particle properties
  36160. this.updateParticle(this._particle);
  36161. // particle rotation matrix
  36162. if (this.billboard) {
  36163. this._particle.rotation.x = 0.0;
  36164. this._particle.rotation.y = 0.0;
  36165. }
  36166. if (this._computeParticleRotation) {
  36167. if (this._particle.quaternion) {
  36168. this._quaternion.x = this._particle.quaternion.x;
  36169. this._quaternion.y = this._particle.quaternion.y;
  36170. this._quaternion.z = this._particle.quaternion.z;
  36171. this._quaternion.w = this._particle.quaternion.w;
  36172. }
  36173. else {
  36174. this._yaw = this._particle.rotation.y;
  36175. this._pitch = this._particle.rotation.x;
  36176. this._roll = this._particle.rotation.z;
  36177. this._quaternionRotationYPR();
  36178. }
  36179. this._quaternionToRotationMatrix();
  36180. }
  36181. for (var pt = 0; pt < this._shape.length; pt++) {
  36182. idx = index + pt * 3;
  36183. colidx = colorIndex + pt * 4;
  36184. uvidx = uvIndex + pt * 2;
  36185. this._vertex.x = this._shape[pt].x;
  36186. this._vertex.y = this._shape[pt].y;
  36187. this._vertex.z = this._shape[pt].z;
  36188. if (this._computeParticleVertex) {
  36189. this.updateParticleVertex(this._particle, this._vertex, pt);
  36190. }
  36191. // positions
  36192. this._vertex.x *= this._particle.scale.x;
  36193. this._vertex.y *= this._particle.scale.y;
  36194. this._vertex.z *= this._particle.scale.z;
  36195. 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];
  36196. 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;
  36197. 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;
  36198. 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;
  36199. 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;
  36200. 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;
  36201. 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;
  36202. // normals : if the particles can't be morphed then just rotate the normals
  36203. if (!this._computeParticleVertex && !this.billboard) {
  36204. this._normal.x = this._fixedNormal32[idx];
  36205. this._normal.y = this._fixedNormal32[idx + 1];
  36206. this._normal.z = this._fixedNormal32[idx + 2];
  36207. 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];
  36208. 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;
  36209. 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;
  36210. 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;
  36211. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36212. 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;
  36213. 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;
  36214. }
  36215. if (this._computeParticleColor) {
  36216. this._colors32[colidx] = this._particle.color.r;
  36217. this._colors32[colidx + 1] = this._particle.color.g;
  36218. this._colors32[colidx + 2] = this._particle.color.b;
  36219. this._colors32[colidx + 3] = this._particle.color.a;
  36220. }
  36221. if (this._computeParticleTexture) {
  36222. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36223. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36224. }
  36225. }
  36226. index = idx + 3;
  36227. colorIndex = colidx + 4;
  36228. uvIndex = uvidx + 2;
  36229. }
  36230. if (update) {
  36231. if (this._computeParticleColor) {
  36232. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36233. }
  36234. if (this._computeParticleTexture) {
  36235. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36236. }
  36237. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36238. if (!this.mesh.areNormalsFrozen) {
  36239. if (this._computeParticleVertex || this.billboard) {
  36240. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36241. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36242. for (var i = 0; i < this._normals32.length; i++) {
  36243. this._fixedNormal32[i] = this._normals32[i];
  36244. }
  36245. }
  36246. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36247. }
  36248. }
  36249. this.afterUpdateParticles(start, end, update);
  36250. };
  36251. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36252. this._halfroll = this._roll * 0.5;
  36253. this._halfpitch = this._pitch * 0.5;
  36254. this._halfyaw = this._yaw * 0.5;
  36255. this._sinRoll = Math.sin(this._halfroll);
  36256. this._cosRoll = Math.cos(this._halfroll);
  36257. this._sinPitch = Math.sin(this._halfpitch);
  36258. this._cosPitch = Math.cos(this._halfpitch);
  36259. this._sinYaw = Math.sin(this._halfyaw);
  36260. this._cosYaw = Math.cos(this._halfyaw);
  36261. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36262. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36263. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36264. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36265. };
  36266. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36267. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36268. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36269. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36270. this._rotMatrix.m[3] = 0;
  36271. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36272. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36273. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36274. this._rotMatrix.m[7] = 0;
  36275. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36276. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36277. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36278. this._rotMatrix.m[11] = 0;
  36279. this._rotMatrix.m[12] = 0;
  36280. this._rotMatrix.m[13] = 0;
  36281. this._rotMatrix.m[14] = 0;
  36282. this._rotMatrix.m[15] = 1.0;
  36283. };
  36284. // dispose the SPS
  36285. SolidParticleSystem.prototype.dispose = function () {
  36286. this.mesh.dispose();
  36287. this.vars = null;
  36288. // drop references to internal big arrays for the GC
  36289. this._positions = null;
  36290. this._indices = null;
  36291. this._normals = null;
  36292. this._uvs = null;
  36293. this._colors = null;
  36294. this._positions32 = null;
  36295. this._normals32 = null;
  36296. this._fixedNormal32 = null;
  36297. this._uvs32 = null;
  36298. this._colors32 = null;
  36299. this.pickedParticles = null;
  36300. };
  36301. // Visibilty helpers
  36302. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36303. this.mesh.refreshBoundingInfo();
  36304. };
  36305. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36306. // getter and setter
  36307. get: function () {
  36308. return this._alwaysVisible;
  36309. },
  36310. set: function (val) {
  36311. this._alwaysVisible = val;
  36312. this.mesh.alwaysSelectAsActiveMesh = val;
  36313. },
  36314. enumerable: true,
  36315. configurable: true
  36316. });
  36317. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36318. // getters
  36319. get: function () {
  36320. return this._computeParticleRotation;
  36321. },
  36322. // Optimizer setters
  36323. set: function (val) {
  36324. this._computeParticleRotation = val;
  36325. },
  36326. enumerable: true,
  36327. configurable: true
  36328. });
  36329. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36330. get: function () {
  36331. return this._computeParticleColor;
  36332. },
  36333. set: function (val) {
  36334. this._computeParticleColor = val;
  36335. },
  36336. enumerable: true,
  36337. configurable: true
  36338. });
  36339. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36340. get: function () {
  36341. return this._computeParticleTexture;
  36342. },
  36343. set: function (val) {
  36344. this._computeParticleTexture = val;
  36345. },
  36346. enumerable: true,
  36347. configurable: true
  36348. });
  36349. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36350. get: function () {
  36351. return this._computeParticleVertex;
  36352. },
  36353. set: function (val) {
  36354. this._computeParticleVertex = val;
  36355. },
  36356. enumerable: true,
  36357. configurable: true
  36358. });
  36359. // =======================================================================
  36360. // Particle behavior logic
  36361. // these following methods may be overwritten by the user to fit his needs
  36362. // init : sets all particles first values and calls updateParticle to set them in space
  36363. // can be overwritten by the user
  36364. SolidParticleSystem.prototype.initParticles = function () {
  36365. };
  36366. // recycles a particle : can by overwritten by the user
  36367. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36368. return particle;
  36369. };
  36370. // updates a particle : can be overwritten by the user
  36371. // will be called on each particle by setParticles() :
  36372. // ex : just set a particle position or velocity and recycle conditions
  36373. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36374. return particle;
  36375. };
  36376. // updates a vertex of a particle : can be overwritten by the user
  36377. // will be called on each vertex particle by setParticles() :
  36378. // particle : the current particle
  36379. // vertex : the current index of the current particle
  36380. // pt : the index of the current vertex in the particle shape
  36381. // ex : just set a vertex particle position
  36382. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36383. return vertex;
  36384. };
  36385. // will be called before any other treatment by setParticles()
  36386. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36387. };
  36388. // will be called after all setParticles() treatments
  36389. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36390. };
  36391. return SolidParticleSystem;
  36392. })();
  36393. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36394. })(BABYLON || (BABYLON = {}));
  36395. 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}"};
  36396. 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={}));";
  36397. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36398. module.exports = BABYLON;
  36399. };