babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3037. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3038. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  3039. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3040. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3041. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3042. Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3045. return Tmp;
  3046. })();
  3047. BABYLON.Tmp = Tmp;
  3048. })(BABYLON || (BABYLON = {}));
  3049. var BABYLON;
  3050. (function (BABYLON) {
  3051. var Database = (function () {
  3052. function Database(urlToScene, callbackManifestChecked) {
  3053. // Handling various flavors of prefixed version of IndexedDB
  3054. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3055. this.callbackManifestChecked = callbackManifestChecked;
  3056. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3057. this.db = null;
  3058. this.enableSceneOffline = false;
  3059. this.enableTexturesOffline = false;
  3060. this.manifestVersionFound = 0;
  3061. this.mustUpdateRessources = false;
  3062. this.hasReachedQuota = false;
  3063. if (!Database.IDBStorageEnabled) {
  3064. this.callbackManifestChecked(true);
  3065. }
  3066. else {
  3067. this.checkManifestFile();
  3068. }
  3069. }
  3070. Database.prototype.checkManifestFile = function () {
  3071. var _this = this;
  3072. function noManifestFile() {
  3073. that.enableSceneOffline = false;
  3074. that.enableTexturesOffline = false;
  3075. that.callbackManifestChecked(false);
  3076. }
  3077. var that = this;
  3078. var timeStampUsed = false;
  3079. var manifestURL = this.currentSceneUrl + ".manifest";
  3080. var xhr = new XMLHttpRequest();
  3081. if (navigator.onLine) {
  3082. // Adding a timestamp to by-pass browsers' cache
  3083. timeStampUsed = true;
  3084. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3085. }
  3086. xhr.open("GET", manifestURL, true);
  3087. xhr.addEventListener("load", function () {
  3088. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3089. try {
  3090. var manifestFile = JSON.parse(xhr.response);
  3091. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3092. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3093. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3094. _this.manifestVersionFound = manifestFile.version;
  3095. }
  3096. if (_this.callbackManifestChecked) {
  3097. _this.callbackManifestChecked(true);
  3098. }
  3099. }
  3100. catch (ex) {
  3101. noManifestFile();
  3102. }
  3103. }
  3104. else {
  3105. noManifestFile();
  3106. }
  3107. }, false);
  3108. xhr.addEventListener("error", function (event) {
  3109. if (timeStampUsed) {
  3110. timeStampUsed = false;
  3111. // Let's retry without the timeStamp
  3112. // It could fail when coupled with HTML5 Offline API
  3113. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3114. xhr.open("GET", retryManifestURL, true);
  3115. xhr.send();
  3116. }
  3117. else {
  3118. noManifestFile();
  3119. }
  3120. }, false);
  3121. try {
  3122. xhr.send();
  3123. }
  3124. catch (ex) {
  3125. BABYLON.Tools.Error("Error on XHR send request.");
  3126. that.callbackManifestChecked(false);
  3127. }
  3128. };
  3129. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3130. var _this = this;
  3131. function handleError() {
  3132. that.isSupported = false;
  3133. if (errorCallback)
  3134. errorCallback();
  3135. }
  3136. var that = this;
  3137. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3138. // Your browser doesn't support IndexedDB
  3139. this.isSupported = false;
  3140. if (errorCallback)
  3141. errorCallback();
  3142. }
  3143. else {
  3144. // If the DB hasn't been opened or created yet
  3145. if (!this.db) {
  3146. this.hasReachedQuota = false;
  3147. this.isSupported = true;
  3148. var request = this.idbFactory.open("babylonjs", 1);
  3149. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3150. request.onerror = function (event) {
  3151. handleError();
  3152. };
  3153. // executes when a version change transaction cannot complete due to other active transactions
  3154. request.onblocked = function (event) {
  3155. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3156. handleError();
  3157. };
  3158. // DB has been opened successfully
  3159. request.onsuccess = function (event) {
  3160. _this.db = request.result;
  3161. successCallback();
  3162. };
  3163. // Initialization of the DB. Creating Scenes & Textures stores
  3164. request.onupgradeneeded = function (event) {
  3165. _this.db = (event.target).result;
  3166. try {
  3167. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3168. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3169. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3170. }
  3171. catch (ex) {
  3172. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3173. handleError();
  3174. }
  3175. };
  3176. }
  3177. else {
  3178. if (successCallback)
  3179. successCallback();
  3180. }
  3181. }
  3182. };
  3183. Database.prototype.loadImageFromDB = function (url, image) {
  3184. var _this = this;
  3185. var completeURL = Database.ReturnFullUrlLocation(url);
  3186. var saveAndLoadImage = function () {
  3187. if (!_this.hasReachedQuota && _this.db !== null) {
  3188. // the texture is not yet in the DB, let's try to save it
  3189. _this._saveImageIntoDBAsync(completeURL, image);
  3190. }
  3191. else {
  3192. image.src = url;
  3193. }
  3194. };
  3195. if (!this.mustUpdateRessources) {
  3196. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3197. }
  3198. else {
  3199. saveAndLoadImage();
  3200. }
  3201. };
  3202. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3203. if (this.isSupported && this.db !== null) {
  3204. var texture;
  3205. var transaction = this.db.transaction(["textures"]);
  3206. transaction.onabort = function (event) {
  3207. image.src = url;
  3208. };
  3209. transaction.oncomplete = function (event) {
  3210. var blobTextureURL;
  3211. if (texture) {
  3212. var URL = window.URL || window.webkitURL;
  3213. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3214. image.onerror = function () {
  3215. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3216. image.src = url;
  3217. };
  3218. image.src = blobTextureURL;
  3219. }
  3220. else {
  3221. notInDBCallback();
  3222. }
  3223. };
  3224. var getRequest = transaction.objectStore("textures").get(url);
  3225. getRequest.onsuccess = function (event) {
  3226. texture = (event.target).result;
  3227. };
  3228. getRequest.onerror = function (event) {
  3229. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3230. image.src = url;
  3231. };
  3232. }
  3233. else {
  3234. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3235. image.src = url;
  3236. }
  3237. };
  3238. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3239. var _this = this;
  3240. if (this.isSupported) {
  3241. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3242. var generateBlobUrl = function () {
  3243. var blobTextureURL;
  3244. if (blob) {
  3245. var URL = window.URL || window.webkitURL;
  3246. try {
  3247. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3248. }
  3249. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3250. catch (ex) {
  3251. blobTextureURL = URL.createObjectURL(blob);
  3252. }
  3253. }
  3254. image.src = blobTextureURL;
  3255. };
  3256. if (Database.IsUASupportingBlobStorage) {
  3257. var xhr = new XMLHttpRequest(), blob;
  3258. xhr.open("GET", url, true);
  3259. xhr.responseType = "blob";
  3260. xhr.addEventListener("load", function () {
  3261. if (xhr.status === 200) {
  3262. // Blob as response (XHR2)
  3263. blob = xhr.response;
  3264. var transaction = _this.db.transaction(["textures"], "readwrite");
  3265. // the transaction could abort because of a QuotaExceededError error
  3266. transaction.onabort = function (event) {
  3267. try {
  3268. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3269. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3270. this.hasReachedQuota = true;
  3271. }
  3272. }
  3273. catch (ex) { }
  3274. generateBlobUrl();
  3275. };
  3276. transaction.oncomplete = function (event) {
  3277. generateBlobUrl();
  3278. };
  3279. var newTexture = { textureUrl: url, data: blob };
  3280. try {
  3281. // Put the blob into the dabase
  3282. var addRequest = transaction.objectStore("textures").put(newTexture);
  3283. addRequest.onsuccess = function (event) {
  3284. };
  3285. addRequest.onerror = function (event) {
  3286. generateBlobUrl();
  3287. };
  3288. }
  3289. catch (ex) {
  3290. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3291. if (ex.code === 25) {
  3292. Database.IsUASupportingBlobStorage = false;
  3293. }
  3294. image.src = url;
  3295. }
  3296. }
  3297. else {
  3298. image.src = url;
  3299. }
  3300. }, false);
  3301. xhr.addEventListener("error", function (event) {
  3302. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3303. image.src = url;
  3304. }, false);
  3305. xhr.send();
  3306. }
  3307. else {
  3308. image.src = url;
  3309. }
  3310. }
  3311. else {
  3312. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3313. image.src = url;
  3314. }
  3315. };
  3316. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3317. var _this = this;
  3318. var updateVersion = function (event) {
  3319. // the version is not yet in the DB or we need to update it
  3320. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3321. };
  3322. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3323. };
  3324. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3325. var _this = this;
  3326. if (this.isSupported) {
  3327. var version;
  3328. try {
  3329. var transaction = this.db.transaction(["versions"]);
  3330. transaction.oncomplete = function (event) {
  3331. if (version) {
  3332. // If the version in the JSON file is > than the version in DB
  3333. if (_this.manifestVersionFound > version.data) {
  3334. _this.mustUpdateRessources = true;
  3335. updateInDBCallback();
  3336. }
  3337. else {
  3338. callback(version.data);
  3339. }
  3340. }
  3341. else {
  3342. _this.mustUpdateRessources = true;
  3343. updateInDBCallback();
  3344. }
  3345. };
  3346. transaction.onabort = function (event) {
  3347. callback(-1);
  3348. };
  3349. var getRequest = transaction.objectStore("versions").get(url);
  3350. getRequest.onsuccess = function (event) {
  3351. version = (event.target).result;
  3352. };
  3353. getRequest.onerror = function (event) {
  3354. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3355. callback(-1);
  3356. };
  3357. }
  3358. catch (ex) {
  3359. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3360. callback(-1);
  3361. }
  3362. }
  3363. else {
  3364. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3365. callback(-1);
  3366. }
  3367. };
  3368. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3369. var _this = this;
  3370. if (this.isSupported && !this.hasReachedQuota) {
  3371. try {
  3372. // Open a transaction to the database
  3373. var transaction = this.db.transaction(["versions"], "readwrite");
  3374. // the transaction could abort because of a QuotaExceededError error
  3375. transaction.onabort = function (event) {
  3376. try {
  3377. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3378. _this.hasReachedQuota = true;
  3379. }
  3380. }
  3381. catch (ex) { }
  3382. callback(-1);
  3383. };
  3384. transaction.oncomplete = function (event) {
  3385. callback(_this.manifestVersionFound);
  3386. };
  3387. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3388. // Put the scene into the database
  3389. var addRequest = transaction.objectStore("versions").put(newVersion);
  3390. addRequest.onsuccess = function (event) {
  3391. };
  3392. addRequest.onerror = function (event) {
  3393. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3394. };
  3395. }
  3396. catch (ex) {
  3397. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3398. callback(-1);
  3399. }
  3400. }
  3401. else {
  3402. callback(-1);
  3403. }
  3404. };
  3405. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3406. var _this = this;
  3407. var completeUrl = Database.ReturnFullUrlLocation(url);
  3408. var saveAndLoadFile = function (event) {
  3409. // the scene is not yet in the DB, let's try to save it
  3410. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3411. };
  3412. this._checkVersionFromDB(completeUrl, function (version) {
  3413. if (version !== -1) {
  3414. if (!_this.mustUpdateRessources) {
  3415. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3416. }
  3417. else {
  3418. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3419. }
  3420. }
  3421. else {
  3422. errorCallback();
  3423. }
  3424. });
  3425. };
  3426. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3427. if (this.isSupported) {
  3428. var targetStore;
  3429. if (url.indexOf(".babylon") !== -1) {
  3430. targetStore = "scenes";
  3431. }
  3432. else {
  3433. targetStore = "textures";
  3434. }
  3435. var file;
  3436. var transaction = this.db.transaction([targetStore]);
  3437. transaction.oncomplete = function (event) {
  3438. if (file) {
  3439. callback(file.data);
  3440. }
  3441. else {
  3442. notInDBCallback();
  3443. }
  3444. };
  3445. transaction.onabort = function (event) {
  3446. notInDBCallback();
  3447. };
  3448. var getRequest = transaction.objectStore(targetStore).get(url);
  3449. getRequest.onsuccess = function (event) {
  3450. file = (event.target).result;
  3451. };
  3452. getRequest.onerror = function (event) {
  3453. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3454. notInDBCallback();
  3455. };
  3456. }
  3457. else {
  3458. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3459. callback();
  3460. }
  3461. };
  3462. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3463. var _this = this;
  3464. if (this.isSupported) {
  3465. var targetStore;
  3466. if (url.indexOf(".babylon") !== -1) {
  3467. targetStore = "scenes";
  3468. }
  3469. else {
  3470. targetStore = "textures";
  3471. }
  3472. // Create XHR
  3473. var xhr = new XMLHttpRequest(), fileData;
  3474. xhr.open("GET", url, true);
  3475. if (useArrayBuffer) {
  3476. xhr.responseType = "arraybuffer";
  3477. }
  3478. xhr.onprogress = progressCallback;
  3479. xhr.addEventListener("load", function () {
  3480. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3481. // Blob as response (XHR2)
  3482. //fileData = xhr.responseText;
  3483. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3484. if (!_this.hasReachedQuota) {
  3485. // Open a transaction to the database
  3486. var transaction = _this.db.transaction([targetStore], "readwrite");
  3487. // the transaction could abort because of a QuotaExceededError error
  3488. transaction.onabort = function (event) {
  3489. try {
  3490. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3491. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3492. this.hasReachedQuota = true;
  3493. }
  3494. }
  3495. catch (ex) { }
  3496. callback(fileData);
  3497. };
  3498. transaction.oncomplete = function (event) {
  3499. callback(fileData);
  3500. };
  3501. var newFile;
  3502. if (targetStore === "scenes") {
  3503. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3504. }
  3505. else {
  3506. newFile = { textureUrl: url, data: fileData };
  3507. }
  3508. try {
  3509. // Put the scene into the database
  3510. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3511. addRequest.onsuccess = function (event) {
  3512. };
  3513. addRequest.onerror = function (event) {
  3514. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3515. };
  3516. }
  3517. catch (ex) {
  3518. callback(fileData);
  3519. }
  3520. }
  3521. else {
  3522. callback(fileData);
  3523. }
  3524. }
  3525. else {
  3526. callback();
  3527. }
  3528. }, false);
  3529. xhr.addEventListener("error", function (event) {
  3530. BABYLON.Tools.Error("error on XHR request.");
  3531. callback();
  3532. }, false);
  3533. xhr.send();
  3534. }
  3535. else {
  3536. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3537. callback();
  3538. }
  3539. };
  3540. Database.IsUASupportingBlobStorage = true;
  3541. Database.IDBStorageEnabled = true;
  3542. Database.parseURL = function (url) {
  3543. var a = document.createElement('a');
  3544. a.href = url;
  3545. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3546. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3547. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3548. return absLocation;
  3549. };
  3550. Database.ReturnFullUrlLocation = function (url) {
  3551. if (url.indexOf("http:/") === -1) {
  3552. return (Database.parseURL(window.location.href) + url);
  3553. }
  3554. else {
  3555. return url;
  3556. }
  3557. };
  3558. return Database;
  3559. })();
  3560. BABYLON.Database = Database;
  3561. })(BABYLON || (BABYLON = {}));
  3562. var BABYLON;
  3563. (function (BABYLON) {
  3564. var Internals;
  3565. (function (Internals) {
  3566. /*
  3567. * Based on jsTGALoader - Javascript loader for TGA file
  3568. * By Vincent Thibault
  3569. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3570. */
  3571. var TGATools = (function () {
  3572. function TGATools() {
  3573. }
  3574. TGATools.GetTGAHeader = function (data) {
  3575. var offset = 0;
  3576. var header = {
  3577. id_length: data[offset++],
  3578. colormap_type: data[offset++],
  3579. image_type: data[offset++],
  3580. colormap_index: data[offset++] | data[offset++] << 8,
  3581. colormap_length: data[offset++] | data[offset++] << 8,
  3582. colormap_size: data[offset++],
  3583. origin: [
  3584. data[offset++] | data[offset++] << 8,
  3585. data[offset++] | data[offset++] << 8
  3586. ],
  3587. width: data[offset++] | data[offset++] << 8,
  3588. height: data[offset++] | data[offset++] << 8,
  3589. pixel_size: data[offset++],
  3590. flags: data[offset++]
  3591. };
  3592. return header;
  3593. };
  3594. TGATools.UploadContent = function (gl, data) {
  3595. // Not enough data to contain header ?
  3596. if (data.length < 19) {
  3597. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3598. return;
  3599. }
  3600. // Read Header
  3601. var offset = 18;
  3602. var header = TGATools.GetTGAHeader(data);
  3603. // Assume it's a valid Targa file.
  3604. if (header.id_length + offset > data.length) {
  3605. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3606. return;
  3607. }
  3608. // Skip not needed data
  3609. offset += header.id_length;
  3610. var use_rle = false;
  3611. var use_pal = false;
  3612. var use_rgb = false;
  3613. var use_grey = false;
  3614. // Get some informations.
  3615. switch (header.image_type) {
  3616. case TGATools._TYPE_RLE_INDEXED:
  3617. use_rle = true;
  3618. case TGATools._TYPE_INDEXED:
  3619. use_pal = true;
  3620. break;
  3621. case TGATools._TYPE_RLE_RGB:
  3622. use_rle = true;
  3623. case TGATools._TYPE_RGB:
  3624. use_rgb = true;
  3625. break;
  3626. case TGATools._TYPE_RLE_GREY:
  3627. use_rle = true;
  3628. case TGATools._TYPE_GREY:
  3629. use_grey = true;
  3630. break;
  3631. }
  3632. var pixel_data;
  3633. var numAlphaBits = header.flags & 0xf;
  3634. var pixel_size = header.pixel_size >> 3;
  3635. var pixel_total = header.width * header.height * pixel_size;
  3636. // Read palettes
  3637. var palettes;
  3638. if (use_pal) {
  3639. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3640. }
  3641. // Read LRE
  3642. if (use_rle) {
  3643. pixel_data = new Uint8Array(pixel_total);
  3644. var c, count, i;
  3645. var localOffset = 0;
  3646. var pixels = new Uint8Array(pixel_size);
  3647. while (offset < pixel_total && localOffset < pixel_total) {
  3648. c = data[offset++];
  3649. count = (c & 0x7f) + 1;
  3650. // RLE pixels
  3651. if (c & 0x80) {
  3652. // Bind pixel tmp array
  3653. for (i = 0; i < pixel_size; ++i) {
  3654. pixels[i] = data[offset++];
  3655. }
  3656. // Copy pixel array
  3657. for (i = 0; i < count; ++i) {
  3658. pixel_data.set(pixels, localOffset + i * pixel_size);
  3659. }
  3660. localOffset += pixel_size * count;
  3661. }
  3662. else {
  3663. count *= pixel_size;
  3664. for (i = 0; i < count; ++i) {
  3665. pixel_data[localOffset + i] = data[offset++];
  3666. }
  3667. localOffset += count;
  3668. }
  3669. }
  3670. }
  3671. else {
  3672. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3673. }
  3674. // Load to texture
  3675. var x_start, y_start, x_step, y_step, y_end, x_end;
  3676. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3677. default:
  3678. case TGATools._ORIGIN_UL:
  3679. x_start = 0;
  3680. x_step = 1;
  3681. x_end = header.width;
  3682. y_start = 0;
  3683. y_step = 1;
  3684. y_end = header.height;
  3685. break;
  3686. case TGATools._ORIGIN_BL:
  3687. x_start = 0;
  3688. x_step = 1;
  3689. x_end = header.width;
  3690. y_start = header.height - 1;
  3691. y_step = -1;
  3692. y_end = -1;
  3693. break;
  3694. case TGATools._ORIGIN_UR:
  3695. x_start = header.width - 1;
  3696. x_step = -1;
  3697. x_end = -1;
  3698. y_start = 0;
  3699. y_step = 1;
  3700. y_end = header.height;
  3701. break;
  3702. case TGATools._ORIGIN_BR:
  3703. x_start = header.width - 1;
  3704. x_step = -1;
  3705. x_end = -1;
  3706. y_start = header.height - 1;
  3707. y_step = -1;
  3708. y_end = -1;
  3709. break;
  3710. }
  3711. // Load the specify method
  3712. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3713. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3715. };
  3716. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3717. var image = pixel_data, colormap = palettes;
  3718. var width = header.width, height = header.height;
  3719. var color, i = 0, x, y;
  3720. var imageData = new Uint8Array(width * height * 4);
  3721. for (y = y_start; y !== y_end; y += y_step) {
  3722. for (x = x_start; x !== x_end; x += x_step, i++) {
  3723. color = image[i];
  3724. imageData[(x + width * y) * 4 + 3] = 255;
  3725. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3726. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3727. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3728. }
  3729. }
  3730. return imageData;
  3731. };
  3732. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3733. var image = pixel_data;
  3734. var width = header.width, height = header.height;
  3735. var color, i = 0, x, y;
  3736. var imageData = new Uint8Array(width * height * 4);
  3737. for (y = y_start; y !== y_end; y += y_step) {
  3738. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3739. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3740. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3741. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3742. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3743. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3744. }
  3745. }
  3746. return imageData;
  3747. };
  3748. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3749. var image = pixel_data;
  3750. var width = header.width, height = header.height;
  3751. var i = 0, x, y;
  3752. var imageData = new Uint8Array(width * height * 4);
  3753. for (y = y_start; y !== y_end; y += y_step) {
  3754. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3755. imageData[(x + width * y) * 4 + 3] = 255;
  3756. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3757. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3758. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3759. }
  3760. }
  3761. return imageData;
  3762. };
  3763. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3764. var image = pixel_data;
  3765. var width = header.width, height = header.height;
  3766. var i = 0, x, y;
  3767. var imageData = new Uint8Array(width * height * 4);
  3768. for (y = y_start; y !== y_end; y += y_step) {
  3769. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3770. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3771. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3772. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3773. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3774. }
  3775. }
  3776. return imageData;
  3777. };
  3778. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3779. var image = pixel_data;
  3780. var width = header.width, height = header.height;
  3781. var color, i = 0, x, y;
  3782. var imageData = new Uint8Array(width * height * 4);
  3783. for (y = y_start; y !== y_end; y += y_step) {
  3784. for (x = x_start; x !== x_end; x += x_step, i++) {
  3785. color = image[i];
  3786. imageData[(x + width * y) * 4 + 0] = color;
  3787. imageData[(x + width * y) * 4 + 1] = color;
  3788. imageData[(x + width * y) * 4 + 2] = color;
  3789. imageData[(x + width * y) * 4 + 3] = 255;
  3790. }
  3791. }
  3792. return imageData;
  3793. };
  3794. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3795. var image = pixel_data;
  3796. var width = header.width, height = header.height;
  3797. var i = 0, x, y;
  3798. var imageData = new Uint8Array(width * height * 4);
  3799. for (y = y_start; y !== y_end; y += y_step) {
  3800. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3801. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3802. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3803. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3805. }
  3806. }
  3807. return imageData;
  3808. };
  3809. TGATools._TYPE_NO_DATA = 0;
  3810. TGATools._TYPE_INDEXED = 1;
  3811. TGATools._TYPE_RGB = 2;
  3812. TGATools._TYPE_GREY = 3;
  3813. TGATools._TYPE_RLE_INDEXED = 9;
  3814. TGATools._TYPE_RLE_RGB = 10;
  3815. TGATools._TYPE_RLE_GREY = 11;
  3816. TGATools._ORIGIN_MASK = 0x30;
  3817. TGATools._ORIGIN_SHIFT = 0x04;
  3818. TGATools._ORIGIN_BL = 0x00;
  3819. TGATools._ORIGIN_BR = 0x01;
  3820. TGATools._ORIGIN_UL = 0x02;
  3821. TGATools._ORIGIN_UR = 0x03;
  3822. return TGATools;
  3823. })();
  3824. Internals.TGATools = TGATools;
  3825. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3826. })(BABYLON || (BABYLON = {}));
  3827. var BABYLON;
  3828. (function (BABYLON) {
  3829. var SmartArray = (function () {
  3830. function SmartArray(capacity) {
  3831. this.length = 0;
  3832. this._duplicateId = 0;
  3833. this.data = new Array(capacity);
  3834. this._id = SmartArray._GlobalId++;
  3835. }
  3836. SmartArray.prototype.push = function (value) {
  3837. this.data[this.length++] = value;
  3838. if (this.length > this.data.length) {
  3839. this.data.length *= 2;
  3840. }
  3841. if (!value.__smartArrayFlags) {
  3842. value.__smartArrayFlags = {};
  3843. }
  3844. value.__smartArrayFlags[this._id] = this._duplicateId;
  3845. };
  3846. SmartArray.prototype.pushNoDuplicate = function (value) {
  3847. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3848. return;
  3849. }
  3850. this.push(value);
  3851. };
  3852. SmartArray.prototype.sort = function (compareFn) {
  3853. this.data.sort(compareFn);
  3854. };
  3855. SmartArray.prototype.reset = function () {
  3856. this.length = 0;
  3857. this._duplicateId++;
  3858. };
  3859. SmartArray.prototype.concat = function (array) {
  3860. if (array.length === 0) {
  3861. return;
  3862. }
  3863. if (this.length + array.length > this.data.length) {
  3864. this.data.length = (this.length + array.length) * 2;
  3865. }
  3866. for (var index = 0; index < array.length; index++) {
  3867. this.data[this.length++] = (array.data || array)[index];
  3868. }
  3869. };
  3870. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3871. if (array.length === 0) {
  3872. return;
  3873. }
  3874. if (this.length + array.length > this.data.length) {
  3875. this.data.length = (this.length + array.length) * 2;
  3876. }
  3877. for (var index = 0; index < array.length; index++) {
  3878. var item = (array.data || array)[index];
  3879. this.pushNoDuplicate(item);
  3880. }
  3881. };
  3882. SmartArray.prototype.indexOf = function (value) {
  3883. var position = this.data.indexOf(value);
  3884. if (position >= this.length) {
  3885. return -1;
  3886. }
  3887. return position;
  3888. };
  3889. // Statics
  3890. SmartArray._GlobalId = 0;
  3891. return SmartArray;
  3892. })();
  3893. BABYLON.SmartArray = SmartArray;
  3894. })(BABYLON || (BABYLON = {}));
  3895. var BABYLON;
  3896. (function (BABYLON) {
  3897. var SmartCollection = (function () {
  3898. function SmartCollection(capacity) {
  3899. if (capacity === void 0) { capacity = 10; }
  3900. this.count = 0;
  3901. this._initialCapacity = capacity;
  3902. this.items = {};
  3903. this._keys = new Array(this._initialCapacity);
  3904. }
  3905. SmartCollection.prototype.add = function (key, item) {
  3906. if (this.items[key] != undefined) {
  3907. return -1;
  3908. }
  3909. this.items[key] = item;
  3910. //literal keys are always strings, but we keep source type of key in _keys array
  3911. this._keys[this.count++] = key;
  3912. if (this.count > this._keys.length) {
  3913. this._keys.length *= 2;
  3914. }
  3915. return this.count;
  3916. };
  3917. SmartCollection.prototype.remove = function (key) {
  3918. if (this.items[key] == undefined) {
  3919. return -1;
  3920. }
  3921. return this.removeItemOfIndex(this.indexOf(key));
  3922. };
  3923. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3924. if (index < this.count && index > -1) {
  3925. delete this.items[this._keys[index]];
  3926. //here, shifting by hand is better optimised than .splice
  3927. while (index < this.count) {
  3928. this._keys[index] = this._keys[index + 1];
  3929. index++;
  3930. }
  3931. }
  3932. else {
  3933. return -1;
  3934. }
  3935. return --this.count;
  3936. };
  3937. SmartCollection.prototype.indexOf = function (key) {
  3938. for (var i = 0; i !== this.count; i++) {
  3939. if (this._keys[i] === key) {
  3940. return i;
  3941. }
  3942. }
  3943. return -1;
  3944. };
  3945. SmartCollection.prototype.item = function (key) {
  3946. return this.items[key];
  3947. };
  3948. SmartCollection.prototype.getAllKeys = function () {
  3949. if (this.count > 0) {
  3950. var keys = new Array(this.count);
  3951. for (var i = 0; i < this.count; i++) {
  3952. keys[i] = this._keys[i];
  3953. }
  3954. return keys;
  3955. }
  3956. else {
  3957. return undefined;
  3958. }
  3959. };
  3960. SmartCollection.prototype.getKeyByIndex = function (index) {
  3961. if (index < this.count && index > -1) {
  3962. return this._keys[index];
  3963. }
  3964. else {
  3965. return undefined;
  3966. }
  3967. };
  3968. SmartCollection.prototype.getItemByIndex = function (index) {
  3969. if (index < this.count && index > -1) {
  3970. return this.items[this._keys[index]];
  3971. }
  3972. else {
  3973. return undefined;
  3974. }
  3975. };
  3976. SmartCollection.prototype.empty = function () {
  3977. if (this.count > 0) {
  3978. this.count = 0;
  3979. this.items = {};
  3980. this._keys = new Array(this._initialCapacity);
  3981. }
  3982. };
  3983. SmartCollection.prototype.forEach = function (block) {
  3984. var key;
  3985. for (key in this.items) {
  3986. if (this.items.hasOwnProperty(key)) {
  3987. block(this.items[key]);
  3988. }
  3989. }
  3990. };
  3991. return SmartCollection;
  3992. })();
  3993. BABYLON.SmartCollection = SmartCollection;
  3994. })(BABYLON || (BABYLON = {}));
  3995. var BABYLON;
  3996. (function (BABYLON) {
  3997. // Screenshots
  3998. var screenshotCanvas;
  3999. var cloneValue = function (source, destinationObject) {
  4000. if (!source)
  4001. return null;
  4002. if (source instanceof BABYLON.Mesh) {
  4003. return null;
  4004. }
  4005. if (source instanceof BABYLON.SubMesh) {
  4006. return source.clone(destinationObject);
  4007. }
  4008. else if (source.clone) {
  4009. return source.clone();
  4010. }
  4011. return null;
  4012. };
  4013. var Tools = (function () {
  4014. function Tools() {
  4015. }
  4016. Tools.Instantiate = function (className) {
  4017. var arr = className.split(".");
  4018. var fn = (window || this);
  4019. for (var i = 0, len = arr.length; i < len; i++) {
  4020. fn = fn[arr[i]];
  4021. }
  4022. if (typeof fn !== "function") {
  4023. return null;
  4024. }
  4025. return fn;
  4026. };
  4027. Tools.GetConstructorName = function (obj) {
  4028. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  4029. var cname = str.match(/function\s(\w*)/)[1];
  4030. var aliases = ["", "anonymous", "Anonymous"];
  4031. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  4032. };
  4033. Tools.ToHex = function (i) {
  4034. var str = i.toString(16);
  4035. if (i <= 15) {
  4036. return ("0" + str).toUpperCase();
  4037. }
  4038. return str.toUpperCase();
  4039. };
  4040. Tools.SetImmediate = function (action) {
  4041. if (window.setImmediate) {
  4042. window.setImmediate(action);
  4043. }
  4044. else {
  4045. setTimeout(action, 1);
  4046. }
  4047. };
  4048. Tools.IsExponentOfTwo = function (value) {
  4049. var count = 1;
  4050. do {
  4051. count *= 2;
  4052. } while (count < value);
  4053. return count === value;
  4054. };
  4055. Tools.GetExponentOfTwo = function (value, max) {
  4056. var count = 1;
  4057. do {
  4058. count *= 2;
  4059. } while (count < value);
  4060. if (count > max)
  4061. count = max;
  4062. return count;
  4063. };
  4064. Tools.GetFilename = function (path) {
  4065. var index = path.lastIndexOf("/");
  4066. if (index < 0)
  4067. return path;
  4068. return path.substring(index + 1);
  4069. };
  4070. Tools.GetDOMTextContent = function (element) {
  4071. var result = "";
  4072. var child = element.firstChild;
  4073. while (child) {
  4074. if (child.nodeType === 3) {
  4075. result += child.textContent;
  4076. }
  4077. child = child.nextSibling;
  4078. }
  4079. return result;
  4080. };
  4081. Tools.ToDegrees = function (angle) {
  4082. return angle * 180 / Math.PI;
  4083. };
  4084. Tools.ToRadians = function (angle) {
  4085. return angle * Math.PI / 180;
  4086. };
  4087. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4088. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4089. var output = "";
  4090. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4091. var i = 0;
  4092. var bytes = new Uint8Array(buffer);
  4093. while (i < bytes.length) {
  4094. chr1 = bytes[i++];
  4095. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4096. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4097. enc1 = chr1 >> 2;
  4098. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4099. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4100. enc4 = chr3 & 63;
  4101. if (isNaN(chr2)) {
  4102. enc3 = enc4 = 64;
  4103. }
  4104. else if (isNaN(chr3)) {
  4105. enc4 = 64;
  4106. }
  4107. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4108. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4109. }
  4110. return "data:image/png;base64," + output;
  4111. };
  4112. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4119. }
  4120. return {
  4121. minimum: minimum,
  4122. maximum: maximum
  4123. };
  4124. };
  4125. Tools.ExtractMinAndMax = function (positions, start, count) {
  4126. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4127. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4128. for (var index = start; index < start + count; index++) {
  4129. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4130. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4131. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4132. }
  4133. return {
  4134. minimum: minimum,
  4135. maximum: maximum
  4136. };
  4137. };
  4138. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4139. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4140. return undefined;
  4141. return Array.isArray(obj) ? obj : [obj];
  4142. };
  4143. // Misc.
  4144. Tools.GetPointerPrefix = function () {
  4145. var eventPrefix = "pointer";
  4146. // Check if pointer events are supported
  4147. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4148. eventPrefix = "mouse";
  4149. }
  4150. return eventPrefix;
  4151. };
  4152. Tools.QueueNewFrame = function (func) {
  4153. if (window.requestAnimationFrame)
  4154. window.requestAnimationFrame(func);
  4155. else if (window.msRequestAnimationFrame)
  4156. window.msRequestAnimationFrame(func);
  4157. else if (window.webkitRequestAnimationFrame)
  4158. window.webkitRequestAnimationFrame(func);
  4159. else if (window.mozRequestAnimationFrame)
  4160. window.mozRequestAnimationFrame(func);
  4161. else if (window.oRequestAnimationFrame)
  4162. window.oRequestAnimationFrame(func);
  4163. else {
  4164. window.setTimeout(func, 16);
  4165. }
  4166. };
  4167. Tools.RequestFullscreen = function (element) {
  4168. if (element.requestFullscreen)
  4169. element.requestFullscreen();
  4170. else if (element.msRequestFullscreen)
  4171. element.msRequestFullscreen();
  4172. else if (element.webkitRequestFullscreen)
  4173. element.webkitRequestFullscreen();
  4174. else if (element.mozRequestFullScreen)
  4175. element.mozRequestFullScreen();
  4176. };
  4177. Tools.ExitFullscreen = function () {
  4178. if (document.exitFullscreen) {
  4179. document.exitFullscreen();
  4180. }
  4181. else if (document.mozCancelFullScreen) {
  4182. document.mozCancelFullScreen();
  4183. }
  4184. else if (document.webkitCancelFullScreen) {
  4185. document.webkitCancelFullScreen();
  4186. }
  4187. else if (document.msCancelFullScreen) {
  4188. document.msCancelFullScreen();
  4189. }
  4190. };
  4191. // External files
  4192. Tools.CleanUrl = function (url) {
  4193. url = url.replace(/#/mg, "%23");
  4194. return url;
  4195. };
  4196. Tools.LoadImage = function (url, onload, onerror, database) {
  4197. if (url instanceof ArrayBuffer) {
  4198. url = Tools.EncodeArrayBufferTobase64(url);
  4199. }
  4200. url = Tools.CleanUrl(url);
  4201. var img = new Image();
  4202. if (url.substr(0, 5) !== "data:") {
  4203. if (Tools.CorsBehavior) {
  4204. switch (typeof (Tools.CorsBehavior)) {
  4205. case "function":
  4206. var result = Tools.CorsBehavior(url);
  4207. if (result) {
  4208. img.crossOrigin = result;
  4209. }
  4210. break;
  4211. case "string":
  4212. default:
  4213. img.crossOrigin = Tools.CorsBehavior;
  4214. break;
  4215. }
  4216. }
  4217. }
  4218. img.onload = function () {
  4219. onload(img);
  4220. };
  4221. img.onerror = function (err) {
  4222. Tools.Error("Error while trying to load texture: " + url);
  4223. if (Tools.UseFallbackTexture) {
  4224. 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";
  4225. onload(img);
  4226. }
  4227. else {
  4228. onerror();
  4229. }
  4230. };
  4231. var noIndexedDB = function () {
  4232. img.src = url;
  4233. };
  4234. var loadFromIndexedDB = function () {
  4235. database.loadImageFromDB(url, img);
  4236. };
  4237. //ANY database to do!
  4238. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4239. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4240. }
  4241. else {
  4242. if (url.indexOf("file:") === -1) {
  4243. noIndexedDB();
  4244. }
  4245. else {
  4246. try {
  4247. var textureName = url.substring(5);
  4248. var blobURL;
  4249. try {
  4250. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4251. }
  4252. catch (ex) {
  4253. // Chrome doesn't support oneTimeOnly parameter
  4254. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4255. }
  4256. img.src = blobURL;
  4257. }
  4258. catch (e) {
  4259. img.src = null;
  4260. }
  4261. }
  4262. }
  4263. return img;
  4264. };
  4265. //ANY
  4266. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4267. url = Tools.CleanUrl(url);
  4268. var noIndexedDB = function () {
  4269. var request = new XMLHttpRequest();
  4270. var loadUrl = Tools.BaseUrl + url;
  4271. request.open('GET', loadUrl, true);
  4272. if (useArrayBuffer) {
  4273. request.responseType = "arraybuffer";
  4274. }
  4275. request.onprogress = progressCallBack;
  4276. request.onreadystatechange = function () {
  4277. if (request.readyState === 4) {
  4278. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4279. callback(!useArrayBuffer ? request.responseText : request.response);
  4280. }
  4281. else {
  4282. if (onError) {
  4283. onError();
  4284. }
  4285. else {
  4286. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4287. }
  4288. }
  4289. }
  4290. };
  4291. request.send(null);
  4292. };
  4293. var loadFromIndexedDB = function () {
  4294. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4295. };
  4296. if (url.indexOf("file:") !== -1) {
  4297. var fileName = url.substring(5);
  4298. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4299. }
  4300. else {
  4301. // Caching all files
  4302. if (database && database.enableSceneOffline) {
  4303. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4304. }
  4305. else {
  4306. noIndexedDB();
  4307. }
  4308. }
  4309. };
  4310. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4311. var reader = new FileReader();
  4312. reader.onload = function (e) {
  4313. //target doesn't have result from ts 1.3
  4314. callback(e.target['result']);
  4315. };
  4316. reader.onprogress = progressCallback;
  4317. reader.readAsDataURL(fileToLoad);
  4318. };
  4319. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4320. var reader = new FileReader();
  4321. reader.onerror = function (e) {
  4322. Tools.Log("Error while reading file: " + fileToLoad.name);
  4323. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4324. };
  4325. reader.onload = function (e) {
  4326. //target doesn't have result from ts 1.3
  4327. callback(e.target['result']);
  4328. };
  4329. reader.onprogress = progressCallBack;
  4330. if (!useArrayBuffer) {
  4331. // Asynchronous read
  4332. reader.readAsText(fileToLoad);
  4333. }
  4334. else {
  4335. reader.readAsArrayBuffer(fileToLoad);
  4336. }
  4337. };
  4338. //returns a downloadable url to a file content.
  4339. Tools.FileAsURL = function (content) {
  4340. var fileBlob = new Blob([content]);
  4341. var url = window.URL || window.webkitURL;
  4342. var link = url.createObjectURL(fileBlob);
  4343. return link;
  4344. };
  4345. // Misc.
  4346. Tools.Clamp = function (value, min, max) {
  4347. if (min === void 0) { min = 0; }
  4348. if (max === void 0) { max = 1; }
  4349. return Math.min(max, Math.max(min, value));
  4350. };
  4351. // Returns -1 when value is a negative number and
  4352. // +1 when value is a positive number.
  4353. Tools.Sign = function (value) {
  4354. value = +value; // convert to a number
  4355. if (value === 0 || isNaN(value))
  4356. return value;
  4357. return value > 0 ? 1 : -1;
  4358. };
  4359. Tools.Format = function (value, decimals) {
  4360. if (decimals === void 0) { decimals = 2; }
  4361. return value.toFixed(decimals);
  4362. };
  4363. Tools.CheckExtends = function (v, min, max) {
  4364. if (v.x < min.x)
  4365. min.x = v.x;
  4366. if (v.y < min.y)
  4367. min.y = v.y;
  4368. if (v.z < min.z)
  4369. min.z = v.z;
  4370. if (v.x > max.x)
  4371. max.x = v.x;
  4372. if (v.y > max.y)
  4373. max.y = v.y;
  4374. if (v.z > max.z)
  4375. max.z = v.z;
  4376. };
  4377. Tools.WithinEpsilon = function (a, b, epsilon) {
  4378. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4379. var num = a - b;
  4380. return -epsilon <= num && num <= epsilon;
  4381. };
  4382. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4383. for (var prop in source) {
  4384. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4385. continue;
  4386. }
  4387. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4388. continue;
  4389. }
  4390. var sourceValue = source[prop];
  4391. var typeOfSourceValue = typeof sourceValue;
  4392. if (typeOfSourceValue === "function") {
  4393. continue;
  4394. }
  4395. if (typeOfSourceValue === "object") {
  4396. if (sourceValue instanceof Array) {
  4397. destination[prop] = [];
  4398. if (sourceValue.length > 0) {
  4399. if (typeof sourceValue[0] == "object") {
  4400. for (var index = 0; index < sourceValue.length; index++) {
  4401. var clonedValue = cloneValue(sourceValue[index], destination);
  4402. if (destination[prop].indexOf(clonedValue) === -1) {
  4403. destination[prop].push(clonedValue);
  4404. }
  4405. }
  4406. }
  4407. else {
  4408. destination[prop] = sourceValue.slice(0);
  4409. }
  4410. }
  4411. }
  4412. else {
  4413. destination[prop] = cloneValue(sourceValue, destination);
  4414. }
  4415. }
  4416. else {
  4417. destination[prop] = sourceValue;
  4418. }
  4419. }
  4420. };
  4421. Tools.IsEmpty = function (obj) {
  4422. for (var i in obj) {
  4423. return false;
  4424. }
  4425. return true;
  4426. };
  4427. Tools.RegisterTopRootEvents = function (events) {
  4428. for (var index = 0; index < events.length; index++) {
  4429. var event = events[index];
  4430. window.addEventListener(event.name, event.handler, false);
  4431. try {
  4432. if (window.parent) {
  4433. window.parent.addEventListener(event.name, event.handler, false);
  4434. }
  4435. }
  4436. catch (e) {
  4437. }
  4438. }
  4439. };
  4440. Tools.UnregisterTopRootEvents = function (events) {
  4441. for (var index = 0; index < events.length; index++) {
  4442. var event = events[index];
  4443. window.removeEventListener(event.name, event.handler);
  4444. try {
  4445. if (window.parent) {
  4446. window.parent.removeEventListener(event.name, event.handler);
  4447. }
  4448. }
  4449. catch (e) {
  4450. }
  4451. }
  4452. };
  4453. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4454. // Read the contents of the framebuffer
  4455. var numberOfChannelsByLine = width * 4;
  4456. var halfHeight = height / 2;
  4457. //Reading datas from WebGL
  4458. var data = engine.readPixels(0, 0, width, height);
  4459. //To flip image on Y axis.
  4460. for (var i = 0; i < halfHeight; i++) {
  4461. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4462. var currentCell = j + i * numberOfChannelsByLine;
  4463. var targetLine = height - i - 1;
  4464. var targetCell = j + targetLine * numberOfChannelsByLine;
  4465. var temp = data[currentCell];
  4466. data[currentCell] = data[targetCell];
  4467. data[targetCell] = temp;
  4468. }
  4469. }
  4470. // Create a 2D canvas to store the result
  4471. if (!screenshotCanvas) {
  4472. screenshotCanvas = document.createElement('canvas');
  4473. }
  4474. screenshotCanvas.width = width;
  4475. screenshotCanvas.height = height;
  4476. var context = screenshotCanvas.getContext('2d');
  4477. // Copy the pixels to a 2D canvas
  4478. var imageData = context.createImageData(width, height);
  4479. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4480. var castData = imageData.data;
  4481. castData.set(data);
  4482. context.putImageData(imageData, 0, 0);
  4483. var base64Image = screenshotCanvas.toDataURL();
  4484. if (successCallback) {
  4485. successCallback(base64Image);
  4486. }
  4487. else {
  4488. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4489. if (("download" in document.createElement("a"))) {
  4490. var a = window.document.createElement("a");
  4491. a.href = base64Image;
  4492. var date = new Date();
  4493. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4494. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4495. window.document.body.appendChild(a);
  4496. a.addEventListener("click", function () {
  4497. a.parentElement.removeChild(a);
  4498. });
  4499. a.click();
  4500. }
  4501. else {
  4502. var newWindow = window.open("");
  4503. var img = newWindow.document.createElement("img");
  4504. img.src = base64Image;
  4505. newWindow.document.body.appendChild(img);
  4506. }
  4507. }
  4508. };
  4509. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4510. var width;
  4511. var height;
  4512. //If a precision value is specified
  4513. if (size.precision) {
  4514. width = Math.round(engine.getRenderWidth() * size.precision);
  4515. height = Math.round(width / engine.getAspectRatio(camera));
  4516. size = { width: width, height: height };
  4517. }
  4518. else if (size.width && size.height) {
  4519. width = size.width;
  4520. height = size.height;
  4521. }
  4522. else if (size.width && !size.height) {
  4523. width = size.width;
  4524. height = Math.round(width / engine.getAspectRatio(camera));
  4525. size = { width: width, height: height };
  4526. }
  4527. else if (size.height && !size.width) {
  4528. height = size.height;
  4529. width = Math.round(height * engine.getAspectRatio(camera));
  4530. size = { width: width, height: height };
  4531. }
  4532. else if (!isNaN(size)) {
  4533. height = size;
  4534. width = size;
  4535. }
  4536. else {
  4537. Tools.Error("Invalid 'size' parameter !");
  4538. return;
  4539. }
  4540. var scene = camera.getScene();
  4541. var previousCamera = null;
  4542. if (scene.activeCamera !== camera) {
  4543. previousCamera = scene.activeCamera;
  4544. scene.activeCamera = camera;
  4545. }
  4546. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4547. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4548. texture.renderList = scene.meshes;
  4549. texture.onAfterRender = function () {
  4550. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4551. };
  4552. scene.incrementRenderId();
  4553. texture.render(true);
  4554. texture.dispose();
  4555. if (previousCamera) {
  4556. scene.activeCamera = previousCamera;
  4557. }
  4558. camera.getProjectionMatrix(true); // Force cache refresh;
  4559. };
  4560. // XHR response validator for local file scenario
  4561. Tools.ValidateXHRData = function (xhr, dataType) {
  4562. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4563. if (dataType === void 0) { dataType = 7; }
  4564. try {
  4565. if (dataType & 1) {
  4566. if (xhr.responseText && xhr.responseText.length > 0) {
  4567. return true;
  4568. }
  4569. else if (dataType === 1) {
  4570. return false;
  4571. }
  4572. }
  4573. if (dataType & 2) {
  4574. // Check header width and height since there is no "TGA" magic number
  4575. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4576. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4577. return true;
  4578. }
  4579. else if (dataType === 2) {
  4580. return false;
  4581. }
  4582. }
  4583. if (dataType & 4) {
  4584. // Check for the "DDS" magic number
  4585. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4586. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4587. return true;
  4588. }
  4589. else {
  4590. return false;
  4591. }
  4592. }
  4593. }
  4594. catch (e) {
  4595. }
  4596. return false;
  4597. };
  4598. Object.defineProperty(Tools, "NoneLogLevel", {
  4599. get: function () {
  4600. return Tools._NoneLogLevel;
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Object.defineProperty(Tools, "MessageLogLevel", {
  4606. get: function () {
  4607. return Tools._MessageLogLevel;
  4608. },
  4609. enumerable: true,
  4610. configurable: true
  4611. });
  4612. Object.defineProperty(Tools, "WarningLogLevel", {
  4613. get: function () {
  4614. return Tools._WarningLogLevel;
  4615. },
  4616. enumerable: true,
  4617. configurable: true
  4618. });
  4619. Object.defineProperty(Tools, "ErrorLogLevel", {
  4620. get: function () {
  4621. return Tools._ErrorLogLevel;
  4622. },
  4623. enumerable: true,
  4624. configurable: true
  4625. });
  4626. Object.defineProperty(Tools, "AllLogLevel", {
  4627. get: function () {
  4628. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4629. },
  4630. enumerable: true,
  4631. configurable: true
  4632. });
  4633. Tools._AddLogEntry = function (entry) {
  4634. Tools._LogCache = entry + Tools._LogCache;
  4635. if (Tools.OnNewCacheEntry) {
  4636. Tools.OnNewCacheEntry(entry);
  4637. }
  4638. };
  4639. Tools._FormatMessage = function (message) {
  4640. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4641. var date = new Date();
  4642. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4643. };
  4644. Tools._LogDisabled = function (message) {
  4645. // nothing to do
  4646. };
  4647. Tools._LogEnabled = function (message) {
  4648. var formattedMessage = Tools._FormatMessage(message);
  4649. console.log("BJS - " + formattedMessage);
  4650. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4651. Tools._AddLogEntry(entry);
  4652. };
  4653. Tools._WarnDisabled = function (message) {
  4654. // nothing to do
  4655. };
  4656. Tools._WarnEnabled = function (message) {
  4657. var formattedMessage = Tools._FormatMessage(message);
  4658. console.warn("BJS - " + formattedMessage);
  4659. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4660. Tools._AddLogEntry(entry);
  4661. };
  4662. Tools._ErrorDisabled = function (message) {
  4663. // nothing to do
  4664. };
  4665. Tools._ErrorEnabled = function (message) {
  4666. Tools.errorsCount++;
  4667. var formattedMessage = Tools._FormatMessage(message);
  4668. console.error("BJS - " + formattedMessage);
  4669. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4670. Tools._AddLogEntry(entry);
  4671. };
  4672. Object.defineProperty(Tools, "LogCache", {
  4673. get: function () {
  4674. return Tools._LogCache;
  4675. },
  4676. enumerable: true,
  4677. configurable: true
  4678. });
  4679. Tools.ClearLogCache = function () {
  4680. Tools._LogCache = "";
  4681. Tools.errorsCount = 0;
  4682. };
  4683. Object.defineProperty(Tools, "LogLevels", {
  4684. set: function (level) {
  4685. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4686. Tools.Log = Tools._LogEnabled;
  4687. }
  4688. else {
  4689. Tools.Log = Tools._LogDisabled;
  4690. }
  4691. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4692. Tools.Warn = Tools._WarnEnabled;
  4693. }
  4694. else {
  4695. Tools.Warn = Tools._WarnDisabled;
  4696. }
  4697. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4698. Tools.Error = Tools._ErrorEnabled;
  4699. }
  4700. else {
  4701. Tools.Error = Tools._ErrorDisabled;
  4702. }
  4703. },
  4704. enumerable: true,
  4705. configurable: true
  4706. });
  4707. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4708. get: function () {
  4709. return Tools._PerformanceNoneLogLevel;
  4710. },
  4711. enumerable: true,
  4712. configurable: true
  4713. });
  4714. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4715. get: function () {
  4716. return Tools._PerformanceUserMarkLogLevel;
  4717. },
  4718. enumerable: true,
  4719. configurable: true
  4720. });
  4721. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4722. get: function () {
  4723. return Tools._PerformanceConsoleLogLevel;
  4724. },
  4725. enumerable: true,
  4726. configurable: true
  4727. });
  4728. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4729. set: function (level) {
  4730. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4731. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4732. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4733. return;
  4734. }
  4735. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4736. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4737. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4738. return;
  4739. }
  4740. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4741. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4742. },
  4743. enumerable: true,
  4744. configurable: true
  4745. });
  4746. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4747. };
  4748. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4749. };
  4750. Tools._StartUserMark = function (counterName, condition) {
  4751. if (condition === void 0) { condition = true; }
  4752. if (!condition || !Tools._performance.mark) {
  4753. return;
  4754. }
  4755. Tools._performance.mark(counterName + "-Begin");
  4756. };
  4757. Tools._EndUserMark = function (counterName, condition) {
  4758. if (condition === void 0) { condition = true; }
  4759. if (!condition || !Tools._performance.mark) {
  4760. return;
  4761. }
  4762. Tools._performance.mark(counterName + "-End");
  4763. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4764. };
  4765. Tools._StartPerformanceConsole = function (counterName, condition) {
  4766. if (condition === void 0) { condition = true; }
  4767. if (!condition) {
  4768. return;
  4769. }
  4770. Tools._StartUserMark(counterName, condition);
  4771. if (console.time) {
  4772. console.time(counterName);
  4773. }
  4774. };
  4775. Tools._EndPerformanceConsole = function (counterName, condition) {
  4776. if (condition === void 0) { condition = true; }
  4777. if (!condition) {
  4778. return;
  4779. }
  4780. Tools._EndUserMark(counterName, condition);
  4781. if (console.time) {
  4782. console.timeEnd(counterName);
  4783. }
  4784. };
  4785. Object.defineProperty(Tools, "Now", {
  4786. get: function () {
  4787. if (window.performance && window.performance.now) {
  4788. return window.performance.now();
  4789. }
  4790. return new Date().getTime();
  4791. },
  4792. enumerable: true,
  4793. configurable: true
  4794. });
  4795. Tools.BaseUrl = "";
  4796. Tools.CorsBehavior = "anonymous";
  4797. Tools.UseFallbackTexture = true;
  4798. // Logs
  4799. Tools._NoneLogLevel = 0;
  4800. Tools._MessageLogLevel = 1;
  4801. Tools._WarningLogLevel = 2;
  4802. Tools._ErrorLogLevel = 4;
  4803. Tools._LogCache = "";
  4804. Tools.errorsCount = 0;
  4805. Tools.Log = Tools._LogEnabled;
  4806. Tools.Warn = Tools._WarnEnabled;
  4807. Tools.Error = Tools._ErrorEnabled;
  4808. // Performances
  4809. Tools._PerformanceNoneLogLevel = 0;
  4810. Tools._PerformanceUserMarkLogLevel = 1;
  4811. Tools._PerformanceConsoleLogLevel = 2;
  4812. Tools._performance = window.performance;
  4813. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4814. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4815. return Tools;
  4816. })();
  4817. BABYLON.Tools = Tools;
  4818. /**
  4819. * An implementation of a loop for asynchronous functions.
  4820. */
  4821. var AsyncLoop = (function () {
  4822. /**
  4823. * Constroctor.
  4824. * @param iterations the number of iterations.
  4825. * @param _fn the function to run each iteration
  4826. * @param _successCallback the callback that will be called upon succesful execution
  4827. * @param offset starting offset.
  4828. */
  4829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4830. if (offset === void 0) { offset = 0; }
  4831. this.iterations = iterations;
  4832. this._fn = _fn;
  4833. this._successCallback = _successCallback;
  4834. this.index = offset - 1;
  4835. this._done = false;
  4836. }
  4837. /**
  4838. * Execute the next iteration. Must be called after the last iteration was finished.
  4839. */
  4840. AsyncLoop.prototype.executeNext = function () {
  4841. if (!this._done) {
  4842. if (this.index + 1 < this.iterations) {
  4843. ++this.index;
  4844. this._fn(this);
  4845. }
  4846. else {
  4847. this.breakLoop();
  4848. }
  4849. }
  4850. };
  4851. /**
  4852. * Break the loop and run the success callback.
  4853. */
  4854. AsyncLoop.prototype.breakLoop = function () {
  4855. this._done = true;
  4856. this._successCallback();
  4857. };
  4858. /**
  4859. * Helper function
  4860. */
  4861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4862. if (offset === void 0) { offset = 0; }
  4863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4864. loop.executeNext();
  4865. return loop;
  4866. };
  4867. /**
  4868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4869. * @param iterations total number of iterations
  4870. * @param syncedIterations number of synchronous iterations in each async iteration.
  4871. * @param fn the function to call each iteration.
  4872. * @param callback a success call back that will be called when iterating stops.
  4873. * @param breakFunction a break condition (optional)
  4874. * @param timeout timeout settings for the setTimeout function. default - 0.
  4875. * @constructor
  4876. */
  4877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4878. if (timeout === void 0) { timeout = 0; }
  4879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4880. if (breakFunction && breakFunction())
  4881. loop.breakLoop();
  4882. else {
  4883. setTimeout(function () {
  4884. for (var i = 0; i < syncedIterations; ++i) {
  4885. var iteration = (loop.index * syncedIterations) + i;
  4886. if (iteration >= iterations)
  4887. break;
  4888. fn(iteration);
  4889. if (breakFunction && breakFunction()) {
  4890. loop.breakLoop();
  4891. break;
  4892. }
  4893. }
  4894. loop.executeNext();
  4895. }, timeout);
  4896. }
  4897. }, callback);
  4898. };
  4899. return AsyncLoop;
  4900. })();
  4901. BABYLON.AsyncLoop = AsyncLoop;
  4902. })(BABYLON || (BABYLON = {}));
  4903. var BABYLON;
  4904. (function (BABYLON) {
  4905. var _DepthCullingState = (function () {
  4906. function _DepthCullingState() {
  4907. this._isDepthTestDirty = false;
  4908. this._isDepthMaskDirty = false;
  4909. this._isDepthFuncDirty = false;
  4910. this._isCullFaceDirty = false;
  4911. this._isCullDirty = false;
  4912. this._isZOffsetDirty = false;
  4913. }
  4914. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4915. get: function () {
  4916. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4917. },
  4918. enumerable: true,
  4919. configurable: true
  4920. });
  4921. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4922. get: function () {
  4923. return this._zOffset;
  4924. },
  4925. set: function (value) {
  4926. if (this._zOffset === value) {
  4927. return;
  4928. }
  4929. this._zOffset = value;
  4930. this._isZOffsetDirty = true;
  4931. },
  4932. enumerable: true,
  4933. configurable: true
  4934. });
  4935. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4936. get: function () {
  4937. return this._cullFace;
  4938. },
  4939. set: function (value) {
  4940. if (this._cullFace === value) {
  4941. return;
  4942. }
  4943. this._cullFace = value;
  4944. this._isCullFaceDirty = true;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4950. get: function () {
  4951. return this._cull;
  4952. },
  4953. set: function (value) {
  4954. if (this._cull === value) {
  4955. return;
  4956. }
  4957. this._cull = value;
  4958. this._isCullDirty = true;
  4959. },
  4960. enumerable: true,
  4961. configurable: true
  4962. });
  4963. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4964. get: function () {
  4965. return this._depthFunc;
  4966. },
  4967. set: function (value) {
  4968. if (this._depthFunc === value) {
  4969. return;
  4970. }
  4971. this._depthFunc = value;
  4972. this._isDepthFuncDirty = true;
  4973. },
  4974. enumerable: true,
  4975. configurable: true
  4976. });
  4977. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4978. get: function () {
  4979. return this._depthMask;
  4980. },
  4981. set: function (value) {
  4982. if (this._depthMask === value) {
  4983. return;
  4984. }
  4985. this._depthMask = value;
  4986. this._isDepthMaskDirty = true;
  4987. },
  4988. enumerable: true,
  4989. configurable: true
  4990. });
  4991. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4992. get: function () {
  4993. return this._depthTest;
  4994. },
  4995. set: function (value) {
  4996. if (this._depthTest === value) {
  4997. return;
  4998. }
  4999. this._depthTest = value;
  5000. this._isDepthTestDirty = true;
  5001. },
  5002. enumerable: true,
  5003. configurable: true
  5004. });
  5005. _DepthCullingState.prototype.reset = function () {
  5006. this._depthMask = true;
  5007. this._depthTest = true;
  5008. this._depthFunc = null;
  5009. this._cull = null;
  5010. this._cullFace = null;
  5011. this._zOffset = 0;
  5012. this._isDepthTestDirty = true;
  5013. this._isDepthMaskDirty = true;
  5014. this._isDepthFuncDirty = false;
  5015. this._isCullFaceDirty = false;
  5016. this._isCullDirty = false;
  5017. this._isZOffsetDirty = false;
  5018. };
  5019. _DepthCullingState.prototype.apply = function (gl) {
  5020. if (!this.isDirty) {
  5021. return;
  5022. }
  5023. // Cull
  5024. if (this._isCullDirty) {
  5025. if (this.cull) {
  5026. gl.enable(gl.CULL_FACE);
  5027. }
  5028. else {
  5029. gl.disable(gl.CULL_FACE);
  5030. }
  5031. this._isCullDirty = false;
  5032. }
  5033. // Cull face
  5034. if (this._isCullFaceDirty) {
  5035. gl.cullFace(this.cullFace);
  5036. this._isCullFaceDirty = false;
  5037. }
  5038. // Depth mask
  5039. if (this._isDepthMaskDirty) {
  5040. gl.depthMask(this.depthMask);
  5041. this._isDepthMaskDirty = false;
  5042. }
  5043. // Depth test
  5044. if (this._isDepthTestDirty) {
  5045. if (this.depthTest) {
  5046. gl.enable(gl.DEPTH_TEST);
  5047. }
  5048. else {
  5049. gl.disable(gl.DEPTH_TEST);
  5050. }
  5051. this._isDepthTestDirty = false;
  5052. }
  5053. // Depth func
  5054. if (this._isDepthFuncDirty) {
  5055. gl.depthFunc(this.depthFunc);
  5056. this._isDepthFuncDirty = false;
  5057. }
  5058. // zOffset
  5059. if (this._isZOffsetDirty) {
  5060. if (this.zOffset) {
  5061. gl.enable(gl.POLYGON_OFFSET_FILL);
  5062. gl.polygonOffset(this.zOffset, 0);
  5063. }
  5064. else {
  5065. gl.disable(gl.POLYGON_OFFSET_FILL);
  5066. }
  5067. this._isZOffsetDirty = false;
  5068. }
  5069. };
  5070. return _DepthCullingState;
  5071. })();
  5072. BABYLON._DepthCullingState = _DepthCullingState;
  5073. var _AlphaState = (function () {
  5074. function _AlphaState() {
  5075. this._isAlphaBlendDirty = false;
  5076. this._isBlendFunctionParametersDirty = false;
  5077. this._alphaBlend = false;
  5078. this._blendFunctionParameters = new Array(4);
  5079. }
  5080. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5081. get: function () {
  5082. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5083. },
  5084. enumerable: true,
  5085. configurable: true
  5086. });
  5087. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5088. get: function () {
  5089. return this._alphaBlend;
  5090. },
  5091. set: function (value) {
  5092. if (this._alphaBlend === value) {
  5093. return;
  5094. }
  5095. this._alphaBlend = value;
  5096. this._isAlphaBlendDirty = true;
  5097. },
  5098. enumerable: true,
  5099. configurable: true
  5100. });
  5101. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5102. if (this._blendFunctionParameters[0] === value0 &&
  5103. this._blendFunctionParameters[1] === value1 &&
  5104. this._blendFunctionParameters[2] === value2 &&
  5105. this._blendFunctionParameters[3] === value3) {
  5106. return;
  5107. }
  5108. this._blendFunctionParameters[0] = value0;
  5109. this._blendFunctionParameters[1] = value1;
  5110. this._blendFunctionParameters[2] = value2;
  5111. this._blendFunctionParameters[3] = value3;
  5112. this._isBlendFunctionParametersDirty = true;
  5113. };
  5114. _AlphaState.prototype.reset = function () {
  5115. this._alphaBlend = false;
  5116. this._blendFunctionParameters[0] = null;
  5117. this._blendFunctionParameters[1] = null;
  5118. this._blendFunctionParameters[2] = null;
  5119. this._blendFunctionParameters[3] = null;
  5120. this._isAlphaBlendDirty = true;
  5121. this._isBlendFunctionParametersDirty = false;
  5122. };
  5123. _AlphaState.prototype.apply = function (gl) {
  5124. if (!this.isDirty) {
  5125. return;
  5126. }
  5127. // Alpha blend
  5128. if (this._isAlphaBlendDirty) {
  5129. if (this._alphaBlend) {
  5130. gl.enable(gl.BLEND);
  5131. }
  5132. else {
  5133. gl.disable(gl.BLEND);
  5134. }
  5135. this._isAlphaBlendDirty = false;
  5136. }
  5137. // Alpha function
  5138. if (this._isBlendFunctionParametersDirty) {
  5139. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5140. this._isBlendFunctionParametersDirty = false;
  5141. }
  5142. };
  5143. return _AlphaState;
  5144. })();
  5145. BABYLON._AlphaState = _AlphaState;
  5146. var compileShader = function (gl, source, type, defines) {
  5147. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5148. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5149. gl.compileShader(shader);
  5150. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5151. throw new Error(gl.getShaderInfoLog(shader));
  5152. }
  5153. return shader;
  5154. };
  5155. var getWebGLTextureType = function (gl, type) {
  5156. var textureType = gl.UNSIGNED_BYTE;
  5157. if (type === Engine.TEXTURETYPE_FLOAT)
  5158. textureType = gl.FLOAT;
  5159. return textureType;
  5160. };
  5161. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5162. var magFilter = gl.NEAREST;
  5163. var minFilter = gl.NEAREST;
  5164. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5165. magFilter = gl.LINEAR;
  5166. if (generateMipMaps) {
  5167. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5168. }
  5169. else {
  5170. minFilter = gl.LINEAR;
  5171. }
  5172. }
  5173. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5174. magFilter = gl.LINEAR;
  5175. if (generateMipMaps) {
  5176. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5177. }
  5178. else {
  5179. minFilter = gl.LINEAR;
  5180. }
  5181. }
  5182. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5183. magFilter = gl.NEAREST;
  5184. if (generateMipMaps) {
  5185. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5186. }
  5187. else {
  5188. minFilter = gl.NEAREST;
  5189. }
  5190. }
  5191. return {
  5192. min: minFilter,
  5193. mag: magFilter
  5194. };
  5195. };
  5196. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5198. var engine = scene.getEngine();
  5199. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5200. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5201. gl.bindTexture(gl.TEXTURE_2D, texture);
  5202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5203. texture._baseWidth = width;
  5204. texture._baseHeight = height;
  5205. texture._width = potWidth;
  5206. texture._height = potHeight;
  5207. texture.isReady = true;
  5208. processFunction(potWidth, potHeight);
  5209. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5212. if (!noMipmap && !isCompressed) {
  5213. gl.generateMipmap(gl.TEXTURE_2D);
  5214. }
  5215. gl.bindTexture(gl.TEXTURE_2D, null);
  5216. engine.resetTextureCache();
  5217. scene._removePendingData(texture);
  5218. if (onLoad) {
  5219. onLoad();
  5220. }
  5221. };
  5222. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5223. var img;
  5224. var onload = function () {
  5225. loadedImages[index] = img;
  5226. loadedImages._internalCount++;
  5227. scene._removePendingData(img);
  5228. if (loadedImages._internalCount === 6) {
  5229. onfinish(loadedImages);
  5230. }
  5231. };
  5232. var onerror = function () {
  5233. scene._removePendingData(img);
  5234. };
  5235. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5236. scene._addPendingData(img);
  5237. };
  5238. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5239. var loadedImages = [];
  5240. loadedImages._internalCount = 0;
  5241. for (var index = 0; index < 6; index++) {
  5242. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5243. }
  5244. };
  5245. var EngineCapabilities = (function () {
  5246. function EngineCapabilities() {
  5247. }
  5248. return EngineCapabilities;
  5249. })();
  5250. BABYLON.EngineCapabilities = EngineCapabilities;
  5251. /**
  5252. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5253. */
  5254. var Engine = (function () {
  5255. /**
  5256. * @constructor
  5257. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5258. * @param {boolean} [antialias] - enable antialias
  5259. * @param options - further options to be sent to the getContext function
  5260. */
  5261. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5262. var _this = this;
  5263. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5264. // Public members
  5265. this.isFullscreen = false;
  5266. this.isPointerLock = false;
  5267. this.cullBackFaces = true;
  5268. this.renderEvenInBackground = true;
  5269. // To enable/disable IDB support and avoid XHR on .manifest
  5270. this.enableOfflineSupport = true;
  5271. this.scenes = new Array();
  5272. this._windowIsBackground = false;
  5273. this._webGLVersion = "1.0";
  5274. this._drawCalls = 0;
  5275. this._renderingQueueLaunched = false;
  5276. this._activeRenderLoops = [];
  5277. // FPS
  5278. this.fpsRange = 60;
  5279. this.previousFramesDuration = [];
  5280. this.fps = 60;
  5281. this.deltaTime = 0;
  5282. // States
  5283. this._depthCullingState = new _DepthCullingState();
  5284. this._alphaState = new _AlphaState();
  5285. this._alphaMode = Engine.ALPHA_DISABLE;
  5286. // Cache
  5287. this._loadedTexturesCache = new Array();
  5288. this._maxTextureChannels = 16;
  5289. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5290. this._compiledEffects = {};
  5291. this._uintIndicesCurrentlySet = false;
  5292. this._renderingCanvas = canvas;
  5293. options = options || {};
  5294. options.antialias = antialias;
  5295. if (options.preserveDrawingBuffer === undefined) {
  5296. options.preserveDrawingBuffer = false;
  5297. }
  5298. // GL
  5299. //try {
  5300. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5301. // if (this._gl) {
  5302. // this._webGLVersion = "2.0";
  5303. // }
  5304. //} catch (e) {
  5305. // // Do nothing
  5306. //}
  5307. if (!this._gl) {
  5308. try {
  5309. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5310. }
  5311. catch (e) {
  5312. throw new Error("WebGL not supported");
  5313. }
  5314. }
  5315. if (!this._gl) {
  5316. throw new Error("WebGL not supported");
  5317. }
  5318. this._onBlur = function () {
  5319. _this._windowIsBackground = true;
  5320. };
  5321. this._onFocus = function () {
  5322. _this._windowIsBackground = false;
  5323. };
  5324. window.addEventListener("blur", this._onBlur);
  5325. window.addEventListener("focus", this._onFocus);
  5326. // Viewport
  5327. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5328. this.resize();
  5329. // Caps
  5330. this._caps = new EngineCapabilities();
  5331. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5332. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5333. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5334. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5335. // Infos
  5336. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5337. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5338. if (rendererInfo != null) {
  5339. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5340. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5341. }
  5342. if (!this._glVendor) {
  5343. this._glVendor = "Unknown vendor";
  5344. }
  5345. if (!this._glRenderer) {
  5346. this._glRenderer = "Unknown renderer";
  5347. }
  5348. // Extensions
  5349. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5350. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5351. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5352. 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');
  5353. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5354. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5355. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5356. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5357. this._caps.highPrecisionShaderSupported = true;
  5358. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5359. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5360. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5361. if (this._gl.getShaderPrecisionFormat) {
  5362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5364. }
  5365. // Depth buffer
  5366. this.setDepthBuffer(true);
  5367. this.setDepthFunctionToLessOrEqual();
  5368. this.setDepthWrite(true);
  5369. // Fullscreen
  5370. this._onFullscreenChange = function () {
  5371. if (document.fullscreen !== undefined) {
  5372. _this.isFullscreen = document.fullscreen;
  5373. }
  5374. else if (document.mozFullScreen !== undefined) {
  5375. _this.isFullscreen = document.mozFullScreen;
  5376. }
  5377. else if (document.webkitIsFullScreen !== undefined) {
  5378. _this.isFullscreen = document.webkitIsFullScreen;
  5379. }
  5380. else if (document.msIsFullScreen !== undefined) {
  5381. _this.isFullscreen = document.msIsFullScreen;
  5382. }
  5383. // Pointer lock
  5384. if (_this.isFullscreen && _this._pointerLockRequested) {
  5385. canvas.requestPointerLock = canvas.requestPointerLock ||
  5386. canvas.msRequestPointerLock ||
  5387. canvas.mozRequestPointerLock ||
  5388. canvas.webkitRequestPointerLock;
  5389. if (canvas.requestPointerLock) {
  5390. canvas.requestPointerLock();
  5391. }
  5392. }
  5393. };
  5394. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5395. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5396. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5397. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5398. // Pointer lock
  5399. this._onPointerLockChange = function () {
  5400. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5401. document.webkitPointerLockElement === canvas ||
  5402. document.msPointerLockElement === canvas ||
  5403. document.pointerLockElement === canvas);
  5404. };
  5405. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5406. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5407. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5408. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5409. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5410. Engine.audioEngine = new BABYLON.AudioEngine();
  5411. }
  5412. //default loading screen
  5413. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5414. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5415. }
  5416. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5417. get: function () {
  5418. return Engine._ALPHA_DISABLE;
  5419. },
  5420. enumerable: true,
  5421. configurable: true
  5422. });
  5423. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5424. get: function () {
  5425. return Engine._ALPHA_ONEONE;
  5426. },
  5427. enumerable: true,
  5428. configurable: true
  5429. });
  5430. Object.defineProperty(Engine, "ALPHA_ADD", {
  5431. get: function () {
  5432. return Engine._ALPHA_ADD;
  5433. },
  5434. enumerable: true,
  5435. configurable: true
  5436. });
  5437. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5438. get: function () {
  5439. return Engine._ALPHA_COMBINE;
  5440. },
  5441. enumerable: true,
  5442. configurable: true
  5443. });
  5444. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5445. get: function () {
  5446. return Engine._ALPHA_SUBTRACT;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5452. get: function () {
  5453. return Engine._ALPHA_MULTIPLY;
  5454. },
  5455. enumerable: true,
  5456. configurable: true
  5457. });
  5458. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5459. get: function () {
  5460. return Engine._ALPHA_MAXIMIZED;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5466. get: function () {
  5467. return Engine._DELAYLOADSTATE_NONE;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5473. get: function () {
  5474. return Engine._DELAYLOADSTATE_LOADED;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5480. get: function () {
  5481. return Engine._DELAYLOADSTATE_LOADING;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5487. get: function () {
  5488. return Engine._DELAYLOADSTATE_NOTLOADED;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5494. get: function () {
  5495. return Engine._TEXTUREFORMAT_ALPHA;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5501. get: function () {
  5502. return Engine._TEXTUREFORMAT_LUMINANCE;
  5503. },
  5504. enumerable: true,
  5505. configurable: true
  5506. });
  5507. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5508. get: function () {
  5509. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5515. get: function () {
  5516. return Engine._TEXTUREFORMAT_RGB;
  5517. },
  5518. enumerable: true,
  5519. configurable: true
  5520. });
  5521. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5522. get: function () {
  5523. return Engine._TEXTUREFORMAT_RGBA;
  5524. },
  5525. enumerable: true,
  5526. configurable: true
  5527. });
  5528. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5529. get: function () {
  5530. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5531. },
  5532. enumerable: true,
  5533. configurable: true
  5534. });
  5535. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5536. get: function () {
  5537. return Engine._TEXTURETYPE_FLOAT;
  5538. },
  5539. enumerable: true,
  5540. configurable: true
  5541. });
  5542. Object.defineProperty(Engine, "Version", {
  5543. get: function () {
  5544. return "2.4.0-alpha";
  5545. },
  5546. enumerable: true,
  5547. configurable: true
  5548. });
  5549. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5550. get: function () {
  5551. return this._webGLVersion;
  5552. },
  5553. enumerable: true,
  5554. configurable: true
  5555. });
  5556. Engine.prototype._prepareWorkingCanvas = function () {
  5557. if (this._workingCanvas) {
  5558. return;
  5559. }
  5560. this._workingCanvas = document.createElement("canvas");
  5561. this._workingContext = this._workingCanvas.getContext("2d");
  5562. };
  5563. Engine.prototype.resetTextureCache = function () {
  5564. for (var index = 0; index < this._maxTextureChannels; index++) {
  5565. this._activeTexturesCache[index] = null;
  5566. }
  5567. };
  5568. Engine.prototype.getGlInfo = function () {
  5569. return {
  5570. vendor: this._glVendor,
  5571. renderer: this._glRenderer,
  5572. version: this._glVersion
  5573. };
  5574. };
  5575. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5576. if (useScreen === void 0) { useScreen = false; }
  5577. var viewport = camera.viewport;
  5578. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5579. };
  5580. Engine.prototype.getRenderWidth = function (useScreen) {
  5581. if (useScreen === void 0) { useScreen = false; }
  5582. if (!useScreen && this._currentRenderTarget) {
  5583. return this._currentRenderTarget._width;
  5584. }
  5585. return this._renderingCanvas.width;
  5586. };
  5587. Engine.prototype.getRenderHeight = function (useScreen) {
  5588. if (useScreen === void 0) { useScreen = false; }
  5589. if (!useScreen && this._currentRenderTarget) {
  5590. return this._currentRenderTarget._height;
  5591. }
  5592. return this._renderingCanvas.height;
  5593. };
  5594. Engine.prototype.getRenderingCanvas = function () {
  5595. return this._renderingCanvas;
  5596. };
  5597. Engine.prototype.getRenderingCanvasClientRect = function () {
  5598. return this._renderingCanvas.getBoundingClientRect();
  5599. };
  5600. Engine.prototype.setHardwareScalingLevel = function (level) {
  5601. this._hardwareScalingLevel = level;
  5602. this.resize();
  5603. };
  5604. Engine.prototype.getHardwareScalingLevel = function () {
  5605. return this._hardwareScalingLevel;
  5606. };
  5607. Engine.prototype.getLoadedTexturesCache = function () {
  5608. return this._loadedTexturesCache;
  5609. };
  5610. Engine.prototype.getCaps = function () {
  5611. return this._caps;
  5612. };
  5613. Object.defineProperty(Engine.prototype, "drawCalls", {
  5614. get: function () {
  5615. return this._drawCalls;
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. // Methods
  5621. Engine.prototype.resetDrawCalls = function () {
  5622. this._drawCalls = 0;
  5623. };
  5624. Engine.prototype.setDepthFunctionToGreater = function () {
  5625. this._depthCullingState.depthFunc = this._gl.GREATER;
  5626. };
  5627. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5628. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5629. };
  5630. Engine.prototype.setDepthFunctionToLess = function () {
  5631. this._depthCullingState.depthFunc = this._gl.LESS;
  5632. };
  5633. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5634. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5635. };
  5636. /**
  5637. * stop executing a render loop function and remove it from the execution array
  5638. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5639. */
  5640. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5641. if (!renderFunction) {
  5642. this._activeRenderLoops = [];
  5643. return;
  5644. }
  5645. var index = this._activeRenderLoops.indexOf(renderFunction);
  5646. if (index >= 0) {
  5647. this._activeRenderLoops.splice(index, 1);
  5648. }
  5649. };
  5650. Engine.prototype._renderLoop = function () {
  5651. var shouldRender = true;
  5652. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5653. shouldRender = false;
  5654. }
  5655. if (shouldRender) {
  5656. // Start new frame
  5657. this.beginFrame();
  5658. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5659. var renderFunction = this._activeRenderLoops[index];
  5660. renderFunction();
  5661. }
  5662. // Present
  5663. this.endFrame();
  5664. }
  5665. if (this._activeRenderLoops.length > 0) {
  5666. // Register new frame
  5667. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5668. }
  5669. else {
  5670. this._renderingQueueLaunched = false;
  5671. }
  5672. };
  5673. /**
  5674. * Register and execute a render loop. The engine can have more than one render function.
  5675. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5676. * @example
  5677. * engine.runRenderLoop(function () {
  5678. * scene.render()
  5679. * })
  5680. */
  5681. Engine.prototype.runRenderLoop = function (renderFunction) {
  5682. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5683. return;
  5684. }
  5685. this._activeRenderLoops.push(renderFunction);
  5686. if (!this._renderingQueueLaunched) {
  5687. this._renderingQueueLaunched = true;
  5688. this._bindedRenderFunction = this._renderLoop.bind(this);
  5689. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5690. }
  5691. };
  5692. /**
  5693. * Toggle full screen mode.
  5694. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5695. */
  5696. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5697. if (this.isFullscreen) {
  5698. BABYLON.Tools.ExitFullscreen();
  5699. }
  5700. else {
  5701. this._pointerLockRequested = requestPointerLock;
  5702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5703. }
  5704. };
  5705. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5706. this.applyStates();
  5707. if (backBuffer) {
  5708. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5709. }
  5710. if (depthStencil && this._depthCullingState.depthMask) {
  5711. this._gl.clearDepth(1.0);
  5712. }
  5713. var mode = 0;
  5714. if (backBuffer) {
  5715. mode |= this._gl.COLOR_BUFFER_BIT;
  5716. }
  5717. if (depthStencil && this._depthCullingState.depthMask) {
  5718. mode |= this._gl.DEPTH_BUFFER_BIT;
  5719. }
  5720. this._gl.clear(mode);
  5721. };
  5722. /**
  5723. * Set the WebGL's viewport
  5724. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5725. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5726. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5727. */
  5728. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5729. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5730. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5731. var x = viewport.x || 0;
  5732. var y = viewport.y || 0;
  5733. this._cachedViewport = viewport;
  5734. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5735. };
  5736. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5737. this._cachedViewport = null;
  5738. this._gl.viewport(x, y, width, height);
  5739. };
  5740. Engine.prototype.beginFrame = function () {
  5741. this._measureFps();
  5742. };
  5743. Engine.prototype.endFrame = function () {
  5744. //this.flushFramebuffer();
  5745. };
  5746. /**
  5747. * resize the view according to the canvas' size.
  5748. * @example
  5749. * window.addEventListener("resize", function () {
  5750. * engine.resize();
  5751. * });
  5752. */
  5753. Engine.prototype.resize = function () {
  5754. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5755. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5756. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5757. for (var index = 0; index < this.scenes.length; index++) {
  5758. var scene = this.scenes[index];
  5759. if (scene.debugLayer.isVisible()) {
  5760. scene.debugLayer._syncPositions();
  5761. }
  5762. }
  5763. };
  5764. /**
  5765. * force a specific size of the canvas
  5766. * @param {number} width - the new canvas' width
  5767. * @param {number} height - the new canvas' height
  5768. */
  5769. Engine.prototype.setSize = function (width, height) {
  5770. this._renderingCanvas.width = width;
  5771. this._renderingCanvas.height = height;
  5772. for (var index = 0; index < this.scenes.length; index++) {
  5773. var scene = this.scenes[index];
  5774. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5775. var cam = scene.cameras[camIndex];
  5776. cam._currentRenderId = 0;
  5777. }
  5778. }
  5779. };
  5780. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5781. this._currentRenderTarget = texture;
  5782. var gl = this._gl;
  5783. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5784. if (texture.isCube) {
  5785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5786. }
  5787. else {
  5788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5789. }
  5790. this._gl.viewport(0, 0, texture._width, texture._height);
  5791. this.wipeCaches();
  5792. };
  5793. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5794. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5795. this._currentRenderTarget = null;
  5796. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5797. var gl = this._gl;
  5798. gl.bindTexture(gl.TEXTURE_2D, texture);
  5799. gl.generateMipmap(gl.TEXTURE_2D);
  5800. gl.bindTexture(gl.TEXTURE_2D, null);
  5801. }
  5802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5803. };
  5804. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5805. if (texture.generateMipMaps) {
  5806. var gl = this._gl;
  5807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5808. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5809. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5810. }
  5811. };
  5812. Engine.prototype.flushFramebuffer = function () {
  5813. this._gl.flush();
  5814. };
  5815. Engine.prototype.restoreDefaultFramebuffer = function () {
  5816. this._currentRenderTarget = null;
  5817. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5818. this.setViewport(this._cachedViewport);
  5819. this.wipeCaches();
  5820. };
  5821. // VBOs
  5822. Engine.prototype._resetVertexBufferBinding = function () {
  5823. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5824. this._cachedVertexBuffers = null;
  5825. };
  5826. Engine.prototype.createVertexBuffer = function (vertices) {
  5827. var vbo = this._gl.createBuffer();
  5828. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5829. if (vertices instanceof Float32Array) {
  5830. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5831. }
  5832. else {
  5833. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5834. }
  5835. this._resetVertexBufferBinding();
  5836. vbo.references = 1;
  5837. return vbo;
  5838. };
  5839. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5840. var vbo = this._gl.createBuffer();
  5841. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5842. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5843. this._resetVertexBufferBinding();
  5844. vbo.references = 1;
  5845. return vbo;
  5846. };
  5847. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5848. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5849. if (offset === undefined) {
  5850. offset = 0;
  5851. }
  5852. if (vertices instanceof Float32Array) {
  5853. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5854. }
  5855. else {
  5856. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5857. }
  5858. this._resetVertexBufferBinding();
  5859. };
  5860. Engine.prototype._resetIndexBufferBinding = function () {
  5861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5862. this._cachedIndexBuffer = null;
  5863. };
  5864. Engine.prototype.createIndexBuffer = function (indices) {
  5865. var vbo = this._gl.createBuffer();
  5866. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5867. // Check for 32 bits indices
  5868. var arrayBuffer;
  5869. var need32Bits = false;
  5870. if (this._caps.uintIndices) {
  5871. for (var index = 0; index < indices.length; index++) {
  5872. if (indices[index] > 65535) {
  5873. need32Bits = true;
  5874. break;
  5875. }
  5876. }
  5877. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5878. }
  5879. else {
  5880. arrayBuffer = new Uint16Array(indices);
  5881. }
  5882. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5883. this._resetIndexBufferBinding();
  5884. vbo.references = 1;
  5885. vbo.is32Bits = need32Bits;
  5886. return vbo;
  5887. };
  5888. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5889. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5890. this._cachedVertexBuffers = vertexBuffer;
  5891. this._cachedEffectForVertexBuffers = effect;
  5892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5893. var offset = 0;
  5894. for (var index = 0; index < vertexDeclaration.length; index++) {
  5895. var order = effect.getAttributeLocation(index);
  5896. if (order >= 0) {
  5897. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5898. }
  5899. offset += vertexDeclaration[index] * 4;
  5900. }
  5901. }
  5902. if (this._cachedIndexBuffer !== indexBuffer) {
  5903. this._cachedIndexBuffer = indexBuffer;
  5904. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5905. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5906. }
  5907. };
  5908. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5909. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5910. this._cachedVertexBuffers = vertexBuffers;
  5911. this._cachedEffectForVertexBuffers = effect;
  5912. var attributes = effect.getAttributesNames();
  5913. for (var index = 0; index < attributes.length; index++) {
  5914. var order = effect.getAttributeLocation(index);
  5915. if (order >= 0) {
  5916. var vertexBuffer = vertexBuffers[attributes[index]];
  5917. if (!vertexBuffer) {
  5918. continue;
  5919. }
  5920. var stride = vertexBuffer.getStrideSize();
  5921. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5922. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5923. }
  5924. }
  5925. }
  5926. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5927. this._cachedIndexBuffer = indexBuffer;
  5928. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5929. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5930. }
  5931. };
  5932. Engine.prototype._releaseBuffer = function (buffer) {
  5933. buffer.references--;
  5934. if (buffer.references === 0) {
  5935. this._gl.deleteBuffer(buffer);
  5936. return true;
  5937. }
  5938. return false;
  5939. };
  5940. Engine.prototype.createInstancesBuffer = function (capacity) {
  5941. var buffer = this._gl.createBuffer();
  5942. buffer.capacity = capacity;
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5944. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5945. return buffer;
  5946. };
  5947. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5948. this._gl.deleteBuffer(buffer);
  5949. };
  5950. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5951. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5952. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5953. for (var index = 0; index < 4; index++) {
  5954. var offsetLocation = offsetLocations[index];
  5955. this._gl.enableVertexAttribArray(offsetLocation);
  5956. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5957. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5958. }
  5959. };
  5960. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5962. for (var index = 0; index < 4; index++) {
  5963. var offsetLocation = offsetLocations[index];
  5964. this._gl.disableVertexAttribArray(offsetLocation);
  5965. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5966. }
  5967. };
  5968. Engine.prototype.applyStates = function () {
  5969. this._depthCullingState.apply(this._gl);
  5970. this._alphaState.apply(this._gl);
  5971. };
  5972. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5973. // Apply states
  5974. this.applyStates();
  5975. this._drawCalls++;
  5976. // Render
  5977. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5978. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5979. if (instancesCount) {
  5980. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5981. return;
  5982. }
  5983. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5984. };
  5985. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5986. // Apply states
  5987. this.applyStates();
  5988. this._drawCalls++;
  5989. if (instancesCount) {
  5990. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5991. return;
  5992. }
  5993. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5994. };
  5995. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5996. // Apply states
  5997. this.applyStates();
  5998. this._drawCalls++;
  5999. if (instancesCount) {
  6000. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6001. return;
  6002. }
  6003. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6004. };
  6005. // Shaders
  6006. Engine.prototype._releaseEffect = function (effect) {
  6007. if (this._compiledEffects[effect._key]) {
  6008. delete this._compiledEffects[effect._key];
  6009. if (effect.getProgram()) {
  6010. this._gl.deleteProgram(effect.getProgram());
  6011. }
  6012. }
  6013. };
  6014. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6015. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6016. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6017. var name = vertex + "+" + fragment + "@" + defines;
  6018. if (this._compiledEffects[name]) {
  6019. return this._compiledEffects[name];
  6020. }
  6021. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6022. effect._key = name;
  6023. this._compiledEffects[name] = effect;
  6024. return effect;
  6025. };
  6026. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6027. if (uniformsNames === void 0) { uniformsNames = []; }
  6028. if (samplers === void 0) { samplers = []; }
  6029. if (defines === void 0) { defines = ""; }
  6030. return this.createEffect({
  6031. vertex: "particles",
  6032. fragmentElement: fragmentName
  6033. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6034. };
  6035. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6036. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6037. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6038. var shaderProgram = this._gl.createProgram();
  6039. this._gl.attachShader(shaderProgram, vertexShader);
  6040. this._gl.attachShader(shaderProgram, fragmentShader);
  6041. this._gl.linkProgram(shaderProgram);
  6042. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6043. if (!linked) {
  6044. var error = this._gl.getProgramInfoLog(shaderProgram);
  6045. if (error) {
  6046. throw new Error(error);
  6047. }
  6048. }
  6049. this._gl.deleteShader(vertexShader);
  6050. this._gl.deleteShader(fragmentShader);
  6051. return shaderProgram;
  6052. };
  6053. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6054. var results = [];
  6055. for (var index = 0; index < uniformsNames.length; index++) {
  6056. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6057. }
  6058. return results;
  6059. };
  6060. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6061. var results = [];
  6062. for (var index = 0; index < attributesNames.length; index++) {
  6063. try {
  6064. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6065. }
  6066. catch (e) {
  6067. results.push(-1);
  6068. }
  6069. }
  6070. return results;
  6071. };
  6072. Engine.prototype.enableEffect = function (effect) {
  6073. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6074. if (effect && effect.onBind) {
  6075. effect.onBind(effect);
  6076. }
  6077. return;
  6078. }
  6079. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6080. // Use program
  6081. this._gl.useProgram(effect.getProgram());
  6082. for (var i in this._vertexAttribArrays) {
  6083. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6084. continue;
  6085. }
  6086. this._vertexAttribArrays[i] = false;
  6087. this._gl.disableVertexAttribArray(i);
  6088. }
  6089. var attributesCount = effect.getAttributesCount();
  6090. for (var index = 0; index < attributesCount; index++) {
  6091. // Attributes
  6092. var order = effect.getAttributeLocation(index);
  6093. if (order >= 0) {
  6094. this._vertexAttribArrays[order] = true;
  6095. this._gl.enableVertexAttribArray(order);
  6096. }
  6097. }
  6098. this._currentEffect = effect;
  6099. if (effect.onBind) {
  6100. effect.onBind(effect);
  6101. }
  6102. };
  6103. Engine.prototype.setArray = function (uniform, array) {
  6104. if (!uniform)
  6105. return;
  6106. this._gl.uniform1fv(uniform, array);
  6107. };
  6108. Engine.prototype.setArray2 = function (uniform, array) {
  6109. if (!uniform || array.length % 2 !== 0)
  6110. return;
  6111. this._gl.uniform2fv(uniform, array);
  6112. };
  6113. Engine.prototype.setArray3 = function (uniform, array) {
  6114. if (!uniform || array.length % 3 !== 0)
  6115. return;
  6116. this._gl.uniform3fv(uniform, array);
  6117. };
  6118. Engine.prototype.setArray4 = function (uniform, array) {
  6119. if (!uniform || array.length % 4 !== 0)
  6120. return;
  6121. this._gl.uniform4fv(uniform, array);
  6122. };
  6123. Engine.prototype.setMatrices = function (uniform, matrices) {
  6124. if (!uniform)
  6125. return;
  6126. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6127. };
  6128. Engine.prototype.setMatrix = function (uniform, matrix) {
  6129. if (!uniform)
  6130. return;
  6131. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6132. };
  6133. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6134. if (!uniform)
  6135. return;
  6136. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6137. };
  6138. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6139. if (!uniform)
  6140. return;
  6141. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6142. };
  6143. Engine.prototype.setFloat = function (uniform, value) {
  6144. if (!uniform)
  6145. return;
  6146. this._gl.uniform1f(uniform, value);
  6147. };
  6148. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6149. if (!uniform)
  6150. return;
  6151. this._gl.uniform2f(uniform, x, y);
  6152. };
  6153. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6154. if (!uniform)
  6155. return;
  6156. this._gl.uniform3f(uniform, x, y, z);
  6157. };
  6158. Engine.prototype.setBool = function (uniform, bool) {
  6159. if (!uniform)
  6160. return;
  6161. this._gl.uniform1i(uniform, bool);
  6162. };
  6163. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6164. if (!uniform)
  6165. return;
  6166. this._gl.uniform4f(uniform, x, y, z, w);
  6167. };
  6168. Engine.prototype.setColor3 = function (uniform, color3) {
  6169. if (!uniform)
  6170. return;
  6171. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6172. };
  6173. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6174. if (!uniform)
  6175. return;
  6176. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6177. };
  6178. // States
  6179. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6180. if (zOffset === void 0) { zOffset = 0; }
  6181. if (reverseSide === void 0) { reverseSide = false; }
  6182. // Culling
  6183. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6184. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6185. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6186. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6187. if (culling) {
  6188. this._depthCullingState.cullFace = cullFace;
  6189. this._depthCullingState.cull = true;
  6190. }
  6191. else {
  6192. this._depthCullingState.cull = false;
  6193. }
  6194. }
  6195. // Z offset
  6196. this._depthCullingState.zOffset = zOffset;
  6197. };
  6198. Engine.prototype.setDepthBuffer = function (enable) {
  6199. this._depthCullingState.depthTest = enable;
  6200. };
  6201. Engine.prototype.getDepthWrite = function () {
  6202. return this._depthCullingState.depthMask;
  6203. };
  6204. Engine.prototype.setDepthWrite = function (enable) {
  6205. this._depthCullingState.depthMask = enable;
  6206. };
  6207. Engine.prototype.setColorWrite = function (enable) {
  6208. this._gl.colorMask(enable, enable, enable, enable);
  6209. };
  6210. Engine.prototype.setAlphaMode = function (mode) {
  6211. if (this._alphaMode === mode) {
  6212. return;
  6213. }
  6214. switch (mode) {
  6215. case Engine.ALPHA_DISABLE:
  6216. this.setDepthWrite(true);
  6217. this._alphaState.alphaBlend = false;
  6218. break;
  6219. case Engine.ALPHA_COMBINE:
  6220. this.setDepthWrite(false);
  6221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6222. this._alphaState.alphaBlend = true;
  6223. break;
  6224. case Engine.ALPHA_ONEONE:
  6225. this.setDepthWrite(false);
  6226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6227. this._alphaState.alphaBlend = true;
  6228. break;
  6229. case Engine.ALPHA_ADD:
  6230. this.setDepthWrite(false);
  6231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6232. this._alphaState.alphaBlend = true;
  6233. break;
  6234. case Engine.ALPHA_SUBTRACT:
  6235. this.setDepthWrite(false);
  6236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6237. this._alphaState.alphaBlend = true;
  6238. break;
  6239. case Engine.ALPHA_MULTIPLY:
  6240. this.setDepthWrite(false);
  6241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6242. this._alphaState.alphaBlend = true;
  6243. break;
  6244. case Engine.ALPHA_MAXIMIZED:
  6245. this.setDepthWrite(false);
  6246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6247. this._alphaState.alphaBlend = true;
  6248. break;
  6249. }
  6250. this._alphaMode = mode;
  6251. };
  6252. Engine.prototype.getAlphaMode = function () {
  6253. return this._alphaMode;
  6254. };
  6255. Engine.prototype.setAlphaTesting = function (enable) {
  6256. this._alphaTest = enable;
  6257. };
  6258. Engine.prototype.getAlphaTesting = function () {
  6259. return this._alphaTest;
  6260. };
  6261. // Textures
  6262. Engine.prototype.wipeCaches = function () {
  6263. this.resetTextureCache();
  6264. this._currentEffect = null;
  6265. this._depthCullingState.reset();
  6266. this._alphaState.reset();
  6267. this._cachedVertexBuffers = null;
  6268. this._cachedIndexBuffer = null;
  6269. this._cachedEffectForVertexBuffers = null;
  6270. };
  6271. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6272. var gl = this._gl;
  6273. gl.bindTexture(gl.TEXTURE_2D, texture);
  6274. var magFilter = gl.NEAREST;
  6275. var minFilter = gl.NEAREST;
  6276. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6277. magFilter = gl.LINEAR;
  6278. minFilter = gl.LINEAR;
  6279. }
  6280. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6281. magFilter = gl.LINEAR;
  6282. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6283. }
  6284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6286. gl.bindTexture(gl.TEXTURE_2D, null);
  6287. texture.samplingMode = samplingMode;
  6288. };
  6289. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6290. var _this = this;
  6291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6292. if (onLoad === void 0) { onLoad = null; }
  6293. if (onError === void 0) { onError = null; }
  6294. if (buffer === void 0) { buffer = null; }
  6295. var texture = this._gl.createTexture();
  6296. var extension;
  6297. var fromData = false;
  6298. if (url.substr(0, 5) === "data:") {
  6299. fromData = true;
  6300. }
  6301. if (!fromData)
  6302. extension = url.substr(url.length - 4, 4).toLowerCase();
  6303. else {
  6304. var oldUrl = url;
  6305. fromData = oldUrl.split(':');
  6306. url = oldUrl;
  6307. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6308. }
  6309. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6310. var isTGA = (extension === ".tga");
  6311. scene._addPendingData(texture);
  6312. texture.url = url;
  6313. texture.noMipmap = noMipmap;
  6314. texture.references = 1;
  6315. texture.samplingMode = samplingMode;
  6316. this._loadedTexturesCache.push(texture);
  6317. var onerror = function () {
  6318. scene._removePendingData(texture);
  6319. if (onError) {
  6320. onError();
  6321. }
  6322. };
  6323. var callback;
  6324. if (isTGA) {
  6325. callback = function (arrayBuffer) {
  6326. var data = new Uint8Array(arrayBuffer);
  6327. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6328. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6329. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6330. }, onLoad, samplingMode);
  6331. };
  6332. if (!(fromData instanceof Array))
  6333. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6334. callback(arrayBuffer);
  6335. }, onerror, scene.database, true);
  6336. else
  6337. callback(buffer);
  6338. }
  6339. else if (isDDS) {
  6340. callback = function (data) {
  6341. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6342. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6343. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6344. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6345. }, onLoad, samplingMode);
  6346. };
  6347. if (!(fromData instanceof Array))
  6348. BABYLON.Tools.LoadFile(url, function (data) {
  6349. callback(data);
  6350. }, onerror, scene.database, true);
  6351. else
  6352. callback(buffer);
  6353. }
  6354. else {
  6355. var onload = function (img) {
  6356. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6357. var isPot = (img.width === potWidth && img.height === potHeight);
  6358. if (!isPot) {
  6359. _this._prepareWorkingCanvas();
  6360. _this._workingCanvas.width = potWidth;
  6361. _this._workingCanvas.height = potHeight;
  6362. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6363. _this._workingContext.imageSmoothingEnabled = false;
  6364. _this._workingContext.mozImageSmoothingEnabled = false;
  6365. _this._workingContext.oImageSmoothingEnabled = false;
  6366. _this._workingContext.webkitImageSmoothingEnabled = false;
  6367. _this._workingContext.msImageSmoothingEnabled = false;
  6368. }
  6369. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6370. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6371. _this._workingContext.imageSmoothingEnabled = true;
  6372. _this._workingContext.mozImageSmoothingEnabled = true;
  6373. _this._workingContext.oImageSmoothingEnabled = true;
  6374. _this._workingContext.webkitImageSmoothingEnabled = true;
  6375. _this._workingContext.msImageSmoothingEnabled = true;
  6376. }
  6377. }
  6378. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6379. }, onLoad, samplingMode);
  6380. };
  6381. if (!(fromData instanceof Array))
  6382. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6383. else
  6384. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6385. }
  6386. return texture;
  6387. };
  6388. Engine.prototype._getInternalFormat = function (format) {
  6389. var internalFormat = this._gl.RGBA;
  6390. switch (format) {
  6391. case Engine.TEXTUREFORMAT_ALPHA:
  6392. internalFormat = this._gl.ALPHA;
  6393. break;
  6394. case Engine.TEXTUREFORMAT_LUMINANCE:
  6395. internalFormat = this._gl.LUMINANCE;
  6396. break;
  6397. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6398. internalFormat = this._gl.LUMINANCE_ALPHA;
  6399. break;
  6400. case Engine.TEXTUREFORMAT_RGB:
  6401. internalFormat = this._gl.RGB;
  6402. break;
  6403. case Engine.TEXTUREFORMAT_RGBA:
  6404. internalFormat = this._gl.RGBA;
  6405. break;
  6406. }
  6407. return internalFormat;
  6408. };
  6409. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6410. if (compression === void 0) { compression = null; }
  6411. var internalFormat = this._getInternalFormat(format);
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6413. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6414. if (compression) {
  6415. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6416. }
  6417. else {
  6418. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6419. }
  6420. if (texture.generateMipMaps) {
  6421. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6422. }
  6423. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6424. this.resetTextureCache();
  6425. texture.isReady = true;
  6426. };
  6427. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6428. if (compression === void 0) { compression = null; }
  6429. var texture = this._gl.createTexture();
  6430. texture._baseWidth = width;
  6431. texture._baseHeight = height;
  6432. texture._width = width;
  6433. texture._height = height;
  6434. texture.references = 1;
  6435. this.updateRawTexture(texture, data, format, invertY, compression);
  6436. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6437. // Filters
  6438. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6439. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6441. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6442. texture.samplingMode = samplingMode;
  6443. this._loadedTexturesCache.push(texture);
  6444. return texture;
  6445. };
  6446. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6447. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6448. var texture = this._gl.createTexture();
  6449. texture._baseWidth = width;
  6450. texture._baseHeight = height;
  6451. if (forceExponantOfTwo) {
  6452. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6453. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6454. }
  6455. this.resetTextureCache();
  6456. texture._width = width;
  6457. texture._height = height;
  6458. texture.isReady = false;
  6459. texture.generateMipMaps = generateMipMaps;
  6460. texture.references = 1;
  6461. texture.samplingMode = samplingMode;
  6462. this.updateTextureSamplingMode(samplingMode, texture);
  6463. this._loadedTexturesCache.push(texture);
  6464. return texture;
  6465. };
  6466. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6467. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6468. if (texture.isCube) {
  6469. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6470. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6471. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6472. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6473. }
  6474. else {
  6475. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6476. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6477. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6478. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6479. }
  6480. };
  6481. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6482. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6483. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6484. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6485. if (texture.generateMipMaps) {
  6486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6487. }
  6488. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6489. this.resetTextureCache();
  6490. texture.isReady = true;
  6491. };
  6492. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6493. if (texture._isDisabled) {
  6494. return;
  6495. }
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6497. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6498. try {
  6499. // Testing video texture support
  6500. if (this._videoTextureSupported === undefined) {
  6501. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6502. if (this._gl.getError() !== 0) {
  6503. this._videoTextureSupported = false;
  6504. }
  6505. else {
  6506. this._videoTextureSupported = true;
  6507. }
  6508. }
  6509. // Copy video through the current working canvas if video texture is not supported
  6510. if (!this._videoTextureSupported) {
  6511. if (!texture._workingCanvas) {
  6512. texture._workingCanvas = document.createElement("canvas");
  6513. texture._workingContext = texture._workingCanvas.getContext("2d");
  6514. texture._workingCanvas.width = texture._width;
  6515. texture._workingCanvas.height = texture._height;
  6516. }
  6517. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6518. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6519. }
  6520. else {
  6521. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6522. }
  6523. if (texture.generateMipMaps) {
  6524. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6525. }
  6526. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6527. this.resetTextureCache();
  6528. texture.isReady = true;
  6529. }
  6530. catch (ex) {
  6531. // Something unexpected
  6532. // Let's disable the texture
  6533. texture._isDisabled = true;
  6534. }
  6535. };
  6536. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6537. // old version had a "generateMipMaps" arg instead of options.
  6538. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6539. // in the same way, generateDepthBuffer is defaulted to true
  6540. var generateMipMaps = false;
  6541. var generateDepthBuffer = true;
  6542. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6543. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6544. if (options !== undefined) {
  6545. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6546. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6547. type = options.type === undefined ? type : options.type;
  6548. if (options.samplingMode !== undefined) {
  6549. samplingMode = options.samplingMode;
  6550. }
  6551. if (type === Engine.TEXTURETYPE_FLOAT) {
  6552. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6553. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6554. }
  6555. }
  6556. var gl = this._gl;
  6557. var texture = gl.createTexture();
  6558. gl.bindTexture(gl.TEXTURE_2D, texture);
  6559. var width = size.width || size;
  6560. var height = size.height || size;
  6561. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6562. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6563. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6564. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6565. }
  6566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6570. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6571. var depthBuffer;
  6572. // Create the depth buffer
  6573. if (generateDepthBuffer) {
  6574. depthBuffer = gl.createRenderbuffer();
  6575. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6576. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6577. }
  6578. // Create the framebuffer
  6579. var framebuffer = gl.createFramebuffer();
  6580. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6581. if (generateDepthBuffer) {
  6582. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6583. }
  6584. if (generateMipMaps) {
  6585. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6586. }
  6587. // Unbind
  6588. gl.bindTexture(gl.TEXTURE_2D, null);
  6589. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6590. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6591. texture._framebuffer = framebuffer;
  6592. if (generateDepthBuffer) {
  6593. texture._depthBuffer = depthBuffer;
  6594. }
  6595. texture._width = width;
  6596. texture._height = height;
  6597. texture.isReady = true;
  6598. texture.generateMipMaps = generateMipMaps;
  6599. texture.references = 1;
  6600. texture.samplingMode = samplingMode;
  6601. this.resetTextureCache();
  6602. this._loadedTexturesCache.push(texture);
  6603. return texture;
  6604. };
  6605. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6606. var gl = this._gl;
  6607. var texture = gl.createTexture();
  6608. var generateMipMaps = true;
  6609. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6610. if (options !== undefined) {
  6611. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6612. if (options.samplingMode !== undefined) {
  6613. samplingMode = options.samplingMode;
  6614. }
  6615. }
  6616. texture.isCube = true;
  6617. texture.references = 1;
  6618. texture.generateMipMaps = generateMipMaps;
  6619. texture.references = 1;
  6620. texture.samplingMode = samplingMode;
  6621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6622. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6623. for (var face = 0; face < 6; face++) {
  6624. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6625. }
  6626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6630. // Create the depth buffer
  6631. var depthBuffer = gl.createRenderbuffer();
  6632. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6633. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6634. // Create the framebuffer
  6635. var framebuffer = gl.createFramebuffer();
  6636. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6637. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6638. // Mipmaps
  6639. if (texture.generateMipMaps) {
  6640. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6641. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6642. }
  6643. // Unbind
  6644. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6645. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6646. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6647. texture._framebuffer = framebuffer;
  6648. texture._depthBuffer = depthBuffer;
  6649. this.resetTextureCache();
  6650. texture._width = size;
  6651. texture._height = size;
  6652. texture.isReady = true;
  6653. return texture;
  6654. };
  6655. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6656. var _this = this;
  6657. var gl = this._gl;
  6658. var texture = gl.createTexture();
  6659. texture.isCube = true;
  6660. texture.url = rootUrl;
  6661. texture.references = 1;
  6662. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6663. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6664. if (isDDS) {
  6665. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6666. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6667. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6668. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6669. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6670. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6671. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6672. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6673. }
  6674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6678. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6679. _this.resetTextureCache();
  6680. texture._width = info.width;
  6681. texture._height = info.height;
  6682. texture.isReady = true;
  6683. }, null, null, true);
  6684. }
  6685. else {
  6686. cascadeLoad(rootUrl, scene, function (imgs) {
  6687. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6688. var height = width;
  6689. _this._prepareWorkingCanvas();
  6690. _this._workingCanvas.width = width;
  6691. _this._workingCanvas.height = height;
  6692. var faces = [
  6693. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6694. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6695. ];
  6696. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6697. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6698. for (var index = 0; index < faces.length; index++) {
  6699. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6700. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6701. }
  6702. if (!noMipmap) {
  6703. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6704. }
  6705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6709. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6710. _this.resetTextureCache();
  6711. texture._width = width;
  6712. texture._height = height;
  6713. texture.isReady = true;
  6714. }, files);
  6715. }
  6716. return texture;
  6717. };
  6718. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6719. var _this = this;
  6720. var gl = this._gl;
  6721. var texture = gl.createTexture();
  6722. scene._addPendingData(texture);
  6723. texture.isCube = true;
  6724. texture.references = 1;
  6725. texture.url = url;
  6726. var internalFormat = this._getInternalFormat(format);
  6727. var textureType = gl.UNSIGNED_BYTE;
  6728. if (type === Engine.TEXTURETYPE_FLOAT) {
  6729. textureType = gl.FLOAT;
  6730. }
  6731. var width = size;
  6732. var height = width;
  6733. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6734. texture._width = width;
  6735. texture._height = height;
  6736. var onerror = function () {
  6737. scene._removePendingData(texture);
  6738. };
  6739. var internalCallback = function (data) {
  6740. var rgbeDataArrays = callback(data);
  6741. var facesIndex = [
  6742. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6743. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6744. ];
  6745. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6746. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6747. for (var index = 0; index < facesIndex.length; index++) {
  6748. var faceData = rgbeDataArrays[index];
  6749. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6750. }
  6751. if (!noMipmap && isPot) {
  6752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6753. }
  6754. else {
  6755. noMipmap = true;
  6756. }
  6757. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6760. }
  6761. else {
  6762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6764. }
  6765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6767. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6768. texture.isReady = true;
  6769. _this.resetTextureCache();
  6770. scene._removePendingData(texture);
  6771. };
  6772. BABYLON.Tools.LoadFile(url, function (data) {
  6773. internalCallback(data);
  6774. }, onerror, scene.database, true);
  6775. return texture;
  6776. };
  6777. ;
  6778. Engine.prototype._releaseTexture = function (texture) {
  6779. var gl = this._gl;
  6780. if (texture._framebuffer) {
  6781. gl.deleteFramebuffer(texture._framebuffer);
  6782. }
  6783. if (texture._depthBuffer) {
  6784. gl.deleteRenderbuffer(texture._depthBuffer);
  6785. }
  6786. gl.deleteTexture(texture);
  6787. // Unbind channels
  6788. this.unbindAllTextures();
  6789. var index = this._loadedTexturesCache.indexOf(texture);
  6790. if (index !== -1) {
  6791. this._loadedTexturesCache.splice(index, 1);
  6792. }
  6793. };
  6794. Engine.prototype.bindSamplers = function (effect) {
  6795. this._gl.useProgram(effect.getProgram());
  6796. var samplers = effect.getSamplers();
  6797. for (var index = 0; index < samplers.length; index++) {
  6798. var uniform = effect.getUniform(samplers[index]);
  6799. this._gl.uniform1i(uniform, index);
  6800. }
  6801. this._currentEffect = null;
  6802. };
  6803. Engine.prototype._bindTexture = function (channel, texture) {
  6804. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6805. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6806. this._activeTexturesCache[channel] = null;
  6807. };
  6808. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6809. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6810. };
  6811. Engine.prototype.unbindAllTextures = function () {
  6812. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6813. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6814. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6815. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6816. this._activeTexturesCache[channel] = null;
  6817. }
  6818. };
  6819. Engine.prototype.setTexture = function (channel, texture) {
  6820. if (channel < 0) {
  6821. return;
  6822. }
  6823. // Not ready?
  6824. if (!texture || !texture.isReady()) {
  6825. if (this._activeTexturesCache[channel] != null) {
  6826. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6827. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6828. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6829. this._activeTexturesCache[channel] = null;
  6830. }
  6831. return;
  6832. }
  6833. // Video
  6834. var alreadyActivated = false;
  6835. if (texture instanceof BABYLON.VideoTexture) {
  6836. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6837. alreadyActivated = true;
  6838. texture.update();
  6839. }
  6840. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6841. texture.delayLoad();
  6842. return;
  6843. }
  6844. if (this._activeTexturesCache[channel] === texture) {
  6845. return;
  6846. }
  6847. this._activeTexturesCache[channel] = texture;
  6848. var internalTexture = texture.getInternalTexture();
  6849. if (!alreadyActivated) {
  6850. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6851. }
  6852. if (internalTexture.isCube) {
  6853. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6854. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6855. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6856. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6857. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6858. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6859. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6860. }
  6861. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6862. }
  6863. else {
  6864. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6865. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6866. internalTexture._cachedWrapU = texture.wrapU;
  6867. switch (texture.wrapU) {
  6868. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6869. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6870. break;
  6871. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6873. break;
  6874. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6876. break;
  6877. }
  6878. }
  6879. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6880. internalTexture._cachedWrapV = texture.wrapV;
  6881. switch (texture.wrapV) {
  6882. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6884. break;
  6885. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6887. break;
  6888. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6890. break;
  6891. }
  6892. }
  6893. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6894. }
  6895. };
  6896. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6897. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6898. var value = texture.anisotropicFilteringLevel;
  6899. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6900. value = 1;
  6901. }
  6902. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6903. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6904. texture._cachedAnisotropicFilteringLevel = value;
  6905. }
  6906. };
  6907. Engine.prototype.readPixels = function (x, y, width, height) {
  6908. var data = new Uint8Array(height * width * 4);
  6909. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6910. return data;
  6911. };
  6912. Engine.prototype.releaseInternalTexture = function (texture) {
  6913. if (!texture) {
  6914. return;
  6915. }
  6916. texture.references--;
  6917. // Final reference ?
  6918. if (texture.references === 0) {
  6919. var texturesCache = this.getLoadedTexturesCache();
  6920. var index = texturesCache.indexOf(texture);
  6921. if (index > -1) {
  6922. texturesCache.splice(index, 1);
  6923. }
  6924. this._releaseTexture(texture);
  6925. }
  6926. };
  6927. // Dispose
  6928. Engine.prototype.dispose = function () {
  6929. this.hideLoadingUI();
  6930. this.stopRenderLoop();
  6931. // Release scenes
  6932. while (this.scenes.length) {
  6933. this.scenes[0].dispose();
  6934. }
  6935. // Release audio engine
  6936. Engine.audioEngine.dispose();
  6937. // Release effects
  6938. for (var name in this._compiledEffects) {
  6939. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6940. }
  6941. // Unbind
  6942. for (var i in this._vertexAttribArrays) {
  6943. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6944. continue;
  6945. }
  6946. this._gl.disableVertexAttribArray(i);
  6947. }
  6948. this._gl = null;
  6949. // Events
  6950. window.removeEventListener("blur", this._onBlur);
  6951. window.removeEventListener("focus", this._onFocus);
  6952. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6953. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6954. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6955. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6956. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6957. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6958. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6959. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6960. };
  6961. // Loading screen
  6962. Engine.prototype.displayLoadingUI = function () {
  6963. this._loadingScreen.displayLoadingUI();
  6964. };
  6965. Engine.prototype.hideLoadingUI = function () {
  6966. this._loadingScreen.hideLoadingUI();
  6967. };
  6968. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6969. get: function () {
  6970. return this._loadingScreen;
  6971. },
  6972. set: function (loadingScreen) {
  6973. this._loadingScreen = loadingScreen;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6979. set: function (text) {
  6980. this._loadingScreen.loadingUIText = text;
  6981. },
  6982. enumerable: true,
  6983. configurable: true
  6984. });
  6985. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6986. set: function (color) {
  6987. this._loadingScreen.loadingUIBackgroundColor = color;
  6988. },
  6989. enumerable: true,
  6990. configurable: true
  6991. });
  6992. // FPS
  6993. Engine.prototype.getFps = function () {
  6994. return this.fps;
  6995. };
  6996. Engine.prototype.getDeltaTime = function () {
  6997. return this.deltaTime;
  6998. };
  6999. Engine.prototype._measureFps = function () {
  7000. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7001. var length = this.previousFramesDuration.length;
  7002. if (length >= 2) {
  7003. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7004. }
  7005. if (length >= this.fpsRange) {
  7006. if (length > this.fpsRange) {
  7007. this.previousFramesDuration.splice(0, 1);
  7008. length = this.previousFramesDuration.length;
  7009. }
  7010. var sum = 0;
  7011. for (var id = 0; id < length - 1; id++) {
  7012. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7013. }
  7014. this.fps = 1000.0 / (sum / (length - 1));
  7015. }
  7016. };
  7017. // Statics
  7018. Engine.isSupported = function () {
  7019. try {
  7020. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7021. if (navigator.isCocoonJS) {
  7022. return true;
  7023. }
  7024. var tempcanvas = document.createElement("canvas");
  7025. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7026. return gl != null && !!window.WebGLRenderingContext;
  7027. }
  7028. catch (e) {
  7029. return false;
  7030. }
  7031. };
  7032. // Const statics
  7033. Engine._ALPHA_DISABLE = 0;
  7034. Engine._ALPHA_ADD = 1;
  7035. Engine._ALPHA_COMBINE = 2;
  7036. Engine._ALPHA_SUBTRACT = 3;
  7037. Engine._ALPHA_MULTIPLY = 4;
  7038. Engine._ALPHA_MAXIMIZED = 5;
  7039. Engine._ALPHA_ONEONE = 6;
  7040. Engine._DELAYLOADSTATE_NONE = 0;
  7041. Engine._DELAYLOADSTATE_LOADED = 1;
  7042. Engine._DELAYLOADSTATE_LOADING = 2;
  7043. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7044. Engine._TEXTUREFORMAT_ALPHA = 0;
  7045. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7046. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7047. Engine._TEXTUREFORMAT_RGB = 4;
  7048. Engine._TEXTUREFORMAT_RGBA = 5;
  7049. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7050. Engine._TEXTURETYPE_FLOAT = 1;
  7051. // Updatable statics so stick with vars here
  7052. Engine.Epsilon = 0.001;
  7053. Engine.CollisionsEpsilon = 0.001;
  7054. Engine.CodeRepository = "src/";
  7055. Engine.ShadersRepository = "src/Shaders/";
  7056. return Engine;
  7057. })();
  7058. BABYLON.Engine = Engine;
  7059. })(BABYLON || (BABYLON = {}));
  7060. var BABYLON;
  7061. (function (BABYLON) {
  7062. /**
  7063. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7064. */
  7065. var Node = (function () {
  7066. /**
  7067. * @constructor
  7068. * @param {string} name - the name and id to be given to this node
  7069. * @param {BABYLON.Scene} the scene this node will be added to
  7070. */
  7071. function Node(name, scene) {
  7072. this.state = "";
  7073. this.animations = new Array();
  7074. this._ranges = {};
  7075. this._childrenFlag = -1;
  7076. this._isEnabled = true;
  7077. this._isReady = true;
  7078. this._currentRenderId = -1;
  7079. this._parentRenderId = -1;
  7080. this.name = name;
  7081. this.id = name;
  7082. this._scene = scene;
  7083. this._initCache();
  7084. }
  7085. Node.prototype.getScene = function () {
  7086. return this._scene;
  7087. };
  7088. Node.prototype.getEngine = function () {
  7089. return this._scene.getEngine();
  7090. };
  7091. // override it in derived class
  7092. Node.prototype.getWorldMatrix = function () {
  7093. return BABYLON.Matrix.Identity();
  7094. };
  7095. // override it in derived class if you add new variables to the cache
  7096. // and call the parent class method
  7097. Node.prototype._initCache = function () {
  7098. this._cache = {};
  7099. this._cache.parent = undefined;
  7100. };
  7101. Node.prototype.updateCache = function (force) {
  7102. if (!force && this.isSynchronized())
  7103. return;
  7104. this._cache.parent = this.parent;
  7105. this._updateCache();
  7106. };
  7107. // override it in derived class if you add new variables to the cache
  7108. // and call the parent class method if !ignoreParentClass
  7109. Node.prototype._updateCache = function (ignoreParentClass) {
  7110. };
  7111. // override it in derived class if you add new variables to the cache
  7112. Node.prototype._isSynchronized = function () {
  7113. return true;
  7114. };
  7115. Node.prototype._markSyncedWithParent = function () {
  7116. this._parentRenderId = this.parent._currentRenderId;
  7117. };
  7118. Node.prototype.isSynchronizedWithParent = function () {
  7119. if (!this.parent) {
  7120. return true;
  7121. }
  7122. if (this._parentRenderId !== this.parent._currentRenderId) {
  7123. return false;
  7124. }
  7125. return this.parent.isSynchronized();
  7126. };
  7127. Node.prototype.isSynchronized = function (updateCache) {
  7128. var check = this.hasNewParent();
  7129. check = check || !this.isSynchronizedWithParent();
  7130. check = check || !this._isSynchronized();
  7131. if (updateCache)
  7132. this.updateCache(true);
  7133. return !check;
  7134. };
  7135. Node.prototype.hasNewParent = function (update) {
  7136. if (this._cache.parent === this.parent)
  7137. return false;
  7138. if (update)
  7139. this._cache.parent = this.parent;
  7140. return true;
  7141. };
  7142. /**
  7143. * Is this node ready to be used/rendered
  7144. * @return {boolean} is it ready
  7145. */
  7146. Node.prototype.isReady = function () {
  7147. return this._isReady;
  7148. };
  7149. /**
  7150. * Is this node enabled.
  7151. * If the node has a parent and is enabled, the parent will be inspected as well.
  7152. * @return {boolean} whether this node (and its parent) is enabled.
  7153. * @see setEnabled
  7154. */
  7155. Node.prototype.isEnabled = function () {
  7156. if (!this._isEnabled) {
  7157. return false;
  7158. }
  7159. if (this.parent) {
  7160. return this.parent.isEnabled();
  7161. }
  7162. return true;
  7163. };
  7164. /**
  7165. * Set the enabled state of this node.
  7166. * @param {boolean} value - the new enabled state
  7167. * @see isEnabled
  7168. */
  7169. Node.prototype.setEnabled = function (value) {
  7170. this._isEnabled = value;
  7171. };
  7172. /**
  7173. * Is this node a descendant of the given node.
  7174. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7175. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7176. * @see parent
  7177. */
  7178. Node.prototype.isDescendantOf = function (ancestor) {
  7179. if (this.parent) {
  7180. if (this.parent === ancestor) {
  7181. return true;
  7182. }
  7183. return this.parent.isDescendantOf(ancestor);
  7184. }
  7185. return false;
  7186. };
  7187. Node.prototype._getDescendants = function (list, results) {
  7188. for (var index = 0; index < list.length; index++) {
  7189. var item = list[index];
  7190. if (item.isDescendantOf(this)) {
  7191. results.push(item);
  7192. }
  7193. }
  7194. };
  7195. /**
  7196. * Will return all nodes that have this node as parent.
  7197. * @return {BABYLON.Node[]} all children nodes of all types.
  7198. */
  7199. Node.prototype.getDescendants = function () {
  7200. var results = [];
  7201. this._getDescendants(this._scene.meshes, results);
  7202. this._getDescendants(this._scene.lights, results);
  7203. this._getDescendants(this._scene.cameras, results);
  7204. return results;
  7205. };
  7206. Node.prototype._setReady = function (state) {
  7207. if (state === this._isReady) {
  7208. return;
  7209. }
  7210. if (!state) {
  7211. this._isReady = false;
  7212. return;
  7213. }
  7214. this._isReady = true;
  7215. if (this.onReady) {
  7216. this.onReady(this);
  7217. }
  7218. };
  7219. Node.prototype.getAnimationByName = function (name) {
  7220. for (var i = 0; i < this.animations.length; i++) {
  7221. var animation = this.animations[i];
  7222. if (animation.name === name) {
  7223. return animation;
  7224. }
  7225. }
  7226. return null;
  7227. };
  7228. Node.prototype.createAnimationRange = function (name, from, to) {
  7229. // check name not already in use
  7230. if (!this._ranges[name]) {
  7231. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7232. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7233. if (this.animations[i]) {
  7234. this.animations[i].createRange(name, from, to);
  7235. }
  7236. }
  7237. }
  7238. };
  7239. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7240. if (deleteFrames === void 0) { deleteFrames = true; }
  7241. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7242. if (this.animations[i]) {
  7243. this.animations[i].deleteRange(name, deleteFrames);
  7244. }
  7245. }
  7246. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7247. };
  7248. Node.prototype.getAnimationRange = function (name) {
  7249. return this._ranges[name];
  7250. };
  7251. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7252. var range = this.getAnimationRange(name);
  7253. if (!range) {
  7254. return null;
  7255. }
  7256. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7257. };
  7258. Node.prototype.serializeAnimationRanges = function () {
  7259. var serializationRanges = [];
  7260. for (var name in this._ranges) {
  7261. var range = {};
  7262. range.name = name;
  7263. range.from = this._ranges[name].from;
  7264. range.to = this._ranges[name].to;
  7265. serializationRanges.push(range);
  7266. }
  7267. return serializationRanges;
  7268. };
  7269. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7270. if (parsedNode.ranges) {
  7271. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7272. var data = parsedNode.ranges[index];
  7273. node.createAnimationRange(data.name, data.from, data.to);
  7274. }
  7275. }
  7276. };
  7277. return Node;
  7278. })();
  7279. BABYLON.Node = Node;
  7280. })(BABYLON || (BABYLON = {}));
  7281. var BABYLON;
  7282. (function (BABYLON) {
  7283. var FilesInput = (function () {
  7284. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7285. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7286. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7287. this._engine = p_engine;
  7288. this._canvas = p_canvas;
  7289. this._currentScene = p_scene;
  7290. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7291. this._progressCallback = p_progressCallback;
  7292. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7293. this._textureLoadingCallback = p_textureLoadingCallback;
  7294. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7295. }
  7296. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7297. var _this = this;
  7298. if (p_elementToMonitor) {
  7299. this._elementToMonitor = p_elementToMonitor;
  7300. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7301. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7302. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7303. }
  7304. };
  7305. FilesInput.prototype.renderFunction = function () {
  7306. if (this._additionnalRenderLoopLogicCallback) {
  7307. this._additionnalRenderLoopLogicCallback();
  7308. }
  7309. if (this._currentScene) {
  7310. if (this._textureLoadingCallback) {
  7311. var remaining = this._currentScene.getWaitingItemsCount();
  7312. if (remaining > 0) {
  7313. this._textureLoadingCallback(remaining);
  7314. }
  7315. }
  7316. this._currentScene.render();
  7317. }
  7318. };
  7319. FilesInput.prototype.drag = function (e) {
  7320. e.stopPropagation();
  7321. e.preventDefault();
  7322. };
  7323. FilesInput.prototype.drop = function (eventDrop) {
  7324. eventDrop.stopPropagation();
  7325. eventDrop.preventDefault();
  7326. this.loadFiles(eventDrop);
  7327. };
  7328. FilesInput.prototype.loadFiles = function (event) {
  7329. if (this._startingProcessingFilesCallback)
  7330. this._startingProcessingFilesCallback();
  7331. // Handling data transfer via drag'n'drop
  7332. if (event && event.dataTransfer && event.dataTransfer.files) {
  7333. this._filesToLoad = event.dataTransfer.files;
  7334. }
  7335. // Handling files from input files
  7336. if (event && event.target && event.target.files) {
  7337. this._filesToLoad = event.target.files;
  7338. }
  7339. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7340. for (var i = 0; i < this._filesToLoad.length; i++) {
  7341. switch (this._filesToLoad[i].type) {
  7342. case "image/jpeg":
  7343. case "image/png":
  7344. case "image/bmp":
  7345. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7346. break;
  7347. case "image/targa":
  7348. case "image/vnd.ms-dds":
  7349. case "audio/wav":
  7350. case "audio/x-wav":
  7351. case "audio/mp3":
  7352. case "audio/mpeg":
  7353. case "audio/mpeg3":
  7354. case "audio/x-mpeg-3":
  7355. case "audio/ogg":
  7356. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7357. break;
  7358. default:
  7359. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7360. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7361. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7362. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7363. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7364. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7365. this._sceneFileToLoad = this._filesToLoad[i];
  7366. }
  7367. break;
  7368. }
  7369. }
  7370. this.reload();
  7371. }
  7372. };
  7373. FilesInput.prototype.reload = function () {
  7374. var _this = this;
  7375. var that = this;
  7376. // If a ".babylon" file has been provided
  7377. if (this._sceneFileToLoad) {
  7378. if (this._currentScene) {
  7379. if (BABYLON.Tools.errorsCount > 0) {
  7380. BABYLON.Tools.ClearLogCache();
  7381. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7382. }
  7383. this._engine.stopRenderLoop();
  7384. this._currentScene.dispose();
  7385. }
  7386. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7387. that._currentScene = newScene;
  7388. // Wait for textures and shaders to be ready
  7389. that._currentScene.executeWhenReady(function () {
  7390. // Attach camera to canvas inputs
  7391. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7392. that._currentScene.createDefaultCameraOrLight();
  7393. }
  7394. that._currentScene.activeCamera.attachControl(that._canvas);
  7395. if (that._sceneLoadedCallback) {
  7396. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7397. }
  7398. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7399. });
  7400. }, function (progress) {
  7401. if (_this._progressCallback) {
  7402. _this._progressCallback(progress);
  7403. }
  7404. });
  7405. }
  7406. else {
  7407. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7408. }
  7409. };
  7410. FilesInput.FilesTextures = new Array();
  7411. FilesInput.FilesToLoad = new Array();
  7412. return FilesInput;
  7413. })();
  7414. BABYLON.FilesInput = FilesInput;
  7415. })(BABYLON || (BABYLON = {}));
  7416. var BABYLON;
  7417. (function (BABYLON) {
  7418. var IntersectionInfo = (function () {
  7419. function IntersectionInfo(bu, bv, distance) {
  7420. this.bu = bu;
  7421. this.bv = bv;
  7422. this.distance = distance;
  7423. this.faceId = 0;
  7424. this.subMeshId = 0;
  7425. }
  7426. return IntersectionInfo;
  7427. })();
  7428. BABYLON.IntersectionInfo = IntersectionInfo;
  7429. var PickingInfo = (function () {
  7430. function PickingInfo() {
  7431. this.hit = false;
  7432. this.distance = 0;
  7433. this.pickedPoint = null;
  7434. this.pickedMesh = null;
  7435. this.bu = 0;
  7436. this.bv = 0;
  7437. this.faceId = -1;
  7438. this.subMeshId = 0;
  7439. this.pickedSprite = null;
  7440. }
  7441. // Methods
  7442. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7443. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7444. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7445. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7446. return null;
  7447. }
  7448. var indices = this.pickedMesh.getIndices();
  7449. var result;
  7450. if (useVerticesNormals) {
  7451. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7452. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7453. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7454. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7455. normal0 = normal0.scale(this.bu);
  7456. normal1 = normal1.scale(this.bv);
  7457. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7458. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7459. }
  7460. else {
  7461. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7462. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7463. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7464. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7465. var p1p2 = vertex1.subtract(vertex2);
  7466. var p3p2 = vertex3.subtract(vertex2);
  7467. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7468. }
  7469. if (useWorldCoordinates) {
  7470. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7471. }
  7472. return BABYLON.Vector3.Normalize(result);
  7473. };
  7474. PickingInfo.prototype.getTextureCoordinates = function () {
  7475. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7476. return null;
  7477. }
  7478. var indices = this.pickedMesh.getIndices();
  7479. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7480. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7481. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7482. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7483. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7484. uv1 = uv1.scale(this.bu);
  7485. uv2 = uv2.scale(this.bv);
  7486. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7487. };
  7488. return PickingInfo;
  7489. })();
  7490. BABYLON.PickingInfo = PickingInfo;
  7491. })(BABYLON || (BABYLON = {}));
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var BoundingSphere = (function () {
  7495. function BoundingSphere(minimum, maximum) {
  7496. this.minimum = minimum;
  7497. this.maximum = maximum;
  7498. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7499. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7500. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7501. this.radius = distance * 0.5;
  7502. this.centerWorld = BABYLON.Vector3.Zero();
  7503. this._update(BABYLON.Matrix.Identity());
  7504. }
  7505. // Methods
  7506. BoundingSphere.prototype._update = function (world) {
  7507. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7508. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7509. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7510. };
  7511. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7512. for (var i = 0; i < 6; i++) {
  7513. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7514. return false;
  7515. }
  7516. return true;
  7517. };
  7518. BoundingSphere.prototype.intersectsPoint = function (point) {
  7519. var x = this.centerWorld.x - point.x;
  7520. var y = this.centerWorld.y - point.y;
  7521. var z = this.centerWorld.z - point.z;
  7522. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7523. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7524. return false;
  7525. return true;
  7526. };
  7527. // Statics
  7528. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7529. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7530. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7531. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7532. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7533. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7534. return false;
  7535. return true;
  7536. };
  7537. return BoundingSphere;
  7538. })();
  7539. BABYLON.BoundingSphere = BoundingSphere;
  7540. })(BABYLON || (BABYLON = {}));
  7541. var BABYLON;
  7542. (function (BABYLON) {
  7543. var BoundingBox = (function () {
  7544. function BoundingBox(minimum, maximum) {
  7545. this.minimum = minimum;
  7546. this.maximum = maximum;
  7547. this.vectors = new Array();
  7548. this.vectorsWorld = new Array();
  7549. // Bounding vectors
  7550. this.vectors.push(this.minimum.clone());
  7551. this.vectors.push(this.maximum.clone());
  7552. this.vectors.push(this.minimum.clone());
  7553. this.vectors[2].x = this.maximum.x;
  7554. this.vectors.push(this.minimum.clone());
  7555. this.vectors[3].y = this.maximum.y;
  7556. this.vectors.push(this.minimum.clone());
  7557. this.vectors[4].z = this.maximum.z;
  7558. this.vectors.push(this.maximum.clone());
  7559. this.vectors[5].z = this.minimum.z;
  7560. this.vectors.push(this.maximum.clone());
  7561. this.vectors[6].x = this.minimum.x;
  7562. this.vectors.push(this.maximum.clone());
  7563. this.vectors[7].y = this.minimum.y;
  7564. // OBB
  7565. this.center = this.maximum.add(this.minimum).scale(0.5);
  7566. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7567. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7568. // World
  7569. for (var index = 0; index < this.vectors.length; index++) {
  7570. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7571. }
  7572. this.minimumWorld = BABYLON.Vector3.Zero();
  7573. this.maximumWorld = BABYLON.Vector3.Zero();
  7574. this._update(BABYLON.Matrix.Identity());
  7575. }
  7576. // Methods
  7577. BoundingBox.prototype.getWorldMatrix = function () {
  7578. return this._worldMatrix;
  7579. };
  7580. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7581. this._worldMatrix.copyFrom(matrix);
  7582. return this;
  7583. };
  7584. BoundingBox.prototype._update = function (world) {
  7585. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7586. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7587. for (var index = 0; index < this.vectors.length; index++) {
  7588. var v = this.vectorsWorld[index];
  7589. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7590. if (v.x < this.minimumWorld.x)
  7591. this.minimumWorld.x = v.x;
  7592. if (v.y < this.minimumWorld.y)
  7593. this.minimumWorld.y = v.y;
  7594. if (v.z < this.minimumWorld.z)
  7595. this.minimumWorld.z = v.z;
  7596. if (v.x > this.maximumWorld.x)
  7597. this.maximumWorld.x = v.x;
  7598. if (v.y > this.maximumWorld.y)
  7599. this.maximumWorld.y = v.y;
  7600. if (v.z > this.maximumWorld.z)
  7601. this.maximumWorld.z = v.z;
  7602. }
  7603. // OBB
  7604. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7605. this.center.scaleInPlace(0.5);
  7606. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7607. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7608. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7609. this._worldMatrix = world;
  7610. };
  7611. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7612. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7613. };
  7614. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7615. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7616. };
  7617. BoundingBox.prototype.intersectsPoint = function (point) {
  7618. var delta = -BABYLON.Engine.Epsilon;
  7619. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7620. return false;
  7621. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7622. return false;
  7623. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7624. return false;
  7625. return true;
  7626. };
  7627. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7628. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7629. };
  7630. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7631. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7632. return false;
  7633. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7634. return false;
  7635. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7636. return false;
  7637. return true;
  7638. };
  7639. // Statics
  7640. BoundingBox.Intersects = function (box0, box1) {
  7641. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7642. return false;
  7643. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7644. return false;
  7645. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7646. return false;
  7647. return true;
  7648. };
  7649. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7650. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7651. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7652. return (num <= (sphereRadius * sphereRadius));
  7653. };
  7654. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7655. for (var p = 0; p < 6; p++) {
  7656. for (var i = 0; i < 8; i++) {
  7657. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7658. return false;
  7659. }
  7660. }
  7661. }
  7662. return true;
  7663. };
  7664. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7665. for (var p = 0; p < 6; p++) {
  7666. var inCount = 8;
  7667. for (var i = 0; i < 8; i++) {
  7668. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7669. --inCount;
  7670. }
  7671. else {
  7672. break;
  7673. }
  7674. }
  7675. if (inCount === 0)
  7676. return false;
  7677. }
  7678. return true;
  7679. };
  7680. return BoundingBox;
  7681. })();
  7682. BABYLON.BoundingBox = BoundingBox;
  7683. })(BABYLON || (BABYLON = {}));
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var computeBoxExtents = function (axis, box) {
  7687. var p = BABYLON.Vector3.Dot(box.center, axis);
  7688. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7689. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7690. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7691. var r = r0 + r1 + r2;
  7692. return {
  7693. min: p - r,
  7694. max: p + r
  7695. };
  7696. };
  7697. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7698. var axisOverlap = function (axis, box0, box1) {
  7699. var result0 = computeBoxExtents(axis, box0);
  7700. var result1 = computeBoxExtents(axis, box1);
  7701. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7702. };
  7703. var BoundingInfo = (function () {
  7704. function BoundingInfo(minimum, maximum) {
  7705. this.minimum = minimum;
  7706. this.maximum = maximum;
  7707. this._isLocked = false;
  7708. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7709. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7710. }
  7711. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7712. get: function () {
  7713. return this._isLocked;
  7714. },
  7715. set: function (value) {
  7716. this._isLocked = value;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. // Methods
  7722. BoundingInfo.prototype.update = function (world) {
  7723. if (this._isLocked) {
  7724. return;
  7725. }
  7726. this.boundingBox._update(world);
  7727. this.boundingSphere._update(world);
  7728. };
  7729. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7730. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7731. return false;
  7732. return this.boundingBox.isInFrustum(frustumPlanes);
  7733. };
  7734. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7735. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7736. };
  7737. BoundingInfo.prototype._checkCollision = function (collider) {
  7738. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7739. };
  7740. BoundingInfo.prototype.intersectsPoint = function (point) {
  7741. if (!this.boundingSphere.centerWorld) {
  7742. return false;
  7743. }
  7744. if (!this.boundingSphere.intersectsPoint(point)) {
  7745. return false;
  7746. }
  7747. if (!this.boundingBox.intersectsPoint(point)) {
  7748. return false;
  7749. }
  7750. return true;
  7751. };
  7752. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7753. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7754. return false;
  7755. }
  7756. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7757. return false;
  7758. }
  7759. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7760. return false;
  7761. }
  7762. if (!precise) {
  7763. return true;
  7764. }
  7765. var box0 = this.boundingBox;
  7766. var box1 = boundingInfo.boundingBox;
  7767. if (!axisOverlap(box0.directions[0], box0, box1))
  7768. return false;
  7769. if (!axisOverlap(box0.directions[1], box0, box1))
  7770. return false;
  7771. if (!axisOverlap(box0.directions[2], box0, box1))
  7772. return false;
  7773. if (!axisOverlap(box1.directions[0], box0, box1))
  7774. return false;
  7775. if (!axisOverlap(box1.directions[1], box0, box1))
  7776. return false;
  7777. if (!axisOverlap(box1.directions[2], box0, box1))
  7778. return false;
  7779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7780. return false;
  7781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7782. return false;
  7783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7784. return false;
  7785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7786. return false;
  7787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7788. return false;
  7789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7790. return false;
  7791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7792. return false;
  7793. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7794. return false;
  7795. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7796. return false;
  7797. return true;
  7798. };
  7799. return BoundingInfo;
  7800. })();
  7801. BABYLON.BoundingInfo = BoundingInfo;
  7802. })(BABYLON || (BABYLON = {}));
  7803. var BABYLON;
  7804. (function (BABYLON) {
  7805. var AbstractMesh = (function (_super) {
  7806. __extends(AbstractMesh, _super);
  7807. // Constructor
  7808. function AbstractMesh(name, scene) {
  7809. var _this = this;
  7810. _super.call(this, name, scene);
  7811. // Properties
  7812. this.definedFacingForward = true; // orientation for POV movement & rotation
  7813. this.position = new BABYLON.Vector3(0, 0, 0);
  7814. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7815. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7816. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7817. this.visibility = 1.0;
  7818. this.alphaIndex = Number.MAX_VALUE;
  7819. this.infiniteDistance = false;
  7820. this.isVisible = true;
  7821. this.isPickable = true;
  7822. this.showBoundingBox = false;
  7823. this.showSubMeshesBoundingBox = false;
  7824. this.onDispose = null;
  7825. this.isBlocker = false;
  7826. this.renderingGroupId = 0;
  7827. this.receiveShadows = false;
  7828. this.renderOutline = false;
  7829. this.outlineColor = BABYLON.Color3.Red();
  7830. this.outlineWidth = 0.02;
  7831. this.renderOverlay = false;
  7832. this.overlayColor = BABYLON.Color3.Red();
  7833. this.overlayAlpha = 0.5;
  7834. this.hasVertexAlpha = false;
  7835. this.useVertexColors = true;
  7836. this.applyFog = true;
  7837. this.computeBonesUsingShaders = true;
  7838. this.scalingDeterminant = 1;
  7839. this.numBoneInfluencers = 4;
  7840. this.useOctreeForRenderingSelection = true;
  7841. this.useOctreeForPicking = true;
  7842. this.useOctreeForCollisions = true;
  7843. this.layerMask = 0x0FFFFFFF;
  7844. this.alwaysSelectAsActiveMesh = false;
  7845. // Physics
  7846. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7847. // Collisions
  7848. this._checkCollisions = false;
  7849. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7850. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7851. this._collider = new BABYLON.Collider();
  7852. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7853. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7854. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7855. // Edges
  7856. this.edgesWidth = 1;
  7857. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7858. // Cache
  7859. this._localWorld = BABYLON.Matrix.Zero();
  7860. this._worldMatrix = BABYLON.Matrix.Zero();
  7861. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7862. this._absolutePosition = BABYLON.Vector3.Zero();
  7863. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7864. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7865. this._isDirty = false;
  7866. this._pivotMatrix = BABYLON.Matrix.Identity();
  7867. this._isDisposed = false;
  7868. this._renderId = 0;
  7869. this._intersectionsInProgress = new Array();
  7870. this._onAfterWorldMatrixUpdate = new Array();
  7871. this._isWorldMatrixFrozen = false;
  7872. this._unIndexed = false;
  7873. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7874. if (collidedMesh === void 0) { collidedMesh = null; }
  7875. //TODO move this to the collision coordinator!
  7876. if (_this.getScene().workerCollisions)
  7877. newPosition.multiplyInPlace(_this._collider.radius);
  7878. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7879. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7880. _this.position.addInPlace(_this._diffPositionForCollisions);
  7881. }
  7882. if (_this.onCollide && collidedMesh) {
  7883. _this.onCollide(collidedMesh);
  7884. }
  7885. if (_this.onCollisionPositionChange) {
  7886. _this.onCollisionPositionChange(_this.position);
  7887. }
  7888. };
  7889. scene.addMesh(this);
  7890. }
  7891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7892. get: function () {
  7893. return AbstractMesh._BILLBOARDMODE_NONE;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7899. get: function () {
  7900. return AbstractMesh._BILLBOARDMODE_X;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7906. get: function () {
  7907. return AbstractMesh._BILLBOARDMODE_Y;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7913. get: function () {
  7914. return AbstractMesh._BILLBOARDMODE_Z;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7920. get: function () {
  7921. return AbstractMesh._BILLBOARDMODE_ALL;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7927. get: function () {
  7928. return this._skeleton;
  7929. },
  7930. set: function (value) {
  7931. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7932. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7933. }
  7934. if (value && value.needInitialSkinMatrix) {
  7935. value._registerMeshWithPoseMatrix(this);
  7936. }
  7937. this._skeleton = value;
  7938. if (!this._skeleton) {
  7939. this._bonesTransformMatrices = null;
  7940. }
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. // Methods
  7946. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7947. this._poseMatrix.copyFrom(matrix);
  7948. };
  7949. AbstractMesh.prototype.getPoseMatrix = function () {
  7950. return this._poseMatrix;
  7951. };
  7952. AbstractMesh.prototype.disableEdgesRendering = function () {
  7953. if (this._edgesRenderer !== undefined) {
  7954. this._edgesRenderer.dispose();
  7955. this._edgesRenderer = undefined;
  7956. }
  7957. };
  7958. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7959. if (epsilon === void 0) { epsilon = 0.95; }
  7960. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7961. this.disableEdgesRendering();
  7962. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7963. };
  7964. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7965. get: function () {
  7966. return false;
  7967. },
  7968. enumerable: true,
  7969. configurable: true
  7970. });
  7971. AbstractMesh.prototype.getLOD = function (camera) {
  7972. return this;
  7973. };
  7974. AbstractMesh.prototype.getTotalVertices = function () {
  7975. return 0;
  7976. };
  7977. AbstractMesh.prototype.getIndices = function () {
  7978. return null;
  7979. };
  7980. AbstractMesh.prototype.getVerticesData = function (kind) {
  7981. return null;
  7982. };
  7983. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7984. return false;
  7985. };
  7986. AbstractMesh.prototype.getBoundingInfo = function () {
  7987. if (this._masterMesh) {
  7988. return this._masterMesh.getBoundingInfo();
  7989. }
  7990. if (!this._boundingInfo) {
  7991. this._updateBoundingInfo();
  7992. }
  7993. return this._boundingInfo;
  7994. };
  7995. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7996. get: function () {
  7997. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7998. },
  7999. enumerable: true,
  8000. configurable: true
  8001. });
  8002. AbstractMesh.prototype._preActivate = function () {
  8003. };
  8004. AbstractMesh.prototype._activate = function (renderId) {
  8005. this._renderId = renderId;
  8006. };
  8007. AbstractMesh.prototype.getWorldMatrix = function () {
  8008. if (this._masterMesh) {
  8009. return this._masterMesh.getWorldMatrix();
  8010. }
  8011. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8012. this.computeWorldMatrix();
  8013. }
  8014. return this._worldMatrix;
  8015. };
  8016. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8017. get: function () {
  8018. return this._worldMatrix;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8024. get: function () {
  8025. return this._absolutePosition;
  8026. },
  8027. enumerable: true,
  8028. configurable: true
  8029. });
  8030. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8031. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8032. this.computeWorldMatrix(true);
  8033. this._isWorldMatrixFrozen = true;
  8034. };
  8035. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8036. this._isWorldMatrixFrozen = false;
  8037. this.computeWorldMatrix(true);
  8038. };
  8039. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8040. get: function () {
  8041. return this._isWorldMatrixFrozen;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8047. axis.normalize();
  8048. if (!this.rotationQuaternion) {
  8049. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8050. this.rotation = BABYLON.Vector3.Zero();
  8051. }
  8052. var rotationQuaternion;
  8053. if (!space || space === BABYLON.Space.LOCAL) {
  8054. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8055. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8056. }
  8057. else {
  8058. if (this.parent) {
  8059. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8060. invertParentWorldMatrix.invert();
  8061. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8062. }
  8063. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8064. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8065. }
  8066. };
  8067. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8068. var displacementVector = axis.scale(distance);
  8069. if (!space || space === BABYLON.Space.LOCAL) {
  8070. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8071. this.setPositionWithLocalVector(tempV3);
  8072. }
  8073. else {
  8074. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8075. }
  8076. };
  8077. AbstractMesh.prototype.getAbsolutePosition = function () {
  8078. this.computeWorldMatrix();
  8079. return this._absolutePosition;
  8080. };
  8081. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8082. if (!absolutePosition) {
  8083. return;
  8084. }
  8085. var absolutePositionX;
  8086. var absolutePositionY;
  8087. var absolutePositionZ;
  8088. if (absolutePosition.x === undefined) {
  8089. if (arguments.length < 3) {
  8090. return;
  8091. }
  8092. absolutePositionX = arguments[0];
  8093. absolutePositionY = arguments[1];
  8094. absolutePositionZ = arguments[2];
  8095. }
  8096. else {
  8097. absolutePositionX = absolutePosition.x;
  8098. absolutePositionY = absolutePosition.y;
  8099. absolutePositionZ = absolutePosition.z;
  8100. }
  8101. if (this.parent) {
  8102. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8103. invertParentWorldMatrix.invert();
  8104. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8105. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8106. }
  8107. else {
  8108. this.position.x = absolutePositionX;
  8109. this.position.y = absolutePositionY;
  8110. this.position.z = absolutePositionZ;
  8111. }
  8112. };
  8113. // ================================== Point of View Movement =================================
  8114. /**
  8115. * Perform relative position change from the point of view of behind the front of the mesh.
  8116. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8117. * Supports definition of mesh facing forward or backward.
  8118. * @param {number} amountRight
  8119. * @param {number} amountUp
  8120. * @param {number} amountForward
  8121. */
  8122. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8123. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8124. };
  8125. /**
  8126. * Calculate relative position change from the point of view of behind the front of the mesh.
  8127. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8128. * Supports definition of mesh facing forward or backward.
  8129. * @param {number} amountRight
  8130. * @param {number} amountUp
  8131. * @param {number} amountForward
  8132. */
  8133. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8134. var rotMatrix = new BABYLON.Matrix();
  8135. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8136. rotQuaternion.toRotationMatrix(rotMatrix);
  8137. var translationDelta = BABYLON.Vector3.Zero();
  8138. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8140. return translationDelta;
  8141. };
  8142. // ================================== Point of View Rotation =================================
  8143. /**
  8144. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8145. * Supports definition of mesh facing forward or backward.
  8146. * @param {number} flipBack
  8147. * @param {number} twirlClockwise
  8148. * @param {number} tiltRight
  8149. */
  8150. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8151. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8152. };
  8153. /**
  8154. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8155. * Supports definition of mesh facing forward or backward.
  8156. * @param {number} flipBack
  8157. * @param {number} twirlClockwise
  8158. * @param {number} tiltRight
  8159. */
  8160. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8161. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8162. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8163. };
  8164. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8165. this._pivotMatrix = matrix;
  8166. this._cache.pivotMatrixUpdated = true;
  8167. };
  8168. AbstractMesh.prototype.getPivotMatrix = function () {
  8169. return this._pivotMatrix;
  8170. };
  8171. AbstractMesh.prototype._isSynchronized = function () {
  8172. if (this._isDirty) {
  8173. return false;
  8174. }
  8175. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8176. return false;
  8177. if (this._cache.pivotMatrixUpdated) {
  8178. return false;
  8179. }
  8180. if (this.infiniteDistance) {
  8181. return false;
  8182. }
  8183. if (!this._cache.position.equals(this.position))
  8184. return false;
  8185. if (this.rotationQuaternion) {
  8186. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8187. return false;
  8188. }
  8189. else {
  8190. if (!this._cache.rotation.equals(this.rotation))
  8191. return false;
  8192. }
  8193. if (!this._cache.scaling.equals(this.scaling))
  8194. return false;
  8195. return true;
  8196. };
  8197. AbstractMesh.prototype._initCache = function () {
  8198. _super.prototype._initCache.call(this);
  8199. this._cache.localMatrixUpdated = false;
  8200. this._cache.position = BABYLON.Vector3.Zero();
  8201. this._cache.scaling = BABYLON.Vector3.Zero();
  8202. this._cache.rotation = BABYLON.Vector3.Zero();
  8203. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8204. this._cache.billboardMode = -1;
  8205. };
  8206. AbstractMesh.prototype.markAsDirty = function (property) {
  8207. if (property === "rotation") {
  8208. this.rotationQuaternion = null;
  8209. }
  8210. this._currentRenderId = Number.MAX_VALUE;
  8211. this._isDirty = true;
  8212. };
  8213. AbstractMesh.prototype._updateBoundingInfo = function () {
  8214. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8215. this._boundingInfo.update(this.worldMatrixFromCache);
  8216. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8217. };
  8218. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8219. if (!this.subMeshes) {
  8220. return;
  8221. }
  8222. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8223. var subMesh = this.subMeshes[subIndex];
  8224. if (!subMesh.IsGlobal) {
  8225. subMesh.updateBoundingInfo(matrix);
  8226. }
  8227. }
  8228. };
  8229. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8230. if (this._isWorldMatrixFrozen) {
  8231. return this._worldMatrix;
  8232. }
  8233. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8234. this._currentRenderId = this.getScene().getRenderId();
  8235. return this._worldMatrix;
  8236. }
  8237. this._cache.position.copyFrom(this.position);
  8238. this._cache.scaling.copyFrom(this.scaling);
  8239. this._cache.pivotMatrixUpdated = false;
  8240. this._cache.billboardMode = this.billboardMode;
  8241. this._currentRenderId = this.getScene().getRenderId();
  8242. this._isDirty = false;
  8243. // Scaling
  8244. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8245. // Rotation
  8246. if (this.rotationQuaternion) {
  8247. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8248. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8249. }
  8250. else {
  8251. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8252. this._cache.rotation.copyFrom(this.rotation);
  8253. }
  8254. // Translation
  8255. if (this.infiniteDistance && !this.parent) {
  8256. var camera = this.getScene().activeCamera;
  8257. if (camera) {
  8258. var cameraWorldMatrix = camera.getWorldMatrix();
  8259. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8260. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8261. }
  8262. }
  8263. else {
  8264. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8265. }
  8266. // Composing transformations
  8267. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8268. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8269. // Billboarding
  8270. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8271. var localPosition = this.position.clone();
  8272. var zero = this.getScene().activeCamera.globalPosition.clone();
  8273. if (this.parent && this.parent.position) {
  8274. localPosition.addInPlace(this.parent.position);
  8275. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8276. }
  8277. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8278. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8279. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8280. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8281. zero.y = localPosition.y + 0.001;
  8282. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8283. zero.z = localPosition.z + 0.001;
  8284. }
  8285. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8286. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8287. BABYLON.Tmp.Matrix[3].invert();
  8288. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8289. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8290. }
  8291. // Local world
  8292. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8293. // Parent
  8294. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8295. this._markSyncedWithParent();
  8296. if (this._meshToBoneReferal) {
  8297. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8298. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8299. }
  8300. else {
  8301. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8302. }
  8303. }
  8304. else {
  8305. this._worldMatrix.copyFrom(this._localWorld);
  8306. }
  8307. // Bounding info
  8308. this._updateBoundingInfo();
  8309. // Absolute position
  8310. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8311. // Callbacks
  8312. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8313. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8314. }
  8315. if (!this._poseMatrix) {
  8316. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8317. }
  8318. return this._worldMatrix;
  8319. };
  8320. /**
  8321. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8322. * @param func: callback function to add
  8323. */
  8324. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8325. this._onAfterWorldMatrixUpdate.push(func);
  8326. };
  8327. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8328. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8329. if (index > -1) {
  8330. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8331. }
  8332. };
  8333. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8334. this.computeWorldMatrix();
  8335. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8336. };
  8337. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8338. this.computeWorldMatrix();
  8339. var invLocalWorldMatrix = this._localWorld.clone();
  8340. invLocalWorldMatrix.invert();
  8341. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8342. };
  8343. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8344. this.computeWorldMatrix(true);
  8345. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8346. };
  8347. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8348. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8349. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8350. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8351. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8352. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8353. /// <returns>Mesh oriented towards targetMesh</returns>
  8354. yawCor = yawCor || 0; // default to zero if undefined
  8355. pitchCor = pitchCor || 0;
  8356. rollCor = rollCor || 0;
  8357. var dv = targetPoint.subtract(this.position);
  8358. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8359. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8360. var pitch = Math.atan2(dv.y, len);
  8361. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8362. };
  8363. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8364. this._meshToBoneReferal = affectedMesh;
  8365. this.parent = bone;
  8366. if (bone.getWorldMatrix().determinant() < 0) {
  8367. this.scalingDeterminant *= -1;
  8368. }
  8369. };
  8370. AbstractMesh.prototype.detachFromBone = function () {
  8371. if (this.parent.getWorldMatrix().determinant() < 0) {
  8372. this.scalingDeterminant *= -1;
  8373. }
  8374. this._meshToBoneReferal = null;
  8375. this.parent = null;
  8376. };
  8377. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8378. return this._boundingInfo.isInFrustum(frustumPlanes);
  8379. };
  8380. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8381. if (!camera) {
  8382. camera = this.getScene().activeCamera;
  8383. }
  8384. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8385. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8386. return false;
  8387. }
  8388. return true;
  8389. };
  8390. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8391. if (!this._boundingInfo || !mesh._boundingInfo) {
  8392. return false;
  8393. }
  8394. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8395. };
  8396. AbstractMesh.prototype.intersectsPoint = function (point) {
  8397. if (!this._boundingInfo) {
  8398. return false;
  8399. }
  8400. return this._boundingInfo.intersectsPoint(point);
  8401. };
  8402. // Physics
  8403. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8404. var physicsEngine = this.getScene().getPhysicsEngine();
  8405. if (!physicsEngine) {
  8406. return null;
  8407. }
  8408. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8409. if (impostor.impostor) {
  8410. // Old API
  8411. options = impostor;
  8412. impostor = impostor.impostor;
  8413. }
  8414. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8415. physicsEngine._unregisterMesh(this);
  8416. return null;
  8417. }
  8418. if (!options) {
  8419. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8420. }
  8421. else {
  8422. if (!options.mass && options.mass !== 0)
  8423. options.mass = 0;
  8424. if (!options.friction && options.friction !== 0)
  8425. options.friction = 0.2;
  8426. if (!options.restitution && options.restitution !== 0)
  8427. options.restitution = 0.2;
  8428. }
  8429. this._physicImpostor = impostor;
  8430. this._physicsMass = options.mass;
  8431. this._physicsFriction = options.friction;
  8432. this._physicRestitution = options.restitution;
  8433. return physicsEngine._registerMesh(this, impostor, options);
  8434. };
  8435. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8436. if (!this._physicImpostor) {
  8437. return BABYLON.PhysicsEngine.NoImpostor;
  8438. }
  8439. return this._physicImpostor;
  8440. };
  8441. AbstractMesh.prototype.getPhysicsMass = function () {
  8442. if (!this._physicsMass) {
  8443. return 0;
  8444. }
  8445. return this._physicsMass;
  8446. };
  8447. AbstractMesh.prototype.getPhysicsFriction = function () {
  8448. if (!this._physicsFriction) {
  8449. return 0;
  8450. }
  8451. return this._physicsFriction;
  8452. };
  8453. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8454. if (!this._physicRestitution) {
  8455. return 0;
  8456. }
  8457. return this._physicRestitution;
  8458. };
  8459. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8460. if (!camera) {
  8461. camera = this.getScene().activeCamera;
  8462. }
  8463. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8464. };
  8465. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8466. if (!camera) {
  8467. camera = this.getScene().activeCamera;
  8468. }
  8469. return this.absolutePosition.subtract(camera.position).length();
  8470. };
  8471. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8472. if (!this._physicImpostor) {
  8473. return;
  8474. }
  8475. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8476. };
  8477. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8478. if (!this._physicImpostor) {
  8479. return;
  8480. }
  8481. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8482. };
  8483. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8484. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8485. this.updatePhysicsBody();
  8486. };
  8487. AbstractMesh.prototype.updatePhysicsBody = function () {
  8488. if (!this._physicImpostor) {
  8489. return;
  8490. }
  8491. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8492. };
  8493. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8494. // Collisions
  8495. get: function () {
  8496. return this._checkCollisions;
  8497. },
  8498. set: function (collisionEnabled) {
  8499. this._checkCollisions = collisionEnabled;
  8500. if (this.getScene().workerCollisions) {
  8501. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8502. }
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8508. var globalPosition = this.getAbsolutePosition();
  8509. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8510. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8511. this._collider.radius = this.ellipsoid;
  8512. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8513. };
  8514. // Submeshes octree
  8515. /**
  8516. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8517. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8518. */
  8519. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8520. if (maxCapacity === void 0) { maxCapacity = 64; }
  8521. if (maxDepth === void 0) { maxDepth = 2; }
  8522. if (!this._submeshesOctree) {
  8523. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8524. }
  8525. this.computeWorldMatrix(true);
  8526. // Update octree
  8527. var bbox = this.getBoundingInfo().boundingBox;
  8528. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8529. return this._submeshesOctree;
  8530. };
  8531. // Collisions
  8532. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8533. this._generatePointsArray();
  8534. // Transformation
  8535. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8536. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8537. subMesh._lastColliderWorldVertices = [];
  8538. subMesh._trianglePlanes = [];
  8539. var start = subMesh.verticesStart;
  8540. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8541. for (var i = start; i < end; i++) {
  8542. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8543. }
  8544. }
  8545. // Collide
  8546. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8547. if (collider.collisionFound) {
  8548. collider.collidedMesh = this;
  8549. }
  8550. };
  8551. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8552. var subMeshes;
  8553. var len;
  8554. // Octrees
  8555. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8556. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8557. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8558. len = intersections.length;
  8559. subMeshes = intersections.data;
  8560. }
  8561. else {
  8562. subMeshes = this.subMeshes;
  8563. len = subMeshes.length;
  8564. }
  8565. for (var index = 0; index < len; index++) {
  8566. var subMesh = subMeshes[index];
  8567. // Bounding test
  8568. if (len > 1 && !subMesh._checkCollision(collider))
  8569. continue;
  8570. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8571. }
  8572. };
  8573. AbstractMesh.prototype._checkCollision = function (collider) {
  8574. // Bounding box test
  8575. if (!this._boundingInfo._checkCollision(collider))
  8576. return;
  8577. // Transformation matrix
  8578. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8579. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8580. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8581. };
  8582. // Picking
  8583. AbstractMesh.prototype._generatePointsArray = function () {
  8584. return false;
  8585. };
  8586. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8587. var pickingInfo = new BABYLON.PickingInfo();
  8588. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8589. return pickingInfo;
  8590. }
  8591. if (!this._generatePointsArray()) {
  8592. return pickingInfo;
  8593. }
  8594. var intersectInfo = null;
  8595. // Octrees
  8596. var subMeshes;
  8597. var len;
  8598. if (this._submeshesOctree && this.useOctreeForPicking) {
  8599. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8600. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8601. len = intersections.length;
  8602. subMeshes = intersections.data;
  8603. }
  8604. else {
  8605. subMeshes = this.subMeshes;
  8606. len = subMeshes.length;
  8607. }
  8608. for (var index = 0; index < len; index++) {
  8609. var subMesh = subMeshes[index];
  8610. // Bounding test
  8611. if (len > 1 && !subMesh.canIntersects(ray))
  8612. continue;
  8613. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8614. if (currentIntersectInfo) {
  8615. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8616. intersectInfo = currentIntersectInfo;
  8617. intersectInfo.subMeshId = index;
  8618. if (fastCheck) {
  8619. break;
  8620. }
  8621. }
  8622. }
  8623. }
  8624. if (intersectInfo) {
  8625. // Get picked point
  8626. var world = this.getWorldMatrix();
  8627. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8628. var direction = ray.direction.clone();
  8629. direction = direction.scale(intersectInfo.distance);
  8630. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8631. var pickedPoint = worldOrigin.add(worldDirection);
  8632. // Return result
  8633. pickingInfo.hit = true;
  8634. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8635. pickingInfo.pickedPoint = pickedPoint;
  8636. pickingInfo.pickedMesh = this;
  8637. pickingInfo.bu = intersectInfo.bu;
  8638. pickingInfo.bv = intersectInfo.bv;
  8639. pickingInfo.faceId = intersectInfo.faceId;
  8640. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8641. return pickingInfo;
  8642. }
  8643. return pickingInfo;
  8644. };
  8645. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8646. return null;
  8647. };
  8648. AbstractMesh.prototype.releaseSubMeshes = function () {
  8649. if (this.subMeshes) {
  8650. while (this.subMeshes.length) {
  8651. this.subMeshes[0].dispose();
  8652. }
  8653. }
  8654. else {
  8655. this.subMeshes = new Array();
  8656. }
  8657. };
  8658. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8659. var index;
  8660. // Skeleton
  8661. this.skeleton = null;
  8662. // Animations
  8663. this.getScene().stopAnimation(this);
  8664. // Physics
  8665. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8666. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8667. }
  8668. // Intersections in progress
  8669. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8670. var other = this._intersectionsInProgress[index];
  8671. var pos = other._intersectionsInProgress.indexOf(this);
  8672. other._intersectionsInProgress.splice(pos, 1);
  8673. }
  8674. this._intersectionsInProgress = [];
  8675. // Edges
  8676. if (this._edgesRenderer) {
  8677. this._edgesRenderer.dispose();
  8678. this._edgesRenderer = null;
  8679. }
  8680. // SubMeshes
  8681. this.releaseSubMeshes();
  8682. // Remove from scene
  8683. this.getScene().removeMesh(this);
  8684. if (!doNotRecurse) {
  8685. // Particles
  8686. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8687. if (this.getScene().particleSystems[index].emitter === this) {
  8688. this.getScene().particleSystems[index].dispose();
  8689. index--;
  8690. }
  8691. }
  8692. // Children
  8693. var objects = this.getScene().meshes.slice(0);
  8694. for (index = 0; index < objects.length; index++) {
  8695. if (objects[index].parent === this) {
  8696. objects[index].dispose();
  8697. }
  8698. }
  8699. }
  8700. else {
  8701. for (index = 0; index < this.getScene().meshes.length; index++) {
  8702. var obj = this.getScene().meshes[index];
  8703. if (obj.parent === this) {
  8704. obj.parent = null;
  8705. obj.computeWorldMatrix(true);
  8706. }
  8707. }
  8708. }
  8709. this._onAfterWorldMatrixUpdate = [];
  8710. this._isDisposed = true;
  8711. // Callback
  8712. if (this.onDispose) {
  8713. this.onDispose();
  8714. }
  8715. };
  8716. // Statics
  8717. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8718. AbstractMesh._BILLBOARDMODE_X = 1;
  8719. AbstractMesh._BILLBOARDMODE_Y = 2;
  8720. AbstractMesh._BILLBOARDMODE_Z = 4;
  8721. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8722. return AbstractMesh;
  8723. })(BABYLON.Node);
  8724. BABYLON.AbstractMesh = AbstractMesh;
  8725. })(BABYLON || (BABYLON = {}));
  8726. var BABYLON;
  8727. (function (BABYLON) {
  8728. var Light = (function (_super) {
  8729. __extends(Light, _super);
  8730. function Light(name, scene) {
  8731. _super.call(this, name, scene);
  8732. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8733. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8734. this.intensity = 1.0;
  8735. this.range = Number.MAX_VALUE;
  8736. this.includeOnlyWithLayerMask = 0;
  8737. this.includedOnlyMeshes = new Array();
  8738. this.excludedMeshes = new Array();
  8739. this.excludeWithLayerMask = 0;
  8740. this._excludedMeshesIds = new Array();
  8741. this._includedOnlyMeshesIds = new Array();
  8742. scene.addLight(this);
  8743. }
  8744. Light.prototype.getShadowGenerator = function () {
  8745. return this._shadowGenerator;
  8746. };
  8747. Light.prototype.getAbsolutePosition = function () {
  8748. return BABYLON.Vector3.Zero();
  8749. };
  8750. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8751. };
  8752. Light.prototype._getWorldMatrix = function () {
  8753. return BABYLON.Matrix.Identity();
  8754. };
  8755. Light.prototype.canAffectMesh = function (mesh) {
  8756. if (!mesh) {
  8757. return true;
  8758. }
  8759. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8760. return false;
  8761. }
  8762. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8763. return false;
  8764. }
  8765. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8766. return false;
  8767. }
  8768. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8769. return false;
  8770. }
  8771. return true;
  8772. };
  8773. Light.prototype.getWorldMatrix = function () {
  8774. this._currentRenderId = this.getScene().getRenderId();
  8775. var worldMatrix = this._getWorldMatrix();
  8776. if (this.parent && this.parent.getWorldMatrix) {
  8777. if (!this._parentedWorldMatrix) {
  8778. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8779. }
  8780. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8781. this._markSyncedWithParent();
  8782. return this._parentedWorldMatrix;
  8783. }
  8784. return worldMatrix;
  8785. };
  8786. Light.prototype.dispose = function () {
  8787. if (this._shadowGenerator) {
  8788. this._shadowGenerator.dispose();
  8789. this._shadowGenerator = null;
  8790. }
  8791. // Animations
  8792. this.getScene().stopAnimation(this);
  8793. // Remove from scene
  8794. this.getScene().removeLight(this);
  8795. };
  8796. Light.prototype.serialize = function () {
  8797. var serializationObject = {};
  8798. serializationObject.name = this.name;
  8799. serializationObject.id = this.id;
  8800. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8801. if (this.intensity) {
  8802. serializationObject.intensity = this.intensity;
  8803. }
  8804. // Parent
  8805. if (this.parent) {
  8806. serializationObject.parentId = this.parent.id;
  8807. }
  8808. serializationObject.range = this.range;
  8809. serializationObject.diffuse = this.diffuse.asArray();
  8810. serializationObject.specular = this.specular.asArray();
  8811. return serializationObject;
  8812. };
  8813. Light.Parse = function (parsedLight, scene) {
  8814. var light;
  8815. switch (parsedLight.type) {
  8816. case 0:
  8817. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8818. break;
  8819. case 1:
  8820. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8821. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8822. break;
  8823. case 2:
  8824. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8825. break;
  8826. case 3:
  8827. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8828. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8829. break;
  8830. }
  8831. light.id = parsedLight.id;
  8832. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8833. if (parsedLight.intensity !== undefined) {
  8834. light.intensity = parsedLight.intensity;
  8835. }
  8836. if (parsedLight.range) {
  8837. light.range = parsedLight.range;
  8838. }
  8839. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8840. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8841. if (parsedLight.excludedMeshesIds) {
  8842. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8843. }
  8844. // Parent
  8845. if (parsedLight.parentId) {
  8846. light._waitingParentId = parsedLight.parentId;
  8847. }
  8848. if (parsedLight.includedOnlyMeshesIds) {
  8849. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8850. }
  8851. // Animations
  8852. if (parsedLight.animations) {
  8853. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8854. var parsedAnimation = parsedLight.animations[animationIndex];
  8855. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8856. }
  8857. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8858. }
  8859. if (parsedLight.autoAnimate) {
  8860. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8861. }
  8862. return light;
  8863. };
  8864. return Light;
  8865. })(BABYLON.Node);
  8866. BABYLON.Light = Light;
  8867. })(BABYLON || (BABYLON = {}));
  8868. var BABYLON;
  8869. (function (BABYLON) {
  8870. var PointLight = (function (_super) {
  8871. __extends(PointLight, _super);
  8872. function PointLight(name, position, scene) {
  8873. _super.call(this, name, scene);
  8874. this.position = position;
  8875. }
  8876. PointLight.prototype.getAbsolutePosition = function () {
  8877. return this.transformedPosition ? this.transformedPosition : this.position;
  8878. };
  8879. PointLight.prototype.computeTransformedPosition = function () {
  8880. if (this.parent && this.parent.getWorldMatrix) {
  8881. if (!this.transformedPosition) {
  8882. this.transformedPosition = BABYLON.Vector3.Zero();
  8883. }
  8884. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8885. return true;
  8886. }
  8887. return false;
  8888. };
  8889. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8890. if (this.parent && this.parent.getWorldMatrix) {
  8891. this.computeTransformedPosition();
  8892. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8893. return;
  8894. }
  8895. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8896. };
  8897. PointLight.prototype.needCube = function () {
  8898. return true;
  8899. };
  8900. PointLight.prototype.supportsVSM = function () {
  8901. return false;
  8902. };
  8903. PointLight.prototype.needRefreshPerFrame = function () {
  8904. return false;
  8905. };
  8906. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8907. switch (faceIndex) {
  8908. case 0:
  8909. return new BABYLON.Vector3(1, 0, 0);
  8910. case 1:
  8911. return new BABYLON.Vector3(-1, 0, 0);
  8912. case 2:
  8913. return new BABYLON.Vector3(0, -1, 0);
  8914. case 3:
  8915. return new BABYLON.Vector3(0, 1, 0);
  8916. case 4:
  8917. return new BABYLON.Vector3(0, 0, 1);
  8918. case 5:
  8919. return new BABYLON.Vector3(0, 0, -1);
  8920. }
  8921. return BABYLON.Vector3.Zero();
  8922. };
  8923. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8924. var activeCamera = this.getScene().activeCamera;
  8925. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8926. };
  8927. PointLight.prototype._getWorldMatrix = function () {
  8928. if (!this._worldMatrix) {
  8929. this._worldMatrix = BABYLON.Matrix.Identity();
  8930. }
  8931. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8932. return this._worldMatrix;
  8933. };
  8934. PointLight.prototype.serialize = function () {
  8935. var serializationObject = _super.prototype.serialize.call(this);
  8936. serializationObject.type = 0;
  8937. serializationObject.position = this.position.asArray();
  8938. return serializationObject;
  8939. };
  8940. return PointLight;
  8941. })(BABYLON.Light);
  8942. BABYLON.PointLight = PointLight;
  8943. })(BABYLON || (BABYLON = {}));
  8944. var BABYLON;
  8945. (function (BABYLON) {
  8946. var SpotLight = (function (_super) {
  8947. __extends(SpotLight, _super);
  8948. function SpotLight(name, position, direction, angle, exponent, scene) {
  8949. _super.call(this, name, scene);
  8950. this.position = position;
  8951. this.direction = direction;
  8952. this.angle = angle;
  8953. this.exponent = exponent;
  8954. }
  8955. SpotLight.prototype.getAbsolutePosition = function () {
  8956. return this.transformedPosition ? this.transformedPosition : this.position;
  8957. };
  8958. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8959. var activeCamera = this.getScene().activeCamera;
  8960. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8961. };
  8962. SpotLight.prototype.needCube = function () {
  8963. return false;
  8964. };
  8965. SpotLight.prototype.supportsVSM = function () {
  8966. return true;
  8967. };
  8968. SpotLight.prototype.needRefreshPerFrame = function () {
  8969. return false;
  8970. };
  8971. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8972. return this.direction;
  8973. };
  8974. SpotLight.prototype.setDirectionToTarget = function (target) {
  8975. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8976. return this.direction;
  8977. };
  8978. SpotLight.prototype.computeTransformedPosition = function () {
  8979. if (this.parent && this.parent.getWorldMatrix) {
  8980. if (!this.transformedPosition) {
  8981. this.transformedPosition = BABYLON.Vector3.Zero();
  8982. }
  8983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8984. return true;
  8985. }
  8986. return false;
  8987. };
  8988. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8989. var normalizeDirection;
  8990. if (this.parent && this.parent.getWorldMatrix) {
  8991. if (!this._transformedDirection) {
  8992. this._transformedDirection = BABYLON.Vector3.Zero();
  8993. }
  8994. this.computeTransformedPosition();
  8995. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8996. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8997. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8998. }
  8999. else {
  9000. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9001. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9002. }
  9003. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9004. };
  9005. SpotLight.prototype._getWorldMatrix = function () {
  9006. if (!this._worldMatrix) {
  9007. this._worldMatrix = BABYLON.Matrix.Identity();
  9008. }
  9009. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9010. return this._worldMatrix;
  9011. };
  9012. SpotLight.prototype.serialize = function () {
  9013. var serializationObject = _super.prototype.serialize.call(this);
  9014. serializationObject.type = 2;
  9015. serializationObject.position = this.position.asArray();
  9016. serializationObject.direction = this.position.asArray();
  9017. serializationObject.angle = this.angle;
  9018. serializationObject.exponent = this.exponent;
  9019. return serializationObject;
  9020. };
  9021. return SpotLight;
  9022. })(BABYLON.Light);
  9023. BABYLON.SpotLight = SpotLight;
  9024. })(BABYLON || (BABYLON = {}));
  9025. var BABYLON;
  9026. (function (BABYLON) {
  9027. var HemisphericLight = (function (_super) {
  9028. __extends(HemisphericLight, _super);
  9029. function HemisphericLight(name, direction, scene) {
  9030. _super.call(this, name, scene);
  9031. this.direction = direction;
  9032. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9033. }
  9034. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9035. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9036. return this.direction;
  9037. };
  9038. HemisphericLight.prototype.getShadowGenerator = function () {
  9039. return null;
  9040. };
  9041. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9042. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9043. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9044. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9045. };
  9046. HemisphericLight.prototype._getWorldMatrix = function () {
  9047. if (!this._worldMatrix) {
  9048. this._worldMatrix = BABYLON.Matrix.Identity();
  9049. }
  9050. return this._worldMatrix;
  9051. };
  9052. HemisphericLight.prototype.serialize = function () {
  9053. var serializationObject = _super.prototype.serialize.call(this);
  9054. serializationObject.type = 3;
  9055. serializationObject.direction = this.direction.asArray();
  9056. serializationObject.groundColor = this.groundColor.asArray();
  9057. return serializationObject;
  9058. };
  9059. return HemisphericLight;
  9060. })(BABYLON.Light);
  9061. BABYLON.HemisphericLight = HemisphericLight;
  9062. })(BABYLON || (BABYLON = {}));
  9063. var BABYLON;
  9064. (function (BABYLON) {
  9065. var DirectionalLight = (function (_super) {
  9066. __extends(DirectionalLight, _super);
  9067. function DirectionalLight(name, direction, scene) {
  9068. _super.call(this, name, scene);
  9069. this.direction = direction;
  9070. this.shadowOrthoScale = 0.5;
  9071. this.autoUpdateExtends = true;
  9072. // Cache
  9073. this._orthoLeft = Number.MAX_VALUE;
  9074. this._orthoRight = Number.MIN_VALUE;
  9075. this._orthoTop = Number.MIN_VALUE;
  9076. this._orthoBottom = Number.MAX_VALUE;
  9077. this.position = direction.scale(-1);
  9078. }
  9079. DirectionalLight.prototype.getAbsolutePosition = function () {
  9080. return this.transformedPosition ? this.transformedPosition : this.position;
  9081. };
  9082. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9083. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9084. return this.direction;
  9085. };
  9086. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9087. var activeCamera = this.getScene().activeCamera;
  9088. // Check extends
  9089. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9090. var tempVector3 = BABYLON.Vector3.Zero();
  9091. this._orthoLeft = Number.MAX_VALUE;
  9092. this._orthoRight = Number.MIN_VALUE;
  9093. this._orthoTop = Number.MIN_VALUE;
  9094. this._orthoBottom = Number.MAX_VALUE;
  9095. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9096. var mesh = renderList[meshIndex];
  9097. if (!mesh) {
  9098. continue;
  9099. }
  9100. var boundingInfo = mesh.getBoundingInfo();
  9101. if (!boundingInfo) {
  9102. continue;
  9103. }
  9104. var boundingBox = boundingInfo.boundingBox;
  9105. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9106. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9107. if (tempVector3.x < this._orthoLeft)
  9108. this._orthoLeft = tempVector3.x;
  9109. if (tempVector3.y < this._orthoBottom)
  9110. this._orthoBottom = tempVector3.y;
  9111. if (tempVector3.x > this._orthoRight)
  9112. this._orthoRight = tempVector3.x;
  9113. if (tempVector3.y > this._orthoTop)
  9114. this._orthoTop = tempVector3.y;
  9115. }
  9116. }
  9117. }
  9118. var xOffset = this._orthoRight - this._orthoLeft;
  9119. var yOffset = this._orthoTop - this._orthoBottom;
  9120. 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);
  9121. };
  9122. DirectionalLight.prototype.supportsVSM = function () {
  9123. return true;
  9124. };
  9125. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9126. return true;
  9127. };
  9128. DirectionalLight.prototype.needCube = function () {
  9129. return false;
  9130. };
  9131. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9132. return this.direction;
  9133. };
  9134. DirectionalLight.prototype.computeTransformedPosition = function () {
  9135. if (this.parent && this.parent.getWorldMatrix) {
  9136. if (!this.transformedPosition) {
  9137. this.transformedPosition = BABYLON.Vector3.Zero();
  9138. }
  9139. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9140. return true;
  9141. }
  9142. return false;
  9143. };
  9144. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9145. if (this.parent && this.parent.getWorldMatrix) {
  9146. if (!this._transformedDirection) {
  9147. this._transformedDirection = BABYLON.Vector3.Zero();
  9148. }
  9149. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9150. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9151. return;
  9152. }
  9153. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9154. };
  9155. DirectionalLight.prototype._getWorldMatrix = function () {
  9156. if (!this._worldMatrix) {
  9157. this._worldMatrix = BABYLON.Matrix.Identity();
  9158. }
  9159. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9160. return this._worldMatrix;
  9161. };
  9162. DirectionalLight.prototype.serialize = function () {
  9163. var serializationObject = _super.prototype.serialize.call(this);
  9164. serializationObject.type = 1;
  9165. serializationObject.position = this.position.asArray();
  9166. serializationObject.direction = this.direction.asArray();
  9167. return serializationObject;
  9168. };
  9169. return DirectionalLight;
  9170. })(BABYLON.Light);
  9171. BABYLON.DirectionalLight = DirectionalLight;
  9172. })(BABYLON || (BABYLON = {}));
  9173. var BABYLON;
  9174. (function (BABYLON) {
  9175. var ShadowGenerator = (function () {
  9176. function ShadowGenerator(mapSize, light) {
  9177. var _this = this;
  9178. // Members
  9179. this._filter = ShadowGenerator.FILTER_NONE;
  9180. this.blurScale = 2;
  9181. this._blurBoxOffset = 0;
  9182. this._bias = 0.00005;
  9183. this._lightDirection = BABYLON.Vector3.Zero();
  9184. this.forceBackFacesOnly = false;
  9185. this._darkness = 0;
  9186. this._transparencyShadow = false;
  9187. this._viewMatrix = BABYLON.Matrix.Zero();
  9188. this._projectionMatrix = BABYLON.Matrix.Zero();
  9189. this._transformMatrix = BABYLON.Matrix.Zero();
  9190. this._worldViewProjection = BABYLON.Matrix.Zero();
  9191. this._currentFaceIndex = 0;
  9192. this._currentFaceIndexCache = 0;
  9193. this._light = light;
  9194. this._scene = light.getScene();
  9195. this._mapSize = mapSize;
  9196. light._shadowGenerator = this;
  9197. // Render target
  9198. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9199. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9200. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9201. this._shadowMap.anisotropicFilteringLevel = 1;
  9202. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9203. this._shadowMap.renderParticles = false;
  9204. this._shadowMap.onBeforeRender = function (faceIndex) {
  9205. _this._currentFaceIndex = faceIndex;
  9206. };
  9207. this._shadowMap.onAfterUnbind = function () {
  9208. if (!_this.useBlurVarianceShadowMap) {
  9209. return;
  9210. }
  9211. if (!_this._shadowMap2) {
  9212. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9213. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9214. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9215. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9216. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9217. _this._downSamplePostprocess.onApply = function (effect) {
  9218. effect.setTexture("textureSampler", _this._shadowMap);
  9219. };
  9220. _this.blurBoxOffset = 1;
  9221. }
  9222. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9223. };
  9224. // Custom render function
  9225. var renderSubMesh = function (subMesh) {
  9226. var mesh = subMesh.getRenderingMesh();
  9227. var scene = _this._scene;
  9228. var engine = scene.getEngine();
  9229. // Culling
  9230. engine.setState(subMesh.getMaterial().backFaceCulling);
  9231. // Managing instances
  9232. var batch = mesh._getInstancesRenderList(subMesh._id);
  9233. if (batch.mustReturn) {
  9234. return;
  9235. }
  9236. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9237. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9238. engine.enableEffect(_this._effect);
  9239. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9240. var material = subMesh.getMaterial();
  9241. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9242. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9243. if (_this.getLight().needCube()) {
  9244. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9245. }
  9246. // Alpha test
  9247. if (material && material.needAlphaTesting()) {
  9248. var alphaTexture = material.getAlphaTestTexture();
  9249. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9250. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9251. }
  9252. // Bones
  9253. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9254. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9255. }
  9256. if (_this.forceBackFacesOnly) {
  9257. engine.setState(true, 0, false, true);
  9258. }
  9259. // Draw
  9260. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9261. if (_this.forceBackFacesOnly) {
  9262. engine.setState(true, 0, false, false);
  9263. }
  9264. }
  9265. else {
  9266. // Need to reset refresh rate of the shadowMap
  9267. _this._shadowMap.resetRefreshCounter();
  9268. }
  9269. };
  9270. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9271. var index;
  9272. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9273. renderSubMesh(opaqueSubMeshes.data[index]);
  9274. }
  9275. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9276. renderSubMesh(alphaTestSubMeshes.data[index]);
  9277. }
  9278. if (_this._transparencyShadow) {
  9279. for (index = 0; index < transparentSubMeshes.length; index++) {
  9280. renderSubMesh(transparentSubMeshes.data[index]);
  9281. }
  9282. }
  9283. };
  9284. this._shadowMap.onClear = function (engine) {
  9285. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9286. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9287. }
  9288. else {
  9289. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9290. }
  9291. };
  9292. }
  9293. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9294. // Static
  9295. get: function () {
  9296. return ShadowGenerator._FILTER_NONE;
  9297. },
  9298. enumerable: true,
  9299. configurable: true
  9300. });
  9301. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9302. get: function () {
  9303. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9309. get: function () {
  9310. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9316. get: function () {
  9317. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9318. },
  9319. enumerable: true,
  9320. configurable: true
  9321. });
  9322. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9323. get: function () {
  9324. return this._bias;
  9325. },
  9326. set: function (bias) {
  9327. this._bias = bias;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9333. get: function () {
  9334. return this._blurBoxOffset;
  9335. },
  9336. set: function (value) {
  9337. var _this = this;
  9338. if (this._blurBoxOffset === value) {
  9339. return;
  9340. }
  9341. this._blurBoxOffset = value;
  9342. if (this._boxBlurPostprocess) {
  9343. this._boxBlurPostprocess.dispose();
  9344. }
  9345. 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);
  9346. this._boxBlurPostprocess.onApply = function (effect) {
  9347. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9348. };
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9354. get: function () {
  9355. return this._filter;
  9356. },
  9357. set: function (value) {
  9358. if (this._filter === value) {
  9359. return;
  9360. }
  9361. this._filter = value;
  9362. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9363. this._shadowMap.anisotropicFilteringLevel = 16;
  9364. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9365. }
  9366. else {
  9367. this._shadowMap.anisotropicFilteringLevel = 1;
  9368. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9369. }
  9370. },
  9371. enumerable: true,
  9372. configurable: true
  9373. });
  9374. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9375. get: function () {
  9376. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9377. },
  9378. set: function (value) {
  9379. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9385. get: function () {
  9386. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9387. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9388. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9389. },
  9390. set: function (value) {
  9391. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9397. get: function () {
  9398. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9399. },
  9400. set: function (value) {
  9401. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9407. var defines = [];
  9408. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9409. defines.push("#define VSM");
  9410. }
  9411. if (this.getLight().needCube()) {
  9412. defines.push("#define CUBEMAP");
  9413. }
  9414. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9415. var mesh = subMesh.getMesh();
  9416. var material = subMesh.getMaterial();
  9417. // Alpha test
  9418. if (material && material.needAlphaTesting()) {
  9419. defines.push("#define ALPHATEST");
  9420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9421. attribs.push(BABYLON.VertexBuffer.UVKind);
  9422. defines.push("#define UV1");
  9423. }
  9424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9425. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9426. defines.push("#define UV2");
  9427. }
  9428. }
  9429. // Bones
  9430. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9431. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9432. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9433. if (mesh.numBoneInfluencers > 4) {
  9434. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9435. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9436. }
  9437. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9438. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9439. }
  9440. else {
  9441. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9442. }
  9443. // Instances
  9444. if (useInstances) {
  9445. defines.push("#define INSTANCES");
  9446. attribs.push("world0");
  9447. attribs.push("world1");
  9448. attribs.push("world2");
  9449. attribs.push("world3");
  9450. }
  9451. // Get correct effect
  9452. var join = defines.join("\n");
  9453. if (this._cachedDefines !== join) {
  9454. this._cachedDefines = join;
  9455. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9456. }
  9457. return this._effect.isReady();
  9458. };
  9459. ShadowGenerator.prototype.getShadowMap = function () {
  9460. return this._shadowMap;
  9461. };
  9462. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9463. if (this._shadowMap2) {
  9464. return this._shadowMap2;
  9465. }
  9466. return this._shadowMap;
  9467. };
  9468. ShadowGenerator.prototype.getLight = function () {
  9469. return this._light;
  9470. };
  9471. // Methods
  9472. ShadowGenerator.prototype.getTransformMatrix = function () {
  9473. var scene = this._scene;
  9474. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9475. return this._transformMatrix;
  9476. }
  9477. this._currentRenderID = scene.getRenderId();
  9478. this._currentFaceIndexCache = this._currentFaceIndex;
  9479. var lightPosition = this._light.position;
  9480. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9481. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9482. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9483. }
  9484. if (this._light.computeTransformedPosition()) {
  9485. lightPosition = this._light.transformedPosition;
  9486. }
  9487. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9488. this._cachedPosition = lightPosition.clone();
  9489. this._cachedDirection = this._lightDirection.clone();
  9490. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9491. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9492. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9493. }
  9494. return this._transformMatrix;
  9495. };
  9496. ShadowGenerator.prototype.getDarkness = function () {
  9497. return this._darkness;
  9498. };
  9499. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9500. if (darkness >= 1.0)
  9501. this._darkness = 1.0;
  9502. else if (darkness <= 0.0)
  9503. this._darkness = 0.0;
  9504. else
  9505. this._darkness = darkness;
  9506. };
  9507. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9508. this._transparencyShadow = hasShadow;
  9509. };
  9510. ShadowGenerator.prototype._packHalf = function (depth) {
  9511. var scale = depth * 255.0;
  9512. var fract = scale - Math.floor(scale);
  9513. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9514. };
  9515. ShadowGenerator.prototype.dispose = function () {
  9516. this._shadowMap.dispose();
  9517. if (this._shadowMap2) {
  9518. this._shadowMap2.dispose();
  9519. }
  9520. if (this._downSamplePostprocess) {
  9521. this._downSamplePostprocess.dispose();
  9522. }
  9523. if (this._boxBlurPostprocess) {
  9524. this._boxBlurPostprocess.dispose();
  9525. }
  9526. };
  9527. ShadowGenerator.prototype.serialize = function () {
  9528. var serializationObject = {};
  9529. serializationObject.lightId = this._light.id;
  9530. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9531. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9532. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9533. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9534. serializationObject.renderList = [];
  9535. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9536. var mesh = this.getShadowMap().renderList[meshIndex];
  9537. serializationObject.renderList.push(mesh.id);
  9538. }
  9539. return serializationObject;
  9540. };
  9541. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9542. //casting to point light, as light is missing the position attr and typescript complains.
  9543. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9544. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9545. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9546. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9547. shadowGenerator.getShadowMap().renderList.push(mesh);
  9548. }
  9549. if (parsedShadowGenerator.usePoissonSampling) {
  9550. shadowGenerator.usePoissonSampling = true;
  9551. }
  9552. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9553. shadowGenerator.useVarianceShadowMap = true;
  9554. }
  9555. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9556. shadowGenerator.useBlurVarianceShadowMap = true;
  9557. if (parsedShadowGenerator.blurScale) {
  9558. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9559. }
  9560. if (parsedShadowGenerator.blurBoxOffset) {
  9561. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9562. }
  9563. }
  9564. if (parsedShadowGenerator.bias !== undefined) {
  9565. shadowGenerator.bias = parsedShadowGenerator.bias;
  9566. }
  9567. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9568. return shadowGenerator;
  9569. };
  9570. ShadowGenerator._FILTER_NONE = 0;
  9571. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9572. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9573. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9574. return ShadowGenerator;
  9575. })();
  9576. BABYLON.ShadowGenerator = ShadowGenerator;
  9577. })(BABYLON || (BABYLON = {}));
  9578. var BABYLON;
  9579. (function (BABYLON) {
  9580. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9581. if (boxMin.x > sphereCenter.x + sphereRadius)
  9582. return false;
  9583. if (sphereCenter.x - sphereRadius > boxMax.x)
  9584. return false;
  9585. if (boxMin.y > sphereCenter.y + sphereRadius)
  9586. return false;
  9587. if (sphereCenter.y - sphereRadius > boxMax.y)
  9588. return false;
  9589. if (boxMin.z > sphereCenter.z + sphereRadius)
  9590. return false;
  9591. if (sphereCenter.z - sphereRadius > boxMax.z)
  9592. return false;
  9593. return true;
  9594. };
  9595. var getLowestRoot = function (a, b, c, maxR) {
  9596. var determinant = b * b - 4.0 * a * c;
  9597. var result = { root: 0, found: false };
  9598. if (determinant < 0)
  9599. return result;
  9600. var sqrtD = Math.sqrt(determinant);
  9601. var r1 = (-b - sqrtD) / (2.0 * a);
  9602. var r2 = (-b + sqrtD) / (2.0 * a);
  9603. if (r1 > r2) {
  9604. var temp = r2;
  9605. r2 = r1;
  9606. r1 = temp;
  9607. }
  9608. if (r1 > 0 && r1 < maxR) {
  9609. result.root = r1;
  9610. result.found = true;
  9611. return result;
  9612. }
  9613. if (r2 > 0 && r2 < maxR) {
  9614. result.root = r2;
  9615. result.found = true;
  9616. return result;
  9617. }
  9618. return result;
  9619. };
  9620. var Collider = (function () {
  9621. function Collider() {
  9622. this.radius = new BABYLON.Vector3(1, 1, 1);
  9623. this.retry = 0;
  9624. this.basePointWorld = BABYLON.Vector3.Zero();
  9625. this.velocityWorld = BABYLON.Vector3.Zero();
  9626. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9627. this._collisionPoint = BABYLON.Vector3.Zero();
  9628. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9629. this._tempVector = BABYLON.Vector3.Zero();
  9630. this._tempVector2 = BABYLON.Vector3.Zero();
  9631. this._tempVector3 = BABYLON.Vector3.Zero();
  9632. this._tempVector4 = BABYLON.Vector3.Zero();
  9633. this._edge = BABYLON.Vector3.Zero();
  9634. this._baseToVertex = BABYLON.Vector3.Zero();
  9635. this._destinationPoint = BABYLON.Vector3.Zero();
  9636. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9637. this._displacementVector = BABYLON.Vector3.Zero();
  9638. }
  9639. // Methods
  9640. Collider.prototype._initialize = function (source, dir, e) {
  9641. this.velocity = dir;
  9642. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9643. this.basePoint = source;
  9644. source.multiplyToRef(this.radius, this.basePointWorld);
  9645. dir.multiplyToRef(this.radius, this.velocityWorld);
  9646. this.velocityWorldLength = this.velocityWorld.length();
  9647. this.epsilon = e;
  9648. this.collisionFound = false;
  9649. };
  9650. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9651. pa.subtractToRef(point, this._tempVector);
  9652. pb.subtractToRef(point, this._tempVector2);
  9653. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9654. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9655. if (d < 0)
  9656. return false;
  9657. pc.subtractToRef(point, this._tempVector3);
  9658. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9659. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9660. if (d < 0)
  9661. return false;
  9662. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9663. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9664. return d >= 0;
  9665. };
  9666. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9667. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9668. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9669. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9670. return false;
  9671. }
  9672. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9673. return false;
  9674. return true;
  9675. };
  9676. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9677. var t0;
  9678. var embeddedInPlane = false;
  9679. //defensive programming, actually not needed.
  9680. if (!trianglePlaneArray) {
  9681. trianglePlaneArray = [];
  9682. }
  9683. if (!trianglePlaneArray[faceIndex]) {
  9684. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9685. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9686. }
  9687. var trianglePlane = trianglePlaneArray[faceIndex];
  9688. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9689. return;
  9690. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9691. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9692. if (normalDotVelocity == 0) {
  9693. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9694. return;
  9695. embeddedInPlane = true;
  9696. t0 = 0;
  9697. }
  9698. else {
  9699. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9700. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9701. if (t0 > t1) {
  9702. var temp = t1;
  9703. t1 = t0;
  9704. t0 = temp;
  9705. }
  9706. if (t0 > 1.0 || t1 < 0.0)
  9707. return;
  9708. if (t0 < 0)
  9709. t0 = 0;
  9710. if (t0 > 1.0)
  9711. t0 = 1.0;
  9712. }
  9713. this._collisionPoint.copyFromFloats(0, 0, 0);
  9714. var found = false;
  9715. var t = 1.0;
  9716. if (!embeddedInPlane) {
  9717. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9718. this.velocity.scaleToRef(t0, this._tempVector);
  9719. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9720. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9721. found = true;
  9722. t = t0;
  9723. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9724. }
  9725. }
  9726. if (!found) {
  9727. var velocitySquaredLength = this.velocity.lengthSquared();
  9728. var a = velocitySquaredLength;
  9729. this.basePoint.subtractToRef(p1, this._tempVector);
  9730. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9731. var c = this._tempVector.lengthSquared() - 1.0;
  9732. var lowestRoot = getLowestRoot(a, b, c, t);
  9733. if (lowestRoot.found) {
  9734. t = lowestRoot.root;
  9735. found = true;
  9736. this._collisionPoint.copyFrom(p1);
  9737. }
  9738. this.basePoint.subtractToRef(p2, this._tempVector);
  9739. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9740. c = this._tempVector.lengthSquared() - 1.0;
  9741. lowestRoot = getLowestRoot(a, b, c, t);
  9742. if (lowestRoot.found) {
  9743. t = lowestRoot.root;
  9744. found = true;
  9745. this._collisionPoint.copyFrom(p2);
  9746. }
  9747. this.basePoint.subtractToRef(p3, this._tempVector);
  9748. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9749. c = this._tempVector.lengthSquared() - 1.0;
  9750. lowestRoot = getLowestRoot(a, b, c, t);
  9751. if (lowestRoot.found) {
  9752. t = lowestRoot.root;
  9753. found = true;
  9754. this._collisionPoint.copyFrom(p3);
  9755. }
  9756. p2.subtractToRef(p1, this._edge);
  9757. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9758. var edgeSquaredLength = this._edge.lengthSquared();
  9759. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9760. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9761. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9762. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9763. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9764. lowestRoot = getLowestRoot(a, b, c, t);
  9765. if (lowestRoot.found) {
  9766. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9767. if (f >= 0.0 && f <= 1.0) {
  9768. t = lowestRoot.root;
  9769. found = true;
  9770. this._edge.scaleInPlace(f);
  9771. p1.addToRef(this._edge, this._collisionPoint);
  9772. }
  9773. }
  9774. p3.subtractToRef(p2, this._edge);
  9775. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9776. edgeSquaredLength = this._edge.lengthSquared();
  9777. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9778. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9779. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9780. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9781. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9782. lowestRoot = getLowestRoot(a, b, c, t);
  9783. if (lowestRoot.found) {
  9784. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9785. if (f >= 0.0 && f <= 1.0) {
  9786. t = lowestRoot.root;
  9787. found = true;
  9788. this._edge.scaleInPlace(f);
  9789. p2.addToRef(this._edge, this._collisionPoint);
  9790. }
  9791. }
  9792. p1.subtractToRef(p3, this._edge);
  9793. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9794. edgeSquaredLength = this._edge.lengthSquared();
  9795. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9796. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9797. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9798. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9799. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9800. lowestRoot = getLowestRoot(a, b, c, t);
  9801. if (lowestRoot.found) {
  9802. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9803. if (f >= 0.0 && f <= 1.0) {
  9804. t = lowestRoot.root;
  9805. found = true;
  9806. this._edge.scaleInPlace(f);
  9807. p3.addToRef(this._edge, this._collisionPoint);
  9808. }
  9809. }
  9810. }
  9811. if (found) {
  9812. var distToCollision = t * this.velocity.length();
  9813. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9814. if (!this.intersectionPoint) {
  9815. this.intersectionPoint = this._collisionPoint.clone();
  9816. }
  9817. else {
  9818. this.intersectionPoint.copyFrom(this._collisionPoint);
  9819. }
  9820. this.nearestDistance = distToCollision;
  9821. this.collisionFound = true;
  9822. }
  9823. }
  9824. };
  9825. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9826. for (var i = indexStart; i < indexEnd; i += 3) {
  9827. var p1 = pts[indices[i] - decal];
  9828. var p2 = pts[indices[i + 1] - decal];
  9829. var p3 = pts[indices[i + 2] - decal];
  9830. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9831. }
  9832. };
  9833. Collider.prototype._getResponse = function (pos, vel) {
  9834. pos.addToRef(vel, this._destinationPoint);
  9835. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9836. this.basePoint.addToRef(vel, pos);
  9837. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9838. this._slidePlaneNormal.normalize();
  9839. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9840. pos.addInPlace(this._displacementVector);
  9841. this.intersectionPoint.addInPlace(this._displacementVector);
  9842. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9843. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9844. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9845. };
  9846. return Collider;
  9847. })();
  9848. BABYLON.Collider = Collider;
  9849. })(BABYLON || (BABYLON = {}));
  9850. var BABYLON;
  9851. (function (BABYLON) {
  9852. //WebWorker code will be inserted to this variable.
  9853. BABYLON.CollisionWorker = "";
  9854. (function (WorkerTaskType) {
  9855. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9856. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9857. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9858. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9859. var WorkerTaskType = BABYLON.WorkerTaskType;
  9860. (function (WorkerReplyType) {
  9861. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9862. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9863. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9864. var WorkerReplyType = BABYLON.WorkerReplyType;
  9865. var CollisionCoordinatorWorker = (function () {
  9866. function CollisionCoordinatorWorker() {
  9867. var _this = this;
  9868. this._scaledPosition = BABYLON.Vector3.Zero();
  9869. this._scaledVelocity = BABYLON.Vector3.Zero();
  9870. this.onMeshUpdated = function (mesh) {
  9871. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9872. };
  9873. this.onGeometryUpdated = function (geometry) {
  9874. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9875. };
  9876. this._afterRender = function () {
  9877. if (!_this._init)
  9878. return;
  9879. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9880. return;
  9881. }
  9882. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9883. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9884. if (_this._runningUpdated > 4) {
  9885. return;
  9886. }
  9887. ++_this._runningUpdated;
  9888. var payload = {
  9889. updatedMeshes: _this._addUpdateMeshesList,
  9890. updatedGeometries: _this._addUpdateGeometriesList,
  9891. removedGeometries: _this._toRemoveGeometryArray,
  9892. removedMeshes: _this._toRemoveMeshesArray
  9893. };
  9894. var message = {
  9895. payload: payload,
  9896. taskType: WorkerTaskType.UPDATE
  9897. };
  9898. var serializable = [];
  9899. for (var id in payload.updatedGeometries) {
  9900. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9901. //prepare transferables
  9902. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9903. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9904. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9905. }
  9906. }
  9907. _this._worker.postMessage(message, serializable);
  9908. _this._addUpdateMeshesList = {};
  9909. _this._addUpdateGeometriesList = {};
  9910. _this._toRemoveGeometryArray = [];
  9911. _this._toRemoveMeshesArray = [];
  9912. };
  9913. this._onMessageFromWorker = function (e) {
  9914. var returnData = e.data;
  9915. if (returnData.error != WorkerReplyType.SUCCESS) {
  9916. //TODO what errors can be returned from the worker?
  9917. BABYLON.Tools.Warn("error returned from worker!");
  9918. return;
  9919. }
  9920. switch (returnData.taskType) {
  9921. case WorkerTaskType.INIT:
  9922. _this._init = true;
  9923. //Update the worked with ALL of the scene's current state
  9924. _this._scene.meshes.forEach(function (mesh) {
  9925. _this.onMeshAdded(mesh);
  9926. });
  9927. _this._scene.getGeometries().forEach(function (geometry) {
  9928. _this.onGeometryAdded(geometry);
  9929. });
  9930. break;
  9931. case WorkerTaskType.UPDATE:
  9932. _this._runningUpdated--;
  9933. break;
  9934. case WorkerTaskType.COLLIDE:
  9935. _this._runningCollisionTask = false;
  9936. var returnPayload = returnData.payload;
  9937. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9938. return;
  9939. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9940. //cleanup
  9941. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9942. break;
  9943. }
  9944. };
  9945. this._collisionsCallbackArray = [];
  9946. this._init = false;
  9947. this._runningUpdated = 0;
  9948. this._runningCollisionTask = false;
  9949. this._addUpdateMeshesList = {};
  9950. this._addUpdateGeometriesList = {};
  9951. this._toRemoveGeometryArray = [];
  9952. this._toRemoveMeshesArray = [];
  9953. }
  9954. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9955. if (!this._init)
  9956. return;
  9957. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9958. return;
  9959. position.divideToRef(collider.radius, this._scaledPosition);
  9960. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9961. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9962. var payload = {
  9963. collider: {
  9964. position: this._scaledPosition.asArray(),
  9965. velocity: this._scaledVelocity.asArray(),
  9966. radius: collider.radius.asArray()
  9967. },
  9968. collisionId: collisionIndex,
  9969. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9970. maximumRetry: maximumRetry
  9971. };
  9972. var message = {
  9973. payload: payload,
  9974. taskType: WorkerTaskType.COLLIDE
  9975. };
  9976. this._worker.postMessage(message);
  9977. };
  9978. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9979. this._scene = scene;
  9980. this._scene.registerAfterRender(this._afterRender);
  9981. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9982. this._worker = new Worker(workerUrl);
  9983. this._worker.onmessage = this._onMessageFromWorker;
  9984. var message = {
  9985. payload: {},
  9986. taskType: WorkerTaskType.INIT
  9987. };
  9988. this._worker.postMessage(message);
  9989. };
  9990. CollisionCoordinatorWorker.prototype.destroy = function () {
  9991. this._scene.unregisterAfterRender(this._afterRender);
  9992. this._worker.terminate();
  9993. };
  9994. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9995. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9996. this.onMeshUpdated(mesh);
  9997. };
  9998. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9999. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10000. };
  10001. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10002. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10003. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10004. this.onGeometryUpdated(geometry);
  10005. };
  10006. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10007. this._toRemoveGeometryArray.push(geometry.id);
  10008. };
  10009. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10010. var submeshes = [];
  10011. if (mesh.subMeshes) {
  10012. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10013. return {
  10014. position: idx,
  10015. verticesStart: sm.verticesStart,
  10016. verticesCount: sm.verticesCount,
  10017. indexStart: sm.indexStart,
  10018. indexCount: sm.indexCount,
  10019. hasMaterial: !!sm.getMaterial(),
  10020. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10021. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10022. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10023. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10024. };
  10025. });
  10026. }
  10027. var geometryId = null;
  10028. if (mesh instanceof BABYLON.Mesh) {
  10029. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10030. }
  10031. else if (mesh instanceof BABYLON.InstancedMesh) {
  10032. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10033. }
  10034. return {
  10035. uniqueId: mesh.uniqueId,
  10036. id: mesh.id,
  10037. name: mesh.name,
  10038. geometryId: geometryId,
  10039. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10040. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10041. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10042. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10043. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10044. subMeshes: submeshes,
  10045. checkCollisions: mesh.checkCollisions
  10046. };
  10047. };
  10048. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10049. return {
  10050. id: geometry.id,
  10051. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10052. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10053. indices: new Int32Array(geometry.getIndices() || []),
  10054. };
  10055. };
  10056. return CollisionCoordinatorWorker;
  10057. })();
  10058. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10059. var CollisionCoordinatorLegacy = (function () {
  10060. function CollisionCoordinatorLegacy() {
  10061. this._scaledPosition = BABYLON.Vector3.Zero();
  10062. this._scaledVelocity = BABYLON.Vector3.Zero();
  10063. this._finalPosition = BABYLON.Vector3.Zero();
  10064. }
  10065. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10066. position.divideToRef(collider.radius, this._scaledPosition);
  10067. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10068. collider.collidedMesh = null;
  10069. collider.retry = 0;
  10070. collider.initialVelocity = this._scaledVelocity;
  10071. collider.initialPosition = this._scaledPosition;
  10072. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10073. this._finalPosition.multiplyInPlace(collider.radius);
  10074. //run the callback
  10075. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10076. };
  10077. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10078. this._scene = scene;
  10079. };
  10080. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10081. //Legacy need no destruction method.
  10082. };
  10083. //No update in legacy mode
  10084. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10085. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10086. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10087. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10088. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10089. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10090. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10091. if (excludedMesh === void 0) { excludedMesh = null; }
  10092. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10093. if (collider.retry >= maximumRetry) {
  10094. finalPosition.copyFrom(position);
  10095. return;
  10096. }
  10097. collider._initialize(position, velocity, closeDistance);
  10098. // Check all meshes
  10099. for (var index = 0; index < this._scene.meshes.length; index++) {
  10100. var mesh = this._scene.meshes[index];
  10101. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10102. mesh._checkCollision(collider);
  10103. }
  10104. }
  10105. if (!collider.collisionFound) {
  10106. position.addToRef(velocity, finalPosition);
  10107. return;
  10108. }
  10109. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10110. collider._getResponse(position, velocity);
  10111. }
  10112. if (velocity.length() <= closeDistance) {
  10113. finalPosition.copyFrom(position);
  10114. return;
  10115. }
  10116. collider.retry++;
  10117. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10118. };
  10119. return CollisionCoordinatorLegacy;
  10120. })();
  10121. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10122. })(BABYLON || (BABYLON = {}));
  10123. var BABYLON;
  10124. (function (BABYLON) {
  10125. var VRCameraMetrics = (function () {
  10126. function VRCameraMetrics() {
  10127. this.compensateDistortion = true;
  10128. }
  10129. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  10130. get: function () {
  10131. return this.hResolution / (2 * this.vResolution);
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  10137. get: function () {
  10138. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  10144. get: function () {
  10145. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10146. var h = (4 * meters) / this.hScreenSize;
  10147. return BABYLON.Matrix.Translation(h, 0, 0);
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  10153. get: function () {
  10154. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10155. var h = (4 * meters) / this.hScreenSize;
  10156. return BABYLON.Matrix.Translation(-h, 0, 0);
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  10162. get: function () {
  10163. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  10169. get: function () {
  10170. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. VRCameraMetrics.GetDefault = function () {
  10176. var result = new VRCameraMetrics();
  10177. result.hResolution = 1280;
  10178. result.vResolution = 800;
  10179. result.hScreenSize = 0.149759993;
  10180. result.vScreenSize = 0.0935999975;
  10181. result.vScreenCenter = 0.0467999987,
  10182. result.eyeToScreenDistance = 0.0410000011;
  10183. result.lensSeparationDistance = 0.0635000020;
  10184. result.interpupillaryDistance = 0.0640000030;
  10185. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  10186. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  10187. result.postProcessScaleFactor = 1.714605507808412;
  10188. result.lensCenterOffset = 0.151976421;
  10189. return result;
  10190. };
  10191. return VRCameraMetrics;
  10192. })();
  10193. BABYLON.VRCameraMetrics = VRCameraMetrics;
  10194. var Camera = (function (_super) {
  10195. __extends(Camera, _super);
  10196. function Camera(name, position, scene) {
  10197. _super.call(this, name, scene);
  10198. this.position = position;
  10199. // Members
  10200. this.upVector = BABYLON.Vector3.Up();
  10201. this.orthoLeft = null;
  10202. this.orthoRight = null;
  10203. this.orthoBottom = null;
  10204. this.orthoTop = null;
  10205. this.fov = 0.8;
  10206. this.minZ = 1.0;
  10207. this.maxZ = 10000.0;
  10208. this.inertia = 0.9;
  10209. this.mode = Camera.PERSPECTIVE_CAMERA;
  10210. this.isIntermediate = false;
  10211. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10212. this.layerMask = 0x0FFFFFFF;
  10213. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10214. // Camera rig members
  10215. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10216. this._rigCameras = new Array();
  10217. // Cache
  10218. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10219. this._projectionMatrix = new BABYLON.Matrix();
  10220. this._postProcesses = new Array();
  10221. this._postProcessesTakenIndices = [];
  10222. this._activeMeshes = new BABYLON.SmartArray(256);
  10223. this._globalPosition = BABYLON.Vector3.Zero();
  10224. scene.addCamera(this);
  10225. if (!scene.activeCamera) {
  10226. scene.activeCamera = this;
  10227. }
  10228. }
  10229. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10230. get: function () {
  10231. return Camera._PERSPECTIVE_CAMERA;
  10232. },
  10233. enumerable: true,
  10234. configurable: true
  10235. });
  10236. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10237. get: function () {
  10238. return Camera._ORTHOGRAPHIC_CAMERA;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10244. get: function () {
  10245. return Camera._FOVMODE_VERTICAL_FIXED;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10251. get: function () {
  10252. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10258. get: function () {
  10259. return Camera._RIG_MODE_NONE;
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10265. get: function () {
  10266. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10272. get: function () {
  10273. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10279. get: function () {
  10280. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10281. },
  10282. enumerable: true,
  10283. configurable: true
  10284. });
  10285. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10286. get: function () {
  10287. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10288. },
  10289. enumerable: true,
  10290. configurable: true
  10291. });
  10292. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10293. get: function () {
  10294. return Camera._RIG_MODE_VR;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(Camera.prototype, "globalPosition", {
  10300. get: function () {
  10301. return this._globalPosition;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Camera.prototype.getActiveMeshes = function () {
  10307. return this._activeMeshes;
  10308. };
  10309. Camera.prototype.isActiveMesh = function (mesh) {
  10310. return (this._activeMeshes.indexOf(mesh) !== -1);
  10311. };
  10312. //Cache
  10313. Camera.prototype._initCache = function () {
  10314. _super.prototype._initCache.call(this);
  10315. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10316. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10317. this._cache.mode = undefined;
  10318. this._cache.minZ = undefined;
  10319. this._cache.maxZ = undefined;
  10320. this._cache.fov = undefined;
  10321. this._cache.aspectRatio = undefined;
  10322. this._cache.orthoLeft = undefined;
  10323. this._cache.orthoRight = undefined;
  10324. this._cache.orthoBottom = undefined;
  10325. this._cache.orthoTop = undefined;
  10326. this._cache.renderWidth = undefined;
  10327. this._cache.renderHeight = undefined;
  10328. };
  10329. Camera.prototype._updateCache = function (ignoreParentClass) {
  10330. if (!ignoreParentClass) {
  10331. _super.prototype._updateCache.call(this);
  10332. }
  10333. var engine = this.getEngine();
  10334. this._cache.position.copyFrom(this.position);
  10335. this._cache.upVector.copyFrom(this.upVector);
  10336. this._cache.mode = this.mode;
  10337. this._cache.minZ = this.minZ;
  10338. this._cache.maxZ = this.maxZ;
  10339. this._cache.fov = this.fov;
  10340. this._cache.aspectRatio = engine.getAspectRatio(this);
  10341. this._cache.orthoLeft = this.orthoLeft;
  10342. this._cache.orthoRight = this.orthoRight;
  10343. this._cache.orthoBottom = this.orthoBottom;
  10344. this._cache.orthoTop = this.orthoTop;
  10345. this._cache.renderWidth = engine.getRenderWidth();
  10346. this._cache.renderHeight = engine.getRenderHeight();
  10347. };
  10348. Camera.prototype._updateFromScene = function () {
  10349. this.updateCache();
  10350. this._update();
  10351. };
  10352. // Synchronized
  10353. Camera.prototype._isSynchronized = function () {
  10354. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10355. };
  10356. Camera.prototype._isSynchronizedViewMatrix = function () {
  10357. if (!_super.prototype._isSynchronized.call(this))
  10358. return false;
  10359. return this._cache.position.equals(this.position)
  10360. && this._cache.upVector.equals(this.upVector)
  10361. && this.isSynchronizedWithParent();
  10362. };
  10363. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10364. var check = this._cache.mode === this.mode
  10365. && this._cache.minZ === this.minZ
  10366. && this._cache.maxZ === this.maxZ;
  10367. if (!check) {
  10368. return false;
  10369. }
  10370. var engine = this.getEngine();
  10371. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10372. check = this._cache.fov === this.fov
  10373. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10374. }
  10375. else {
  10376. check = this._cache.orthoLeft === this.orthoLeft
  10377. && this._cache.orthoRight === this.orthoRight
  10378. && this._cache.orthoBottom === this.orthoBottom
  10379. && this._cache.orthoTop === this.orthoTop
  10380. && this._cache.renderWidth === engine.getRenderWidth()
  10381. && this._cache.renderHeight === engine.getRenderHeight();
  10382. }
  10383. return check;
  10384. };
  10385. // Controls
  10386. Camera.prototype.attachControl = function (element) {
  10387. };
  10388. Camera.prototype.detachControl = function (element) {
  10389. };
  10390. Camera.prototype._update = function () {
  10391. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10392. this._updateRigCameras();
  10393. }
  10394. this._checkInputs();
  10395. };
  10396. Camera.prototype._checkInputs = function () {
  10397. };
  10398. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10399. if (insertAt === void 0) { insertAt = null; }
  10400. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10401. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10402. return 0;
  10403. }
  10404. if (insertAt == null || insertAt < 0) {
  10405. this._postProcesses.push(postProcess);
  10406. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10407. return this._postProcesses.length - 1;
  10408. }
  10409. var add = 0;
  10410. var i;
  10411. var start;
  10412. if (this._postProcesses[insertAt]) {
  10413. start = this._postProcesses.length - 1;
  10414. for (i = start; i >= insertAt + 1; --i) {
  10415. this._postProcesses[i + 1] = this._postProcesses[i];
  10416. }
  10417. add = 1;
  10418. }
  10419. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10420. if (this._postProcessesTakenIndices[i] < insertAt) {
  10421. continue;
  10422. }
  10423. start = this._postProcessesTakenIndices.length - 1;
  10424. for (var j = start; j >= i; --j) {
  10425. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10426. }
  10427. this._postProcessesTakenIndices[i] = insertAt;
  10428. break;
  10429. }
  10430. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10431. this._postProcessesTakenIndices.push(insertAt);
  10432. }
  10433. var result = insertAt + add;
  10434. this._postProcesses[result] = postProcess;
  10435. return result;
  10436. };
  10437. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10438. if (atIndices === void 0) { atIndices = null; }
  10439. var result = [];
  10440. var i;
  10441. var index;
  10442. if (!atIndices) {
  10443. var length = this._postProcesses.length;
  10444. for (i = 0; i < length; i++) {
  10445. if (this._postProcesses[i] !== postProcess) {
  10446. continue;
  10447. }
  10448. delete this._postProcesses[i];
  10449. index = this._postProcessesTakenIndices.indexOf(i);
  10450. this._postProcessesTakenIndices.splice(index, 1);
  10451. }
  10452. }
  10453. else {
  10454. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10455. for (i = 0; i < atIndices.length; i++) {
  10456. var foundPostProcess = this._postProcesses[atIndices[i]];
  10457. if (foundPostProcess !== postProcess) {
  10458. result.push(i);
  10459. continue;
  10460. }
  10461. delete this._postProcesses[atIndices[i]];
  10462. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10463. this._postProcessesTakenIndices.splice(index, 1);
  10464. }
  10465. }
  10466. return result;
  10467. };
  10468. Camera.prototype.getWorldMatrix = function () {
  10469. if (!this._worldMatrix) {
  10470. this._worldMatrix = BABYLON.Matrix.Identity();
  10471. }
  10472. var viewMatrix = this.getViewMatrix();
  10473. viewMatrix.invertToRef(this._worldMatrix);
  10474. return this._worldMatrix;
  10475. };
  10476. Camera.prototype._getViewMatrix = function () {
  10477. return BABYLON.Matrix.Identity();
  10478. };
  10479. Camera.prototype.getViewMatrix = function (force) {
  10480. this._computedViewMatrix = this._computeViewMatrix(force);
  10481. if (!force && this._isSynchronizedViewMatrix()) {
  10482. return this._computedViewMatrix;
  10483. }
  10484. if (!this.parent || !this.parent.getWorldMatrix) {
  10485. this._globalPosition.copyFrom(this.position);
  10486. }
  10487. else {
  10488. if (!this._worldMatrix) {
  10489. this._worldMatrix = BABYLON.Matrix.Identity();
  10490. }
  10491. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10492. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10493. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10494. this._computedViewMatrix.invert();
  10495. this._markSyncedWithParent();
  10496. }
  10497. this._currentRenderId = this.getScene().getRenderId();
  10498. return this._computedViewMatrix;
  10499. };
  10500. Camera.prototype._computeViewMatrix = function (force) {
  10501. if (!force && this._isSynchronizedViewMatrix()) {
  10502. return this._computedViewMatrix;
  10503. }
  10504. this._computedViewMatrix = this._getViewMatrix();
  10505. this._currentRenderId = this.getScene().getRenderId();
  10506. return this._computedViewMatrix;
  10507. };
  10508. Camera.prototype.getProjectionMatrix = function (force) {
  10509. if (!force && this._isSynchronizedProjectionMatrix()) {
  10510. return this._projectionMatrix;
  10511. }
  10512. var engine = this.getEngine();
  10513. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10514. if (this.minZ <= 0) {
  10515. this.minZ = 0.1;
  10516. }
  10517. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10518. return this._projectionMatrix;
  10519. }
  10520. var halfWidth = engine.getRenderWidth() / 2.0;
  10521. var halfHeight = engine.getRenderHeight() / 2.0;
  10522. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10523. return this._projectionMatrix;
  10524. };
  10525. Camera.prototype.dispose = function () {
  10526. // Animations
  10527. this.getScene().stopAnimation(this);
  10528. // Remove from scene
  10529. this.getScene().removeCamera(this);
  10530. while (this._rigCameras.length > 0) {
  10531. this._rigCameras.pop().dispose();
  10532. }
  10533. // Postprocesses
  10534. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10535. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10536. }
  10537. };
  10538. // ---- Camera rigs section ----
  10539. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10540. while (this._rigCameras.length > 0) {
  10541. this._rigCameras.pop().dispose();
  10542. }
  10543. this.cameraRigMode = mode;
  10544. this._cameraRigParams = {};
  10545. switch (this.cameraRigMode) {
  10546. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10547. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10548. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10549. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10550. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10551. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10552. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10553. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10554. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10555. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10556. break;
  10557. }
  10558. var postProcesses = new Array();
  10559. switch (this.cameraRigMode) {
  10560. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10561. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10562. this._rigCameras[0].isIntermediate = true;
  10563. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10564. postProcesses[1].onApply = function (effect) {
  10565. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10566. };
  10567. break;
  10568. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10569. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10570. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10571. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10572. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10573. var secondCamIndex = 1 - firstCamIndex;
  10574. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10575. this._rigCameras[firstCamIndex].isIntermediate = true;
  10576. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10577. break;
  10578. case Camera.RIG_MODE_VR:
  10579. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10580. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10581. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10582. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10583. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10584. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10585. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10586. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10587. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10588. if (metrics.compensateDistortion) {
  10589. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10590. }
  10591. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10592. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10593. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10594. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10595. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10596. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10597. if (metrics.compensateDistortion) {
  10598. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10599. }
  10600. break;
  10601. }
  10602. this._update();
  10603. };
  10604. Camera.prototype._getVRProjectionMatrix = function () {
  10605. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10606. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10607. return this._projectionMatrix;
  10608. };
  10609. Camera.prototype.setCameraRigParameter = function (name, value) {
  10610. this._cameraRigParams[name] = value;
  10611. //provisionnally:
  10612. if (name === "interaxialDistance") {
  10613. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10614. }
  10615. };
  10616. /**
  10617. * May needs to be overridden by children so sub has required properties to be copied
  10618. */
  10619. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10620. return null;
  10621. };
  10622. /**
  10623. * May needs to be overridden by children
  10624. */
  10625. Camera.prototype._updateRigCameras = function () {
  10626. for (var i = 0; i < this._rigCameras.length; i++) {
  10627. this._rigCameras[i].minZ = this.minZ;
  10628. this._rigCameras[i].maxZ = this.maxZ;
  10629. this._rigCameras[i].fov = this.fov;
  10630. }
  10631. // only update viewport when ANAGLYPH
  10632. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10633. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10634. }
  10635. };
  10636. Camera.prototype.serialize = function () {
  10637. var serializationObject = {};
  10638. serializationObject.name = this.name;
  10639. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10640. serializationObject.id = this.id;
  10641. serializationObject.position = this.position.asArray();
  10642. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10643. // Parent
  10644. if (this.parent) {
  10645. serializationObject.parentId = this.parent.id;
  10646. }
  10647. serializationObject.fov = this.fov;
  10648. serializationObject.minZ = this.minZ;
  10649. serializationObject.maxZ = this.maxZ;
  10650. serializationObject.inertia = this.inertia;
  10651. // Animations
  10652. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10653. serializationObject.ranges = this.serializeAnimationRanges();
  10654. // Layer mask
  10655. serializationObject.layerMask = this.layerMask;
  10656. return serializationObject;
  10657. };
  10658. Camera.Parse = function (parsedCamera, scene) {
  10659. var camera;
  10660. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10661. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10662. var interaxial_distance;
  10663. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10664. var alpha = parsedCamera.alpha;
  10665. var beta = parsedCamera.beta;
  10666. var radius = parsedCamera.radius;
  10667. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10668. interaxial_distance = parsedCamera.interaxial_distance;
  10669. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10670. }
  10671. else {
  10672. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10673. }
  10674. }
  10675. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10676. interaxial_distance = parsedCamera.interaxial_distance;
  10677. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10678. }
  10679. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10680. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10681. }
  10682. else if (parsedCamera.type === "FollowCamera") {
  10683. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10684. camera.heightOffset = parsedCamera.heightOffset;
  10685. camera.radius = parsedCamera.radius;
  10686. camera.rotationOffset = parsedCamera.rotationOffset;
  10687. if (lockedTargetMesh)
  10688. camera.target = lockedTargetMesh;
  10689. }
  10690. else if (parsedCamera.type === "GamepadCamera") {
  10691. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10692. }
  10693. else if (parsedCamera.type === "TouchCamera") {
  10694. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10695. }
  10696. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10697. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10698. }
  10699. else if (parsedCamera.type === "WebVRFreeCamera") {
  10700. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10701. }
  10702. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10703. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10704. }
  10705. else if (parsedCamera.type === "FreeCamera") {
  10706. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
  10707. }
  10708. else {
  10709. // Universal Camera is the default value
  10710. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
  10711. }
  10712. // apply 3d rig, when found
  10713. if (parsedCamera.cameraRigMode) {
  10714. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10715. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10716. }
  10717. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10718. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10719. camera.lockedTarget = lockedTargetMesh;
  10720. }
  10721. camera.id = parsedCamera.id;
  10722. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10723. // Parent
  10724. if (parsedCamera.parentId) {
  10725. camera._waitingParentId = parsedCamera.parentId;
  10726. }
  10727. // Target
  10728. if (parsedCamera.target) {
  10729. if (camera.setTarget) {
  10730. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10731. }
  10732. else {
  10733. //For ArcRotate
  10734. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10735. }
  10736. }
  10737. else {
  10738. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10739. }
  10740. camera.fov = parsedCamera.fov;
  10741. camera.minZ = parsedCamera.minZ;
  10742. camera.maxZ = parsedCamera.maxZ;
  10743. camera.speed = parsedCamera.speed;
  10744. camera.inertia = parsedCamera.inertia;
  10745. camera.checkCollisions = parsedCamera.checkCollisions;
  10746. camera.applyGravity = parsedCamera.applyGravity;
  10747. if (parsedCamera.ellipsoid) {
  10748. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10749. }
  10750. // Animations
  10751. if (parsedCamera.animations) {
  10752. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10753. var parsedAnimation = parsedCamera.animations[animationIndex];
  10754. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10755. }
  10756. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10757. }
  10758. if (parsedCamera.autoAnimate) {
  10759. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10760. }
  10761. // Layer Mask
  10762. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10763. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10764. }
  10765. else {
  10766. camera.layerMask = 0x0FFFFFFF;
  10767. }
  10768. return camera;
  10769. };
  10770. // Statics
  10771. Camera._PERSPECTIVE_CAMERA = 0;
  10772. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10773. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10774. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10775. Camera._RIG_MODE_NONE = 0;
  10776. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10777. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10778. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10779. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10780. Camera._RIG_MODE_VR = 20;
  10781. return Camera;
  10782. })(BABYLON.Node);
  10783. BABYLON.Camera = Camera;
  10784. })(BABYLON || (BABYLON = {}));
  10785. var BABYLON;
  10786. (function (BABYLON) {
  10787. var TargetCamera = (function (_super) {
  10788. __extends(TargetCamera, _super);
  10789. function TargetCamera(name, position, scene) {
  10790. _super.call(this, name, position, scene);
  10791. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10792. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10793. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10794. this.speed = 2.0;
  10795. this.noRotationConstraint = false;
  10796. this.lockedTarget = null;
  10797. this._currentTarget = BABYLON.Vector3.Zero();
  10798. this._viewMatrix = BABYLON.Matrix.Zero();
  10799. this._camMatrix = BABYLON.Matrix.Zero();
  10800. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10801. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10802. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10803. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10804. this._lookAtTemp = BABYLON.Matrix.Zero();
  10805. this._tempMatrix = BABYLON.Matrix.Zero();
  10806. }
  10807. TargetCamera.prototype.getFrontPosition = function (distance) {
  10808. var direction = this.getTarget().subtract(this.position);
  10809. direction.normalize();
  10810. direction.scaleInPlace(distance);
  10811. return this.globalPosition.add(direction);
  10812. };
  10813. TargetCamera.prototype._getLockedTargetPosition = function () {
  10814. if (!this.lockedTarget) {
  10815. return null;
  10816. }
  10817. return this.lockedTarget.position || this.lockedTarget;
  10818. };
  10819. // Cache
  10820. TargetCamera.prototype._initCache = function () {
  10821. _super.prototype._initCache.call(this);
  10822. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10823. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10824. };
  10825. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10826. if (!ignoreParentClass) {
  10827. _super.prototype._updateCache.call(this);
  10828. }
  10829. var lockedTargetPosition = this._getLockedTargetPosition();
  10830. if (!lockedTargetPosition) {
  10831. this._cache.lockedTarget = null;
  10832. }
  10833. else {
  10834. if (!this._cache.lockedTarget) {
  10835. this._cache.lockedTarget = lockedTargetPosition.clone();
  10836. }
  10837. else {
  10838. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10839. }
  10840. }
  10841. this._cache.rotation.copyFrom(this.rotation);
  10842. };
  10843. // Synchronized
  10844. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10845. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10846. return false;
  10847. }
  10848. var lockedTargetPosition = this._getLockedTargetPosition();
  10849. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10850. && this._cache.rotation.equals(this.rotation);
  10851. };
  10852. // Methods
  10853. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10854. var engine = this.getEngine();
  10855. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10856. };
  10857. // Target
  10858. TargetCamera.prototype.setTarget = function (target) {
  10859. this.upVector.normalize();
  10860. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10861. this._camMatrix.invert();
  10862. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10863. var vDir = target.subtract(this.position);
  10864. if (vDir.x >= 0.0) {
  10865. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10866. }
  10867. else {
  10868. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10869. }
  10870. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10871. if (isNaN(this.rotation.x)) {
  10872. this.rotation.x = 0;
  10873. }
  10874. if (isNaN(this.rotation.y)) {
  10875. this.rotation.y = 0;
  10876. }
  10877. if (isNaN(this.rotation.z)) {
  10878. this.rotation.z = 0;
  10879. }
  10880. };
  10881. TargetCamera.prototype.getTarget = function () {
  10882. return this._currentTarget;
  10883. };
  10884. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10885. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10886. };
  10887. TargetCamera.prototype._updatePosition = function () {
  10888. this.position.addInPlace(this.cameraDirection);
  10889. };
  10890. TargetCamera.prototype._checkInputs = function () {
  10891. var needToMove = this._decideIfNeedsToMove();
  10892. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10893. // Move
  10894. if (needToMove) {
  10895. this._updatePosition();
  10896. }
  10897. // Rotate
  10898. if (needToRotate) {
  10899. this.rotation.x += this.cameraRotation.x;
  10900. this.rotation.y += this.cameraRotation.y;
  10901. if (!this.noRotationConstraint) {
  10902. var limit = (Math.PI / 2) * 0.95;
  10903. if (this.rotation.x > limit)
  10904. this.rotation.x = limit;
  10905. if (this.rotation.x < -limit)
  10906. this.rotation.x = -limit;
  10907. }
  10908. }
  10909. // Inertia
  10910. if (needToMove) {
  10911. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10912. this.cameraDirection.x = 0;
  10913. }
  10914. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10915. this.cameraDirection.y = 0;
  10916. }
  10917. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10918. this.cameraDirection.z = 0;
  10919. }
  10920. this.cameraDirection.scaleInPlace(this.inertia);
  10921. }
  10922. if (needToRotate) {
  10923. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10924. this.cameraRotation.x = 0;
  10925. }
  10926. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10927. this.cameraRotation.y = 0;
  10928. }
  10929. this.cameraRotation.scaleInPlace(this.inertia);
  10930. }
  10931. _super.prototype._checkInputs.call(this);
  10932. };
  10933. TargetCamera.prototype._getViewMatrix = function () {
  10934. if (!this.lockedTarget) {
  10935. // Compute
  10936. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10937. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10938. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10939. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10940. this._lookAtTemp.invert();
  10941. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10942. }
  10943. else {
  10944. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10945. }
  10946. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10947. // Computing target and final matrix
  10948. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10949. }
  10950. else {
  10951. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10952. }
  10953. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10954. return this._viewMatrix;
  10955. };
  10956. TargetCamera.prototype._getVRViewMatrix = function () {
  10957. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10958. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10959. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10960. // Computing target and final matrix
  10961. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10962. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10963. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10964. return this._viewMatrix;
  10965. };
  10966. /**
  10967. * @override
  10968. * Override Camera.createRigCamera
  10969. */
  10970. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10971. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10972. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10973. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10974. rigCamera._cameraRigParams = {};
  10975. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10976. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10977. }
  10978. return rigCamera;
  10979. }
  10980. return null;
  10981. };
  10982. /**
  10983. * @override
  10984. * Override Camera._updateRigCameras
  10985. */
  10986. TargetCamera.prototype._updateRigCameras = function () {
  10987. switch (this.cameraRigMode) {
  10988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10991. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10992. case BABYLON.Camera.RIG_MODE_VR:
  10993. var camLeft = this._rigCameras[0];
  10994. var camRight = this._rigCameras[1];
  10995. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10996. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10997. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10998. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10999. camLeft.position.copyFrom(this.position);
  11000. camRight.position.copyFrom(this.position);
  11001. }
  11002. else {
  11003. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11004. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11005. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11006. camLeft.setTarget(this.getTarget());
  11007. camRight.setTarget(this.getTarget());
  11008. }
  11009. break;
  11010. }
  11011. _super.prototype._updateRigCameras.call(this);
  11012. };
  11013. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11014. if (!this._rigCamTransformMatrix) {
  11015. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11016. }
  11017. var target = this.getTarget();
  11018. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11019. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11020. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11021. };
  11022. TargetCamera.prototype.serialize = function () {
  11023. var serializationObject = _super.prototype.serialize.call(this);
  11024. serializationObject.speed = this.speed;
  11025. if (this.rotation) {
  11026. serializationObject.rotation = this.rotation.asArray();
  11027. }
  11028. if (this.lockedTarget && this.lockedTarget.id) {
  11029. serializationObject.lockedTargetId = this.lockedTarget.id;
  11030. }
  11031. return serializationObject;
  11032. };
  11033. return TargetCamera;
  11034. })(BABYLON.Camera);
  11035. BABYLON.TargetCamera = TargetCamera;
  11036. })(BABYLON || (BABYLON = {}));
  11037. var BABYLON;
  11038. (function (BABYLON) {
  11039. var FreeCamera = (function (_super) {
  11040. __extends(FreeCamera, _super);
  11041. function FreeCamera(name, position, scene) {
  11042. var _this = this;
  11043. _super.call(this, name, position, scene);
  11044. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11045. this.keysUp = [38];
  11046. this.keysDown = [40];
  11047. this.keysLeft = [37];
  11048. this.keysRight = [39];
  11049. this.checkCollisions = false;
  11050. this.applyGravity = false;
  11051. this.angularSensibility = 2000.0;
  11052. this._keys = [];
  11053. this._collider = new BABYLON.Collider();
  11054. this._needMoveForGravity = false;
  11055. this._oldPosition = BABYLON.Vector3.Zero();
  11056. this._diffPosition = BABYLON.Vector3.Zero();
  11057. this._newPosition = BABYLON.Vector3.Zero();
  11058. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11059. if (collidedMesh === void 0) { collidedMesh = null; }
  11060. //TODO move this to the collision coordinator!
  11061. if (_this.getScene().workerCollisions)
  11062. newPosition.multiplyInPlace(_this._collider.radius);
  11063. var updatePosition = function (newPos) {
  11064. _this._newPosition.copyFrom(newPos);
  11065. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11066. var oldPosition = _this.position.clone();
  11067. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11068. _this.position.addInPlace(_this._diffPosition);
  11069. if (_this.onCollide && collidedMesh) {
  11070. _this.onCollide(collidedMesh);
  11071. }
  11072. }
  11073. };
  11074. updatePosition(newPosition);
  11075. };
  11076. }
  11077. FreeCamera.prototype._onLostFocus = function (e) {
  11078. this._keys = [];
  11079. };
  11080. // Controls
  11081. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11082. var _this = this;
  11083. var previousPosition;
  11084. var engine = this.getEngine();
  11085. if (this._attachedElement) {
  11086. return;
  11087. }
  11088. this._attachedElement = element;
  11089. if (this._onMouseDown === undefined) {
  11090. this._onMouseDown = function (evt) {
  11091. previousPosition = {
  11092. x: evt.clientX,
  11093. y: evt.clientY
  11094. };
  11095. if (!noPreventDefault) {
  11096. evt.preventDefault();
  11097. }
  11098. };
  11099. this._onMouseUp = function (evt) {
  11100. previousPosition = null;
  11101. if (!noPreventDefault) {
  11102. evt.preventDefault();
  11103. }
  11104. };
  11105. this._onMouseOut = function (evt) {
  11106. previousPosition = null;
  11107. _this._keys = [];
  11108. if (!noPreventDefault) {
  11109. evt.preventDefault();
  11110. }
  11111. };
  11112. this._onMouseMove = function (evt) {
  11113. if (!previousPosition && !engine.isPointerLock) {
  11114. return;
  11115. }
  11116. var offsetX;
  11117. var offsetY;
  11118. if (!engine.isPointerLock) {
  11119. offsetX = evt.clientX - previousPosition.x;
  11120. offsetY = evt.clientY - previousPosition.y;
  11121. }
  11122. else {
  11123. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11124. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11125. }
  11126. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11127. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11128. previousPosition = {
  11129. x: evt.clientX,
  11130. y: evt.clientY
  11131. };
  11132. if (!noPreventDefault) {
  11133. evt.preventDefault();
  11134. }
  11135. };
  11136. this._onKeyDown = function (evt) {
  11137. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11138. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11139. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11140. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11141. var index = _this._keys.indexOf(evt.keyCode);
  11142. if (index === -1) {
  11143. _this._keys.push(evt.keyCode);
  11144. }
  11145. if (!noPreventDefault) {
  11146. evt.preventDefault();
  11147. }
  11148. }
  11149. };
  11150. this._onKeyUp = function (evt) {
  11151. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11152. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11153. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11154. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11155. var index = _this._keys.indexOf(evt.keyCode);
  11156. if (index >= 0) {
  11157. _this._keys.splice(index, 1);
  11158. }
  11159. if (!noPreventDefault) {
  11160. evt.preventDefault();
  11161. }
  11162. }
  11163. };
  11164. this._reset = function () {
  11165. _this._keys = [];
  11166. previousPosition = null;
  11167. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11168. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11169. };
  11170. }
  11171. element.addEventListener("mousedown", this._onMouseDown, false);
  11172. element.addEventListener("mouseup", this._onMouseUp, false);
  11173. element.addEventListener("mouseout", this._onMouseOut, false);
  11174. element.addEventListener("mousemove", this._onMouseMove, false);
  11175. BABYLON.Tools.RegisterTopRootEvents([
  11176. { name: "keydown", handler: this._onKeyDown },
  11177. { name: "keyup", handler: this._onKeyUp },
  11178. { name: "blur", handler: this._onLostFocus }
  11179. ]);
  11180. };
  11181. FreeCamera.prototype.detachControl = function (element) {
  11182. if (this._attachedElement !== element) {
  11183. return;
  11184. }
  11185. element.removeEventListener("mousedown", this._onMouseDown);
  11186. element.removeEventListener("mouseup", this._onMouseUp);
  11187. element.removeEventListener("mouseout", this._onMouseOut);
  11188. element.removeEventListener("mousemove", this._onMouseMove);
  11189. BABYLON.Tools.UnregisterTopRootEvents([
  11190. { name: "keydown", handler: this._onKeyDown },
  11191. { name: "keyup", handler: this._onKeyUp },
  11192. { name: "blur", handler: this._onLostFocus }
  11193. ]);
  11194. this._attachedElement = null;
  11195. if (this._reset) {
  11196. this._reset();
  11197. }
  11198. };
  11199. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11200. var globalPosition;
  11201. if (this.parent) {
  11202. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11203. }
  11204. else {
  11205. globalPosition = this.position;
  11206. }
  11207. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11208. this._collider.radius = this.ellipsoid;
  11209. //no need for clone, as long as gravity is not on.
  11210. var actualVelocity = velocity;
  11211. //add gravity to the velocity to prevent the dual-collision checking
  11212. if (this.applyGravity) {
  11213. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11214. actualVelocity = velocity.add(this.getScene().gravity);
  11215. }
  11216. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11217. };
  11218. FreeCamera.prototype._checkInputs = function () {
  11219. if (!this._localDirection) {
  11220. this._localDirection = BABYLON.Vector3.Zero();
  11221. this._transformedDirection = BABYLON.Vector3.Zero();
  11222. }
  11223. // Keyboard
  11224. for (var index = 0; index < this._keys.length; index++) {
  11225. var keyCode = this._keys[index];
  11226. var speed = this._computeLocalCameraSpeed();
  11227. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11228. this._localDirection.copyFromFloats(-speed, 0, 0);
  11229. }
  11230. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11231. this._localDirection.copyFromFloats(0, 0, speed);
  11232. }
  11233. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11234. this._localDirection.copyFromFloats(speed, 0, 0);
  11235. }
  11236. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11237. this._localDirection.copyFromFloats(0, 0, -speed);
  11238. }
  11239. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11240. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11241. this.cameraDirection.addInPlace(this._transformedDirection);
  11242. }
  11243. _super.prototype._checkInputs.call(this);
  11244. };
  11245. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11246. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11247. };
  11248. FreeCamera.prototype._updatePosition = function () {
  11249. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11250. this._collideWithWorld(this.cameraDirection);
  11251. }
  11252. else {
  11253. this.position.addInPlace(this.cameraDirection);
  11254. }
  11255. };
  11256. FreeCamera.prototype.serialize = function () {
  11257. var serializationObject = _super.prototype.serialize.call(this);
  11258. serializationObject.checkCollisions = this.checkCollisions;
  11259. serializationObject.applyGravity = this.applyGravity;
  11260. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11261. return serializationObject;
  11262. };
  11263. return FreeCamera;
  11264. })(BABYLON.TargetCamera);
  11265. BABYLON.FreeCamera = FreeCamera;
  11266. })(BABYLON || (BABYLON = {}));
  11267. var BABYLON;
  11268. (function (BABYLON) {
  11269. var FollowCamera = (function (_super) {
  11270. __extends(FollowCamera, _super);
  11271. function FollowCamera(name, position, scene) {
  11272. _super.call(this, name, position, scene);
  11273. this.radius = 12;
  11274. this.rotationOffset = 0;
  11275. this.heightOffset = 4;
  11276. this.cameraAcceleration = 0.05;
  11277. this.maxCameraSpeed = 20;
  11278. }
  11279. FollowCamera.prototype.getRadians = function (degrees) {
  11280. return degrees * Math.PI / 180;
  11281. };
  11282. FollowCamera.prototype.follow = function (cameraTarget) {
  11283. if (!cameraTarget)
  11284. return;
  11285. var yRotation;
  11286. if (cameraTarget.rotationQuaternion) {
  11287. var rotMatrix = new BABYLON.Matrix();
  11288. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11289. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11290. }
  11291. else {
  11292. yRotation = cameraTarget.rotation.y;
  11293. }
  11294. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11295. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11296. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11297. var dx = targetX - this.position.x;
  11298. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11299. var dz = (targetZ) - this.position.z;
  11300. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11301. var vy = dy * this.cameraAcceleration;
  11302. var vz = dz * this.cameraAcceleration * 2;
  11303. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11304. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11305. }
  11306. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11307. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11308. }
  11309. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11310. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11311. }
  11312. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11313. this.setTarget(cameraTarget.position);
  11314. };
  11315. FollowCamera.prototype._checkInputs = function () {
  11316. _super.prototype._checkInputs.call(this);
  11317. this.follow(this.target);
  11318. };
  11319. FollowCamera.prototype.serialize = function () {
  11320. var serializationObject = _super.prototype.serialize.call(this);
  11321. serializationObject.radius = this.radius;
  11322. serializationObject.heightOffset = this.heightOffset;
  11323. serializationObject.rotationOffset = this.rotationOffset;
  11324. return serializationObject;
  11325. };
  11326. return FollowCamera;
  11327. })(BABYLON.TargetCamera);
  11328. BABYLON.FollowCamera = FollowCamera;
  11329. var ArcFollowCamera = (function (_super) {
  11330. __extends(ArcFollowCamera, _super);
  11331. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11332. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11333. this.alpha = alpha;
  11334. this.beta = beta;
  11335. this.radius = radius;
  11336. this.target = target;
  11337. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11338. this.follow();
  11339. }
  11340. ArcFollowCamera.prototype.follow = function () {
  11341. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11342. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11343. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11344. this.position = this.target.position.add(this._cartesianCoordinates);
  11345. this.setTarget(this.target.position);
  11346. };
  11347. ArcFollowCamera.prototype._checkInputs = function () {
  11348. _super.prototype._checkInputs.call(this);
  11349. this.follow();
  11350. };
  11351. ArcFollowCamera.prototype.serialize = function () {
  11352. var serializationObject = _super.prototype.serialize.call(this);
  11353. serializationObject.radius = this.radius;
  11354. return serializationObject;
  11355. };
  11356. return ArcFollowCamera;
  11357. })(BABYLON.TargetCamera);
  11358. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11359. })(BABYLON || (BABYLON = {}));
  11360. var BABYLON;
  11361. (function (BABYLON) {
  11362. // We're mainly based on the logic defined into the FreeCamera code
  11363. var TouchCamera = (function (_super) {
  11364. __extends(TouchCamera, _super);
  11365. function TouchCamera(name, position, scene) {
  11366. _super.call(this, name, position, scene);
  11367. this._offsetX = null;
  11368. this._offsetY = null;
  11369. this._pointerCount = 0;
  11370. this._pointerPressed = [];
  11371. this.touchAngularSensibility = 200000.0;
  11372. this.touchMoveSensibility = 250.0;
  11373. }
  11374. TouchCamera.prototype._onLostFocus = function (e) {
  11375. this._offsetX = null;
  11376. this._offsetY = null;
  11377. _super.prototype._onLostFocus.call(this, e);
  11378. };
  11379. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11380. var _this = this;
  11381. var previousPosition;
  11382. if (this._attachedCanvas) {
  11383. return;
  11384. }
  11385. if (this._onPointerDown === undefined) {
  11386. this._onPointerDown = function (evt) {
  11387. if (evt.pointerType === "mouse") {
  11388. return;
  11389. }
  11390. if (!noPreventDefault) {
  11391. evt.preventDefault();
  11392. }
  11393. _this._pointerPressed.push(evt.pointerId);
  11394. if (_this._pointerPressed.length !== 1) {
  11395. return;
  11396. }
  11397. previousPosition = {
  11398. x: evt.clientX,
  11399. y: evt.clientY
  11400. };
  11401. };
  11402. this._onPointerUp = function (evt) {
  11403. if (evt.pointerType === "mouse") {
  11404. return;
  11405. }
  11406. if (!noPreventDefault) {
  11407. evt.preventDefault();
  11408. }
  11409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11410. if (index === -1) {
  11411. return;
  11412. }
  11413. _this._pointerPressed.splice(index, 1);
  11414. if (index != 0) {
  11415. return;
  11416. }
  11417. previousPosition = null;
  11418. _this._offsetX = null;
  11419. _this._offsetY = null;
  11420. };
  11421. this._onPointerMove = function (evt) {
  11422. if (evt.pointerType === "mouse") {
  11423. return;
  11424. }
  11425. if (!noPreventDefault) {
  11426. evt.preventDefault();
  11427. }
  11428. if (!previousPosition) {
  11429. return;
  11430. }
  11431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11432. if (index != 0) {
  11433. return;
  11434. }
  11435. _this._offsetX = evt.clientX - previousPosition.x;
  11436. _this._offsetY = -(evt.clientY - previousPosition.y);
  11437. };
  11438. }
  11439. canvas.addEventListener("pointerdown", this._onPointerDown);
  11440. canvas.addEventListener("pointerup", this._onPointerUp);
  11441. canvas.addEventListener("pointerout", this._onPointerUp);
  11442. canvas.addEventListener("pointermove", this._onPointerMove);
  11443. _super.prototype.attachControl.call(this, canvas);
  11444. };
  11445. TouchCamera.prototype.detachControl = function (canvas) {
  11446. if (this._attachedCanvas !== canvas) {
  11447. return;
  11448. }
  11449. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11450. canvas.removeEventListener("pointerup", this._onPointerUp);
  11451. canvas.removeEventListener("pointerout", this._onPointerUp);
  11452. canvas.removeEventListener("pointermove", this._onPointerMove);
  11453. _super.prototype.detachControl.call(this, canvas);
  11454. };
  11455. TouchCamera.prototype._checkInputs = function () {
  11456. if (this._offsetX) {
  11457. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11458. if (this._pointerPressed.length > 1) {
  11459. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11460. }
  11461. else {
  11462. var speed = this._computeLocalCameraSpeed();
  11463. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11464. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11465. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11466. }
  11467. }
  11468. _super.prototype._checkInputs.call(this);
  11469. };
  11470. return TouchCamera;
  11471. })(BABYLON.FreeCamera);
  11472. BABYLON.TouchCamera = TouchCamera;
  11473. })(BABYLON || (BABYLON = {}));
  11474. var BABYLON;
  11475. (function (BABYLON) {
  11476. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11477. var ArcRotateCamera = (function (_super) {
  11478. __extends(ArcRotateCamera, _super);
  11479. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11480. var _this = this;
  11481. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11482. this.alpha = alpha;
  11483. this.beta = beta;
  11484. this.radius = radius;
  11485. this.target = target;
  11486. this.inertialAlphaOffset = 0;
  11487. this.inertialBetaOffset = 0;
  11488. this.inertialRadiusOffset = 0;
  11489. this.lowerAlphaLimit = null;
  11490. this.upperAlphaLimit = null;
  11491. this.lowerBetaLimit = 0.01;
  11492. this.upperBetaLimit = Math.PI;
  11493. this.lowerRadiusLimit = null;
  11494. this.upperRadiusLimit = null;
  11495. this.angularSensibilityX = 1000.0;
  11496. this.angularSensibilityY = 1000.0;
  11497. this.wheelPrecision = 3.0;
  11498. this.pinchPrecision = 2.0;
  11499. this.panningSensibility = 50.0;
  11500. this.inertialPanningX = 0;
  11501. this.inertialPanningY = 0;
  11502. this.keysUp = [38];
  11503. this.keysDown = [40];
  11504. this.keysLeft = [37];
  11505. this.keysRight = [39];
  11506. this.zoomOnFactor = 1;
  11507. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11508. this.pinchInwards = true;
  11509. this.allowUpsideDown = true;
  11510. this._keys = [];
  11511. this._viewMatrix = new BABYLON.Matrix();
  11512. // Panning
  11513. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11514. this._isRightClick = false;
  11515. this._isCtrlPushed = false;
  11516. this.checkCollisions = false;
  11517. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11518. this._collider = new BABYLON.Collider();
  11519. this._previousPosition = BABYLON.Vector3.Zero();
  11520. this._collisionVelocity = BABYLON.Vector3.Zero();
  11521. this._newPosition = BABYLON.Vector3.Zero();
  11522. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11523. if (collidedMesh === void 0) { collidedMesh = null; }
  11524. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11525. newPosition.multiplyInPlace(_this._collider.radius);
  11526. }
  11527. if (!collidedMesh) {
  11528. _this._previousPosition.copyFrom(_this.position);
  11529. }
  11530. else {
  11531. _this.setPosition(newPosition);
  11532. if (_this.onCollide) {
  11533. _this.onCollide(collidedMesh);
  11534. }
  11535. }
  11536. // Recompute because of constraints
  11537. var cosa = Math.cos(_this.alpha);
  11538. var sina = Math.sin(_this.alpha);
  11539. var cosb = Math.cos(_this.beta);
  11540. var sinb = Math.sin(_this.beta);
  11541. var target = _this._getTargetPosition();
  11542. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11543. _this.position.copyFrom(_this._newPosition);
  11544. var up = _this.upVector;
  11545. if (_this.allowUpsideDown && _this.beta < 0) {
  11546. up = up.clone();
  11547. up = up.negate();
  11548. }
  11549. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11550. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11551. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11552. _this._collisionTriggered = false;
  11553. };
  11554. if (!this.target) {
  11555. this.target = BABYLON.Vector3.Zero();
  11556. }
  11557. this.getViewMatrix();
  11558. }
  11559. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11560. //deprecated angularSensibility support
  11561. get: function () {
  11562. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11563. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11564. },
  11565. //deprecated angularSensibility support
  11566. set: function (value) {
  11567. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11568. this.angularSensibilityX = value;
  11569. this.angularSensibilityY = value;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. ArcRotateCamera.prototype._getTargetPosition = function () {
  11575. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11576. };
  11577. // Cache
  11578. ArcRotateCamera.prototype._initCache = function () {
  11579. _super.prototype._initCache.call(this);
  11580. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11581. this._cache.alpha = undefined;
  11582. this._cache.beta = undefined;
  11583. this._cache.radius = undefined;
  11584. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11585. };
  11586. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11587. if (!ignoreParentClass) {
  11588. _super.prototype._updateCache.call(this);
  11589. }
  11590. this._cache.target.copyFrom(this._getTargetPosition());
  11591. this._cache.alpha = this.alpha;
  11592. this._cache.beta = this.beta;
  11593. this._cache.radius = this.radius;
  11594. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11595. };
  11596. // Synchronized
  11597. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11598. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11599. return false;
  11600. return this._cache.target.equals(this._getTargetPosition())
  11601. && this._cache.alpha === this.alpha
  11602. && this._cache.beta === this.beta
  11603. && this._cache.radius === this.radius
  11604. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11605. };
  11606. // Methods
  11607. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11608. var _this = this;
  11609. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11610. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11611. var previousPinchDistance = 0;
  11612. var pointers = new BABYLON.SmartCollection();
  11613. if (this._attachedElement) {
  11614. return;
  11615. }
  11616. this._attachedElement = element;
  11617. var engine = this.getEngine();
  11618. if (this._onPointerDown === undefined) {
  11619. this._onPointerDown = function (evt) {
  11620. // Manage panning with right click
  11621. _this._isRightClick = evt.button === 2;
  11622. // manage pointers
  11623. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11624. cacheSoloPointer = pointers.item(evt.pointerId);
  11625. if (!noPreventDefault) {
  11626. evt.preventDefault();
  11627. }
  11628. };
  11629. this._onPointerUp = function (evt) {
  11630. cacheSoloPointer = null;
  11631. previousPinchDistance = 0;
  11632. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11633. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11634. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11635. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11636. pointers.empty();
  11637. if (!noPreventDefault) {
  11638. evt.preventDefault();
  11639. }
  11640. };
  11641. this._onContextMenu = function (evt) {
  11642. evt.preventDefault();
  11643. };
  11644. this._onPointerMove = function (evt) {
  11645. if (!noPreventDefault) {
  11646. evt.preventDefault();
  11647. }
  11648. switch (pointers.count) {
  11649. case 1:
  11650. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11651. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11652. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11653. }
  11654. else {
  11655. var offsetX = evt.clientX - cacheSoloPointer.x;
  11656. var offsetY = evt.clientY - cacheSoloPointer.y;
  11657. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11658. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11659. }
  11660. cacheSoloPointer.x = evt.clientX;
  11661. cacheSoloPointer.y = evt.clientY;
  11662. break;
  11663. case 2:
  11664. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11665. pointers.item(evt.pointerId).x = evt.clientX;
  11666. pointers.item(evt.pointerId).y = evt.clientY;
  11667. var direction = _this.pinchInwards ? 1 : -1;
  11668. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11669. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11670. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11671. if (previousPinchDistance === 0) {
  11672. previousPinchDistance = pinchSquaredDistance;
  11673. return;
  11674. }
  11675. if (pinchSquaredDistance !== previousPinchDistance) {
  11676. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11677. previousPinchDistance = pinchSquaredDistance;
  11678. }
  11679. break;
  11680. default:
  11681. if (pointers.item(evt.pointerId)) {
  11682. pointers.item(evt.pointerId).x = evt.clientX;
  11683. pointers.item(evt.pointerId).y = evt.clientY;
  11684. }
  11685. }
  11686. };
  11687. this._onMouseMove = function (evt) {
  11688. if (!engine.isPointerLock) {
  11689. return;
  11690. }
  11691. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11692. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11693. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11694. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11695. if (!noPreventDefault) {
  11696. evt.preventDefault();
  11697. }
  11698. };
  11699. this._wheel = function (event) {
  11700. var delta = 0;
  11701. if (event.wheelDelta) {
  11702. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11703. }
  11704. else if (event.detail) {
  11705. delta = -event.detail / _this.wheelPrecision;
  11706. }
  11707. if (delta)
  11708. _this.inertialRadiusOffset += delta;
  11709. if (event.preventDefault) {
  11710. if (!noPreventDefault) {
  11711. event.preventDefault();
  11712. }
  11713. }
  11714. };
  11715. this._onKeyDown = function (evt) {
  11716. _this._isCtrlPushed = evt.ctrlKey;
  11717. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11718. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11719. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11720. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11721. var index = _this._keys.indexOf(evt.keyCode);
  11722. if (index === -1) {
  11723. _this._keys.push(evt.keyCode);
  11724. }
  11725. if (evt.preventDefault) {
  11726. if (!noPreventDefault) {
  11727. evt.preventDefault();
  11728. }
  11729. }
  11730. }
  11731. };
  11732. this._onKeyUp = function (evt) {
  11733. _this._isCtrlPushed = evt.ctrlKey;
  11734. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11735. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11736. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11737. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11738. var index = _this._keys.indexOf(evt.keyCode);
  11739. if (index >= 0) {
  11740. _this._keys.splice(index, 1);
  11741. }
  11742. if (evt.preventDefault) {
  11743. if (!noPreventDefault) {
  11744. evt.preventDefault();
  11745. }
  11746. }
  11747. }
  11748. };
  11749. this._onLostFocus = function () {
  11750. _this._keys = [];
  11751. pointers.empty();
  11752. previousPinchDistance = 0;
  11753. cacheSoloPointer = null;
  11754. };
  11755. this._onGestureStart = function (e) {
  11756. if (window.MSGesture === undefined) {
  11757. return;
  11758. }
  11759. if (!_this._MSGestureHandler) {
  11760. _this._MSGestureHandler = new MSGesture();
  11761. _this._MSGestureHandler.target = element;
  11762. }
  11763. _this._MSGestureHandler.addPointer(e.pointerId);
  11764. };
  11765. this._onGesture = function (e) {
  11766. _this.radius *= e.scale;
  11767. if (e.preventDefault) {
  11768. if (!noPreventDefault) {
  11769. e.stopPropagation();
  11770. e.preventDefault();
  11771. }
  11772. }
  11773. };
  11774. this._reset = function () {
  11775. _this._keys = [];
  11776. _this.inertialAlphaOffset = 0;
  11777. _this.inertialBetaOffset = 0;
  11778. _this.inertialRadiusOffset = 0;
  11779. pointers.empty();
  11780. previousPinchDistance = 0;
  11781. cacheSoloPointer = null;
  11782. };
  11783. }
  11784. if (!useCtrlForPanning) {
  11785. element.addEventListener("contextmenu", this._onContextMenu, false);
  11786. }
  11787. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11788. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11789. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11790. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11791. element.addEventListener("mousemove", this._onMouseMove, false);
  11792. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11793. element.addEventListener("MSGestureChange", this._onGesture, false);
  11794. element.addEventListener('mousewheel', this._wheel, false);
  11795. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11796. BABYLON.Tools.RegisterTopRootEvents([
  11797. { name: "keydown", handler: this._onKeyDown },
  11798. { name: "keyup", handler: this._onKeyUp },
  11799. { name: "blur", handler: this._onLostFocus }
  11800. ]);
  11801. };
  11802. ArcRotateCamera.prototype.detachControl = function (element) {
  11803. if (this._attachedElement !== element) {
  11804. return;
  11805. }
  11806. element.removeEventListener("contextmenu", this._onContextMenu);
  11807. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11808. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11809. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11810. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11811. element.removeEventListener("mousemove", this._onMouseMove);
  11812. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11813. element.removeEventListener("MSGestureChange", this._onGesture);
  11814. element.removeEventListener('mousewheel', this._wheel);
  11815. element.removeEventListener('DOMMouseScroll', this._wheel);
  11816. BABYLON.Tools.UnregisterTopRootEvents([
  11817. { name: "keydown", handler: this._onKeyDown },
  11818. { name: "keyup", handler: this._onKeyUp },
  11819. { name: "blur", handler: this._onLostFocus }
  11820. ]);
  11821. this._MSGestureHandler = null;
  11822. this._attachedElement = null;
  11823. if (this._reset) {
  11824. this._reset();
  11825. }
  11826. };
  11827. ArcRotateCamera.prototype._checkInputs = function () {
  11828. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11829. if (this._collisionTriggered) {
  11830. return;
  11831. }
  11832. // Keyboard
  11833. for (var index = 0; index < this._keys.length; index++) {
  11834. var keyCode = this._keys[index];
  11835. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11836. this.inertialAlphaOffset -= 0.01;
  11837. }
  11838. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11839. this.inertialBetaOffset -= 0.01;
  11840. }
  11841. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11842. this.inertialAlphaOffset += 0.01;
  11843. }
  11844. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11845. this.inertialBetaOffset += 0.01;
  11846. }
  11847. }
  11848. // Inertia
  11849. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11850. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11851. this.beta += this.inertialBetaOffset;
  11852. this.radius -= this.inertialRadiusOffset;
  11853. this.inertialAlphaOffset *= this.inertia;
  11854. this.inertialBetaOffset *= this.inertia;
  11855. this.inertialRadiusOffset *= this.inertia;
  11856. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11857. this.inertialAlphaOffset = 0;
  11858. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11859. this.inertialBetaOffset = 0;
  11860. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11861. this.inertialRadiusOffset = 0;
  11862. }
  11863. // Panning inertia
  11864. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11865. if (!this._localDirection) {
  11866. this._localDirection = BABYLON.Vector3.Zero();
  11867. this._transformedDirection = BABYLON.Vector3.Zero();
  11868. }
  11869. this.inertialPanningX *= this.inertia;
  11870. this.inertialPanningY *= this.inertia;
  11871. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11872. this.inertialPanningX = 0;
  11873. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11874. this.inertialPanningY = 0;
  11875. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11876. this._localDirection.multiplyInPlace(this.panningAxis);
  11877. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11878. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11879. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  11880. if (!this.panningAxis.y) {
  11881. this._transformedDirection.y = 0;
  11882. }
  11883. this.target.addInPlace(this._transformedDirection);
  11884. }
  11885. // Limits
  11886. this._checkLimits();
  11887. _super.prototype._checkInputs.call(this);
  11888. };
  11889. ArcRotateCamera.prototype._checkLimits = function () {
  11890. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11891. if (this.allowUpsideDown && this.beta > Math.PI) {
  11892. this.beta = this.beta - (2 * Math.PI);
  11893. }
  11894. }
  11895. else {
  11896. if (this.beta < this.lowerBetaLimit) {
  11897. this.beta = this.lowerBetaLimit;
  11898. }
  11899. }
  11900. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11901. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11902. this.beta = this.beta + (2 * Math.PI);
  11903. }
  11904. }
  11905. else {
  11906. if (this.beta > this.upperBetaLimit) {
  11907. this.beta = this.upperBetaLimit;
  11908. }
  11909. }
  11910. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11911. this.alpha = this.lowerAlphaLimit;
  11912. }
  11913. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11914. this.alpha = this.upperAlphaLimit;
  11915. }
  11916. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11917. this.radius = this.lowerRadiusLimit;
  11918. }
  11919. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11920. this.radius = this.upperRadiusLimit;
  11921. }
  11922. };
  11923. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  11924. var radiusv3 = this.position.subtract(this._getTargetPosition());
  11925. this.radius = radiusv3.length();
  11926. // Alpha
  11927. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11928. if (radiusv3.z < 0) {
  11929. this.alpha = 2 * Math.PI - this.alpha;
  11930. }
  11931. // Beta
  11932. this.beta = Math.acos(radiusv3.y / this.radius);
  11933. this._checkLimits();
  11934. };
  11935. ArcRotateCamera.prototype.setPosition = function (position) {
  11936. if (this.position.equals(position)) {
  11937. return;
  11938. }
  11939. this.position = position;
  11940. this.rebuildAnglesAndRadius();
  11941. };
  11942. ArcRotateCamera.prototype.setTarget = function (target) {
  11943. if (this.target.equals(target)) {
  11944. return;
  11945. }
  11946. this.target = target;
  11947. this.rebuildAnglesAndRadius();
  11948. };
  11949. ArcRotateCamera.prototype._getViewMatrix = function () {
  11950. // Compute
  11951. var cosa = Math.cos(this.alpha);
  11952. var sina = Math.sin(this.alpha);
  11953. var cosb = Math.cos(this.beta);
  11954. var sinb = Math.sin(this.beta);
  11955. var target = this._getTargetPosition();
  11956. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11957. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11958. this._collider.radius = this.collisionRadius;
  11959. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11960. this._collisionTriggered = true;
  11961. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11962. }
  11963. else {
  11964. this.position.copyFrom(this._newPosition);
  11965. var up = this.upVector;
  11966. if (this.allowUpsideDown && this.beta < 0) {
  11967. up = up.clone();
  11968. up = up.negate();
  11969. }
  11970. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11971. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11972. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11973. }
  11974. return this._viewMatrix;
  11975. };
  11976. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11977. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11978. meshes = meshes || this.getScene().meshes;
  11979. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11980. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11981. this.radius = distance * this.zoomOnFactor;
  11982. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11983. };
  11984. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11985. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11986. var meshesOrMinMaxVector;
  11987. var distance;
  11988. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11989. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11990. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11991. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11992. }
  11993. else {
  11994. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11995. distance = meshesOrMinMaxVectorAndDistance.distance;
  11996. }
  11997. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11998. if (!doNotUpdateMaxZ) {
  11999. this.maxZ = distance * 2;
  12000. }
  12001. };
  12002. /**
  12003. * @override
  12004. * Override Camera.createRigCamera
  12005. */
  12006. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12007. switch (this.cameraRigMode) {
  12008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12012. case BABYLON.Camera.RIG_MODE_VR:
  12013. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12014. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12015. }
  12016. return null;
  12017. };
  12018. /**
  12019. * @override
  12020. * Override Camera._updateRigCameras
  12021. */
  12022. ArcRotateCamera.prototype._updateRigCameras = function () {
  12023. switch (this.cameraRigMode) {
  12024. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12025. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12028. case BABYLON.Camera.RIG_MODE_VR:
  12029. var camLeft = this._rigCameras[0];
  12030. var camRight = this._rigCameras[1];
  12031. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12032. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12033. camLeft.beta = camRight.beta = this.beta;
  12034. camLeft.radius = camRight.radius = this.radius;
  12035. break;
  12036. }
  12037. _super.prototype._updateRigCameras.call(this);
  12038. };
  12039. ArcRotateCamera.prototype.serialize = function () {
  12040. var serializationObject = _super.prototype.serialize.call(this);
  12041. if (this.target instanceof BABYLON.Vector3) {
  12042. serializationObject.target = this.target.asArray();
  12043. }
  12044. if (this.target && this.target.id) {
  12045. serializationObject.lockedTargetId = this.target.id;
  12046. }
  12047. serializationObject.checkCollisions = this.checkCollisions;
  12048. serializationObject.alpha = this.alpha;
  12049. serializationObject.beta = this.beta;
  12050. serializationObject.radius = this.radius;
  12051. return serializationObject;
  12052. };
  12053. return ArcRotateCamera;
  12054. })(BABYLON.TargetCamera);
  12055. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12056. })(BABYLON || (BABYLON = {}));
  12057. var BABYLON;
  12058. (function (BABYLON) {
  12059. var RenderingManager = (function () {
  12060. function RenderingManager(scene) {
  12061. this._renderingGroups = new Array();
  12062. this._scene = scene;
  12063. }
  12064. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12065. if (this._scene._activeParticleSystems.length === 0) {
  12066. return;
  12067. }
  12068. // Particles
  12069. var activeCamera = this._scene.activeCamera;
  12070. var beforeParticlesDate = BABYLON.Tools.Now;
  12071. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12072. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12073. if (particleSystem.renderingGroupId !== index) {
  12074. continue;
  12075. }
  12076. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12077. continue;
  12078. }
  12079. this._clearDepthBuffer();
  12080. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12081. this._scene._activeParticles += particleSystem.render();
  12082. }
  12083. }
  12084. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12085. };
  12086. RenderingManager.prototype._renderSprites = function (index) {
  12087. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12088. return;
  12089. }
  12090. // Sprites
  12091. var activeCamera = this._scene.activeCamera;
  12092. var beforeSpritessDate = BABYLON.Tools.Now;
  12093. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12094. var spriteManager = this._scene.spriteManagers[id];
  12095. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12096. this._clearDepthBuffer();
  12097. spriteManager.render();
  12098. }
  12099. }
  12100. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12101. };
  12102. RenderingManager.prototype._clearDepthBuffer = function () {
  12103. if (this._depthBufferAlreadyCleaned) {
  12104. return;
  12105. }
  12106. this._scene.getEngine().clear(0, false, true);
  12107. this._depthBufferAlreadyCleaned = true;
  12108. };
  12109. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12110. if (this._currentRenderSprites) {
  12111. this._renderSprites(this._currentIndex);
  12112. }
  12113. if (this._currentRenderParticles) {
  12114. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12115. }
  12116. };
  12117. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12118. this._currentActiveMeshes = activeMeshes;
  12119. this._currentRenderParticles = renderParticles;
  12120. this._currentRenderSprites = renderSprites;
  12121. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12122. this._depthBufferAlreadyCleaned = index == 0;
  12123. var renderingGroup = this._renderingGroups[index];
  12124. var needToStepBack = false;
  12125. this._currentIndex = index;
  12126. if (renderingGroup) {
  12127. this._clearDepthBuffer();
  12128. if (!renderingGroup.onBeforeTransparentRendering) {
  12129. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12130. }
  12131. if (!renderingGroup.render(customRenderFunction)) {
  12132. this._renderingGroups.splice(index, 1);
  12133. needToStepBack = true;
  12134. this._renderSpritesAndParticles();
  12135. }
  12136. }
  12137. else {
  12138. this._renderSpritesAndParticles();
  12139. }
  12140. if (needToStepBack) {
  12141. index--;
  12142. }
  12143. }
  12144. };
  12145. RenderingManager.prototype.reset = function () {
  12146. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12147. if (renderingGroup) {
  12148. renderingGroup.prepare();
  12149. }
  12150. });
  12151. };
  12152. RenderingManager.prototype.dispatch = function (subMesh) {
  12153. var mesh = subMesh.getMesh();
  12154. var renderingGroupId = mesh.renderingGroupId || 0;
  12155. if (!this._renderingGroups[renderingGroupId]) {
  12156. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12157. }
  12158. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12159. };
  12160. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12161. return RenderingManager;
  12162. })();
  12163. BABYLON.RenderingManager = RenderingManager;
  12164. })(BABYLON || (BABYLON = {}));
  12165. var BABYLON;
  12166. (function (BABYLON) {
  12167. var RenderingGroup = (function () {
  12168. function RenderingGroup(index, scene) {
  12169. this.index = index;
  12170. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12171. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12172. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12173. this._scene = scene;
  12174. }
  12175. RenderingGroup.prototype.render = function (customRenderFunction) {
  12176. if (customRenderFunction) {
  12177. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12178. return true;
  12179. }
  12180. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12181. if (this.onBeforeTransparentRendering) {
  12182. this.onBeforeTransparentRendering();
  12183. }
  12184. return false;
  12185. }
  12186. var engine = this._scene.getEngine();
  12187. // Opaque
  12188. var subIndex;
  12189. var submesh;
  12190. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12191. submesh = this._opaqueSubMeshes.data[subIndex];
  12192. submesh.render(false);
  12193. }
  12194. // Alpha test
  12195. engine.setAlphaTesting(true);
  12196. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12197. submesh = this._alphaTestSubMeshes.data[subIndex];
  12198. submesh.render(false);
  12199. }
  12200. engine.setAlphaTesting(false);
  12201. if (this.onBeforeTransparentRendering) {
  12202. this.onBeforeTransparentRendering();
  12203. }
  12204. // Transparent
  12205. if (this._transparentSubMeshes.length) {
  12206. // Sorting
  12207. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12208. submesh = this._transparentSubMeshes.data[subIndex];
  12209. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12210. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12211. }
  12212. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12213. sortedArray.sort(function (a, b) {
  12214. // Alpha index first
  12215. if (a._alphaIndex > b._alphaIndex) {
  12216. return 1;
  12217. }
  12218. if (a._alphaIndex < b._alphaIndex) {
  12219. return -1;
  12220. }
  12221. // Then distance to camera
  12222. if (a._distanceToCamera < b._distanceToCamera) {
  12223. return 1;
  12224. }
  12225. if (a._distanceToCamera > b._distanceToCamera) {
  12226. return -1;
  12227. }
  12228. return 0;
  12229. });
  12230. // Rendering
  12231. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12232. submesh = sortedArray[subIndex];
  12233. submesh.render(true);
  12234. }
  12235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12236. }
  12237. return true;
  12238. };
  12239. RenderingGroup.prototype.prepare = function () {
  12240. this._opaqueSubMeshes.reset();
  12241. this._transparentSubMeshes.reset();
  12242. this._alphaTestSubMeshes.reset();
  12243. };
  12244. RenderingGroup.prototype.dispatch = function (subMesh) {
  12245. var material = subMesh.getMaterial();
  12246. var mesh = subMesh.getMesh();
  12247. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12248. this._transparentSubMeshes.push(subMesh);
  12249. }
  12250. else if (material.needAlphaTesting()) {
  12251. this._alphaTestSubMeshes.push(subMesh);
  12252. }
  12253. else {
  12254. this._opaqueSubMeshes.push(subMesh); // Opaque
  12255. }
  12256. };
  12257. return RenderingGroup;
  12258. })();
  12259. BABYLON.RenderingGroup = RenderingGroup;
  12260. })(BABYLON || (BABYLON = {}));
  12261. var BABYLON;
  12262. (function (BABYLON) {
  12263. /**
  12264. * Represents a scene to be rendered by the engine.
  12265. * @see http://doc.babylonjs.com/page.php?p=21911
  12266. */
  12267. var Scene = (function () {
  12268. /**
  12269. * @constructor
  12270. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12271. */
  12272. function Scene(engine) {
  12273. // Members
  12274. this.autoClear = true;
  12275. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12276. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12277. this.forceWireframe = false;
  12278. this.forcePointsCloud = false;
  12279. this.forceShowBoundingBoxes = false;
  12280. this.animationsEnabled = true;
  12281. this.constantlyUpdateMeshUnderPointer = false;
  12282. // Animations
  12283. this.animations = [];
  12284. 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
  12285. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12286. this._startingPointerTime = 0;
  12287. // Fog
  12288. /**
  12289. * is fog enabled on this scene.
  12290. * @type {boolean}
  12291. */
  12292. this.fogEnabled = true;
  12293. this.fogMode = Scene.FOGMODE_NONE;
  12294. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12295. this.fogDensity = 0.1;
  12296. this.fogStart = 0;
  12297. this.fogEnd = 1000.0;
  12298. // Lights
  12299. /**
  12300. * is shadow enabled on this scene.
  12301. * @type {boolean}
  12302. */
  12303. this.shadowsEnabled = true;
  12304. /**
  12305. * is light enabled on this scene.
  12306. * @type {boolean}
  12307. */
  12308. this.lightsEnabled = true;
  12309. /**
  12310. * All of the lights added to this scene.
  12311. * @see BABYLON.Light
  12312. * @type {BABYLON.Light[]}
  12313. */
  12314. this.lights = new Array();
  12315. // Cameras
  12316. /**
  12317. * All of the cameras added to this scene.
  12318. * @see BABYLON.Camera
  12319. * @type {BABYLON.Camera[]}
  12320. */
  12321. this.cameras = new Array();
  12322. this.activeCameras = new Array();
  12323. // Meshes
  12324. /**
  12325. * All of the (abstract) meshes added to this scene.
  12326. * @see BABYLON.AbstractMesh
  12327. * @type {BABYLON.AbstractMesh[]}
  12328. */
  12329. this.meshes = new Array();
  12330. // Geometries
  12331. this._geometries = new Array();
  12332. this.materials = new Array();
  12333. this.multiMaterials = new Array();
  12334. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12335. // Textures
  12336. this.texturesEnabled = true;
  12337. this.textures = new Array();
  12338. // Particles
  12339. this.particlesEnabled = true;
  12340. this.particleSystems = new Array();
  12341. // Sprites
  12342. this.spritesEnabled = true;
  12343. this.spriteManagers = new Array();
  12344. // Layers
  12345. this.layers = new Array();
  12346. // Skeletons
  12347. this.skeletonsEnabled = true;
  12348. this.skeletons = new Array();
  12349. // Lens flares
  12350. this.lensFlaresEnabled = true;
  12351. this.lensFlareSystems = new Array();
  12352. // Collisions
  12353. this.collisionsEnabled = true;
  12354. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12355. // Postprocesses
  12356. this.postProcessesEnabled = true;
  12357. // Customs render targets
  12358. this.renderTargetsEnabled = true;
  12359. this.dumpNextRenderTargets = false;
  12360. this.customRenderTargets = new Array();
  12361. // Imported meshes
  12362. this.importedMeshesFiles = new Array();
  12363. // Probes
  12364. this.probesEnabled = true;
  12365. this.reflectionProbes = new Array();
  12366. this._actionManagers = new Array();
  12367. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12368. // Procedural textures
  12369. this.proceduralTexturesEnabled = true;
  12370. this._proceduralTextures = new Array();
  12371. this.soundTracks = new Array();
  12372. this._audioEnabled = true;
  12373. this._headphone = false;
  12374. this._totalVertices = 0;
  12375. this._activeIndices = 0;
  12376. this._activeParticles = 0;
  12377. this._lastFrameDuration = 0;
  12378. this._evaluateActiveMeshesDuration = 0;
  12379. this._renderTargetsDuration = 0;
  12380. this._particlesDuration = 0;
  12381. this._renderDuration = 0;
  12382. this._spritesDuration = 0;
  12383. this._animationRatio = 0;
  12384. this._renderId = 0;
  12385. this._executeWhenReadyTimeoutId = -1;
  12386. this._toBeDisposed = new BABYLON.SmartArray(256);
  12387. this._onReadyCallbacks = new Array();
  12388. this._pendingData = []; //ANY
  12389. this._onBeforeRenderCallbacks = new Array();
  12390. this._onAfterRenderCallbacks = new Array();
  12391. this._activeMeshes = new BABYLON.SmartArray(256);
  12392. this._processedMaterials = new BABYLON.SmartArray(256);
  12393. this._renderTargets = new BABYLON.SmartArray(256);
  12394. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12395. this._activeSkeletons = new BABYLON.SmartArray(32);
  12396. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12397. this._activeBones = 0;
  12398. this._activeAnimatables = new Array();
  12399. this._transformMatrix = BABYLON.Matrix.Zero();
  12400. this._edgesRenderers = new BABYLON.SmartArray(16);
  12401. this._uniqueIdCounter = 0;
  12402. this._engine = engine;
  12403. engine.scenes.push(this);
  12404. this._renderingManager = new BABYLON.RenderingManager(this);
  12405. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12406. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12407. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12408. if (BABYLON.OutlineRenderer) {
  12409. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12410. }
  12411. this.attachControl();
  12412. this._debugLayer = new BABYLON.DebugLayer(this);
  12413. if (BABYLON.SoundTrack) {
  12414. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12415. }
  12416. //simplification queue
  12417. if (BABYLON.SimplificationQueue) {
  12418. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12419. }
  12420. //collision coordinator initialization. For now legacy per default.
  12421. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12422. }
  12423. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12424. get: function () {
  12425. return Scene._FOGMODE_NONE;
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12431. get: function () {
  12432. return Scene._FOGMODE_EXP;
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12438. get: function () {
  12439. return Scene._FOGMODE_EXP2;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12445. get: function () {
  12446. return Scene._FOGMODE_LINEAR;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Object.defineProperty(Scene.prototype, "debugLayer", {
  12452. // Properties
  12453. get: function () {
  12454. return this._debugLayer;
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12460. get: function () {
  12461. return this._workerCollisions;
  12462. },
  12463. set: function (enabled) {
  12464. enabled = (enabled && !!Worker);
  12465. this._workerCollisions = enabled;
  12466. if (this.collisionCoordinator) {
  12467. this.collisionCoordinator.destroy();
  12468. }
  12469. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12470. this.collisionCoordinator.init(this);
  12471. },
  12472. enumerable: true,
  12473. configurable: true
  12474. });
  12475. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12476. get: function () {
  12477. return this._selectionOctree;
  12478. },
  12479. enumerable: true,
  12480. configurable: true
  12481. });
  12482. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12483. /**
  12484. * The mesh that is currently under the pointer.
  12485. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12486. */
  12487. get: function () {
  12488. return this._pointerOverMesh;
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Object.defineProperty(Scene.prototype, "pointerX", {
  12494. /**
  12495. * Current on-screen X position of the pointer
  12496. * @return {number} X position of the pointer
  12497. */
  12498. get: function () {
  12499. return this._pointerX;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. Object.defineProperty(Scene.prototype, "pointerY", {
  12505. /**
  12506. * Current on-screen Y position of the pointer
  12507. * @return {number} Y position of the pointer
  12508. */
  12509. get: function () {
  12510. return this._pointerY;
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. Scene.prototype.getCachedMaterial = function () {
  12516. return this._cachedMaterial;
  12517. };
  12518. Scene.prototype.getBoundingBoxRenderer = function () {
  12519. return this._boundingBoxRenderer;
  12520. };
  12521. Scene.prototype.getOutlineRenderer = function () {
  12522. return this._outlineRenderer;
  12523. };
  12524. Scene.prototype.getEngine = function () {
  12525. return this._engine;
  12526. };
  12527. Scene.prototype.getTotalVertices = function () {
  12528. return this._totalVertices;
  12529. };
  12530. Scene.prototype.getActiveIndices = function () {
  12531. return this._activeIndices;
  12532. };
  12533. Scene.prototype.getActiveParticles = function () {
  12534. return this._activeParticles;
  12535. };
  12536. Scene.prototype.getActiveBones = function () {
  12537. return this._activeBones;
  12538. };
  12539. // Stats
  12540. Scene.prototype.getLastFrameDuration = function () {
  12541. return this._lastFrameDuration;
  12542. };
  12543. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12544. return this._evaluateActiveMeshesDuration;
  12545. };
  12546. Scene.prototype.getActiveMeshes = function () {
  12547. return this._activeMeshes;
  12548. };
  12549. Scene.prototype.getRenderTargetsDuration = function () {
  12550. return this._renderTargetsDuration;
  12551. };
  12552. Scene.prototype.getRenderDuration = function () {
  12553. return this._renderDuration;
  12554. };
  12555. Scene.prototype.getParticlesDuration = function () {
  12556. return this._particlesDuration;
  12557. };
  12558. Scene.prototype.getSpritesDuration = function () {
  12559. return this._spritesDuration;
  12560. };
  12561. Scene.prototype.getAnimationRatio = function () {
  12562. return this._animationRatio;
  12563. };
  12564. Scene.prototype.getRenderId = function () {
  12565. return this._renderId;
  12566. };
  12567. Scene.prototype.incrementRenderId = function () {
  12568. this._renderId++;
  12569. };
  12570. Scene.prototype._updatePointerPosition = function (evt) {
  12571. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12572. this._pointerX = evt.clientX - canvasRect.left;
  12573. this._pointerY = evt.clientY - canvasRect.top;
  12574. if (this.cameraToUseForPointers) {
  12575. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12576. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12577. }
  12578. };
  12579. // Pointers handling
  12580. Scene.prototype.attachControl = function () {
  12581. var _this = this;
  12582. var spritePredicate = function (sprite) {
  12583. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12584. };
  12585. this._onPointerMove = function (evt) {
  12586. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12587. return;
  12588. }
  12589. var canvas = _this._engine.getRenderingCanvas();
  12590. _this._updatePointerPosition(evt);
  12591. // Meshes
  12592. 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);
  12593. if (pickResult.hit && pickResult.pickedMesh) {
  12594. _this.setPointerOverSprite(null);
  12595. _this.setPointerOverMesh(pickResult.pickedMesh);
  12596. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12597. canvas.style.cursor = "pointer";
  12598. }
  12599. else {
  12600. canvas.style.cursor = "";
  12601. }
  12602. }
  12603. else {
  12604. _this.setPointerOverMesh(null);
  12605. // Sprites
  12606. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12607. if (pickResult.hit && pickResult.pickedSprite) {
  12608. canvas.style.cursor = "pointer";
  12609. _this.setPointerOverSprite(pickResult.pickedSprite);
  12610. }
  12611. else {
  12612. _this.setPointerOverSprite(null);
  12613. // Restore pointer
  12614. canvas.style.cursor = "";
  12615. }
  12616. }
  12617. if (_this.onPointerMove) {
  12618. _this.onPointerMove(evt, pickResult);
  12619. }
  12620. };
  12621. this._onPointerDown = function (evt) {
  12622. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12623. return;
  12624. }
  12625. _this._updatePointerPosition(evt);
  12626. _this._startingPointerPosition.x = _this._pointerX;
  12627. _this._startingPointerPosition.y = _this._pointerY;
  12628. _this._startingPointerTime = new Date().getTime();
  12629. var predicate = null;
  12630. // Meshes
  12631. _this._pickedDownMesh = null;
  12632. if (!_this.onPointerDown && !_this.onPointerPick) {
  12633. predicate = function (mesh) {
  12634. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12635. };
  12636. }
  12637. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12638. if (pickResult.hit && pickResult.pickedMesh) {
  12639. if (pickResult.pickedMesh.actionManager) {
  12640. _this._pickedDownMesh = pickResult.pickedMesh;
  12641. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12642. switch (evt.button) {
  12643. case 0:
  12644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12645. break;
  12646. case 1:
  12647. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12648. break;
  12649. case 2:
  12650. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12651. break;
  12652. }
  12653. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12654. }
  12655. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12656. var that = _this;
  12657. window.setTimeout(function () {
  12658. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12659. if (pickResult.hit && pickResult.pickedMesh) {
  12660. if (pickResult.pickedMesh.actionManager) {
  12661. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12662. that._startingPointerTime = 0;
  12663. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12664. }
  12665. }
  12666. }
  12667. }, BABYLON.ActionManager.LongPressDelay);
  12668. }
  12669. }
  12670. }
  12671. if (_this.onPointerDown) {
  12672. _this.onPointerDown(evt, pickResult);
  12673. }
  12674. // Sprites
  12675. _this._pickedDownSprite = null;
  12676. if (_this.spriteManagers.length > 0) {
  12677. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12678. if (pickResult.hit && pickResult.pickedSprite) {
  12679. if (pickResult.pickedSprite.actionManager) {
  12680. _this._pickedDownSprite = pickResult.pickedSprite;
  12681. switch (evt.button) {
  12682. case 0:
  12683. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12684. break;
  12685. case 1:
  12686. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12687. break;
  12688. case 2:
  12689. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12690. break;
  12691. }
  12692. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12693. }
  12694. }
  12695. }
  12696. };
  12697. this._onPointerUp = function (evt) {
  12698. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12699. return;
  12700. }
  12701. var predicate = null;
  12702. _this._updatePointerPosition(evt);
  12703. if (!_this.onPointerUp && !_this.onPointerPick) {
  12704. predicate = function (mesh) {
  12705. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12706. };
  12707. }
  12708. // Meshes
  12709. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12710. if (pickResult.hit && pickResult.pickedMesh) {
  12711. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12712. _this.onPointerPick(evt, pickResult);
  12713. }
  12714. if (pickResult.pickedMesh.actionManager) {
  12715. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12716. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12718. }
  12719. }
  12720. }
  12721. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12722. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12723. }
  12724. if (_this.onPointerUp) {
  12725. _this.onPointerUp(evt, pickResult);
  12726. }
  12727. _this._startingPointerTime = 0;
  12728. // Sprites
  12729. if (_this.spriteManagers.length > 0) {
  12730. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12731. if (pickResult.hit && pickResult.pickedSprite) {
  12732. if (pickResult.pickedSprite.actionManager) {
  12733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12734. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12735. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12736. }
  12737. }
  12738. }
  12739. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12740. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12741. }
  12742. }
  12743. };
  12744. this._onKeyDown = function (evt) {
  12745. if (_this.actionManager) {
  12746. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12747. }
  12748. };
  12749. this._onKeyUp = function (evt) {
  12750. if (_this.actionManager) {
  12751. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12752. }
  12753. };
  12754. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12755. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12756. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12757. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12758. // Wheel
  12759. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12760. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12761. BABYLON.Tools.RegisterTopRootEvents([
  12762. { name: "keydown", handler: this._onKeyDown },
  12763. { name: "keyup", handler: this._onKeyUp }
  12764. ]);
  12765. };
  12766. Scene.prototype.detachControl = function () {
  12767. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12768. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12769. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12770. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12771. // Wheel
  12772. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12773. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12774. BABYLON.Tools.UnregisterTopRootEvents([
  12775. { name: "keydown", handler: this._onKeyDown },
  12776. { name: "keyup", handler: this._onKeyUp }
  12777. ]);
  12778. };
  12779. // Ready
  12780. Scene.prototype.isReady = function () {
  12781. if (this._pendingData.length > 0) {
  12782. return false;
  12783. }
  12784. var index;
  12785. for (index = 0; index < this._geometries.length; index++) {
  12786. var geometry = this._geometries[index];
  12787. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12788. return false;
  12789. }
  12790. }
  12791. for (index = 0; index < this.meshes.length; index++) {
  12792. var mesh = this.meshes[index];
  12793. if (!mesh.isReady()) {
  12794. return false;
  12795. }
  12796. var mat = mesh.material;
  12797. if (mat) {
  12798. if (!mat.isReady(mesh)) {
  12799. return false;
  12800. }
  12801. }
  12802. }
  12803. return true;
  12804. };
  12805. Scene.prototype.resetCachedMaterial = function () {
  12806. this._cachedMaterial = null;
  12807. };
  12808. Scene.prototype.registerBeforeRender = function (func) {
  12809. this._onBeforeRenderCallbacks.push(func);
  12810. };
  12811. Scene.prototype.unregisterBeforeRender = function (func) {
  12812. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12813. if (index > -1) {
  12814. this._onBeforeRenderCallbacks.splice(index, 1);
  12815. }
  12816. };
  12817. Scene.prototype.registerAfterRender = function (func) {
  12818. this._onAfterRenderCallbacks.push(func);
  12819. };
  12820. Scene.prototype.unregisterAfterRender = function (func) {
  12821. var index = this._onAfterRenderCallbacks.indexOf(func);
  12822. if (index > -1) {
  12823. this._onAfterRenderCallbacks.splice(index, 1);
  12824. }
  12825. };
  12826. Scene.prototype._addPendingData = function (data) {
  12827. this._pendingData.push(data);
  12828. };
  12829. Scene.prototype._removePendingData = function (data) {
  12830. var index = this._pendingData.indexOf(data);
  12831. if (index !== -1) {
  12832. this._pendingData.splice(index, 1);
  12833. }
  12834. };
  12835. Scene.prototype.getWaitingItemsCount = function () {
  12836. return this._pendingData.length;
  12837. };
  12838. /**
  12839. * Registers a function to be executed when the scene is ready.
  12840. * @param {Function} func - the function to be executed.
  12841. */
  12842. Scene.prototype.executeWhenReady = function (func) {
  12843. var _this = this;
  12844. this._onReadyCallbacks.push(func);
  12845. if (this._executeWhenReadyTimeoutId !== -1) {
  12846. return;
  12847. }
  12848. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12849. _this._checkIsReady();
  12850. }, 150);
  12851. };
  12852. Scene.prototype._checkIsReady = function () {
  12853. var _this = this;
  12854. if (this.isReady()) {
  12855. this._onReadyCallbacks.forEach(function (func) {
  12856. func();
  12857. });
  12858. this._onReadyCallbacks = [];
  12859. this._executeWhenReadyTimeoutId = -1;
  12860. return;
  12861. }
  12862. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12863. _this._checkIsReady();
  12864. }, 150);
  12865. };
  12866. // Animations
  12867. /**
  12868. * Will start the animation sequence of a given target
  12869. * @param target - the target
  12870. * @param {number} from - from which frame should animation start
  12871. * @param {number} to - till which frame should animation run.
  12872. * @param {boolean} [loop] - should the animation loop
  12873. * @param {number} [speedRatio] - the speed in which to run the animation
  12874. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12875. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12876. * @return {BABYLON.Animatable} the animatable object created for this animation
  12877. * @see BABYLON.Animatable
  12878. * @see http://doc.babylonjs.com/page.php?p=22081
  12879. */
  12880. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12881. if (speedRatio === void 0) { speedRatio = 1.0; }
  12882. this.stopAnimation(target);
  12883. if (!animatable) {
  12884. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12885. }
  12886. // Local animations
  12887. if (target.animations) {
  12888. animatable.appendAnimations(target, target.animations);
  12889. }
  12890. // Children animations
  12891. if (target.getAnimatables) {
  12892. var animatables = target.getAnimatables();
  12893. for (var index = 0; index < animatables.length; index++) {
  12894. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12895. }
  12896. }
  12897. return animatable;
  12898. };
  12899. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12900. if (speedRatio === undefined) {
  12901. speedRatio = 1.0;
  12902. }
  12903. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12904. return animatable;
  12905. };
  12906. Scene.prototype.getAnimatableByTarget = function (target) {
  12907. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12908. if (this._activeAnimatables[index].target === target) {
  12909. return this._activeAnimatables[index];
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. Object.defineProperty(Scene.prototype, "Animatables", {
  12915. get: function () {
  12916. return this._activeAnimatables;
  12917. },
  12918. enumerable: true,
  12919. configurable: true
  12920. });
  12921. /**
  12922. * Will stop the animation of the given target
  12923. * @param target - the target
  12924. * @see beginAnimation
  12925. */
  12926. Scene.prototype.stopAnimation = function (target) {
  12927. var animatable = this.getAnimatableByTarget(target);
  12928. if (animatable) {
  12929. animatable.stop();
  12930. }
  12931. };
  12932. Scene.prototype._animate = function () {
  12933. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12934. return;
  12935. }
  12936. if (!this._animationStartDate) {
  12937. if (this._pendingData.length > 0) {
  12938. return;
  12939. }
  12940. this._animationStartDate = BABYLON.Tools.Now;
  12941. }
  12942. // Getting time
  12943. var now = BABYLON.Tools.Now;
  12944. var delay = now - this._animationStartDate;
  12945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12946. this._activeAnimatables[index]._animate(delay);
  12947. }
  12948. };
  12949. // Matrix
  12950. Scene.prototype.getViewMatrix = function () {
  12951. return this._viewMatrix;
  12952. };
  12953. Scene.prototype.getProjectionMatrix = function () {
  12954. return this._projectionMatrix;
  12955. };
  12956. Scene.prototype.getTransformMatrix = function () {
  12957. return this._transformMatrix;
  12958. };
  12959. Scene.prototype.setTransformMatrix = function (view, projection) {
  12960. this._viewMatrix = view;
  12961. this._projectionMatrix = projection;
  12962. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12963. };
  12964. // Methods
  12965. Scene.prototype.addMesh = function (newMesh) {
  12966. newMesh.uniqueId = this._uniqueIdCounter++;
  12967. var position = this.meshes.push(newMesh);
  12968. //notify the collision coordinator
  12969. this.collisionCoordinator.onMeshAdded(newMesh);
  12970. if (this.onNewMeshAdded) {
  12971. this.onNewMeshAdded(newMesh, position, this);
  12972. }
  12973. };
  12974. Scene.prototype.removeMesh = function (toRemove) {
  12975. var index = this.meshes.indexOf(toRemove);
  12976. if (index !== -1) {
  12977. // Remove from the scene if mesh found
  12978. this.meshes.splice(index, 1);
  12979. }
  12980. //notify the collision coordinator
  12981. this.collisionCoordinator.onMeshRemoved(toRemove);
  12982. if (this.onMeshRemoved) {
  12983. this.onMeshRemoved(toRemove);
  12984. }
  12985. return index;
  12986. };
  12987. Scene.prototype.removeSkeleton = function (toRemove) {
  12988. var index = this.skeletons.indexOf(toRemove);
  12989. if (index !== -1) {
  12990. // Remove from the scene if mesh found
  12991. this.skeletons.splice(index, 1);
  12992. }
  12993. return index;
  12994. };
  12995. Scene.prototype.removeLight = function (toRemove) {
  12996. var index = this.lights.indexOf(toRemove);
  12997. if (index !== -1) {
  12998. // Remove from the scene if mesh found
  12999. this.lights.splice(index, 1);
  13000. }
  13001. if (this.onLightRemoved) {
  13002. this.onLightRemoved(toRemove);
  13003. }
  13004. return index;
  13005. };
  13006. Scene.prototype.removeCamera = function (toRemove) {
  13007. var index = this.cameras.indexOf(toRemove);
  13008. if (index !== -1) {
  13009. // Remove from the scene if mesh found
  13010. this.cameras.splice(index, 1);
  13011. }
  13012. // Remove from activeCameras
  13013. var index2 = this.activeCameras.indexOf(toRemove);
  13014. if (index2 !== -1) {
  13015. // Remove from the scene if mesh found
  13016. this.activeCameras.splice(index2, 1);
  13017. }
  13018. // Reset the activeCamera
  13019. if (this.activeCamera === toRemove) {
  13020. if (this.cameras.length > 0) {
  13021. this.activeCamera = this.cameras[0];
  13022. }
  13023. else {
  13024. this.activeCamera = null;
  13025. }
  13026. }
  13027. if (this.onCameraRemoved) {
  13028. this.onCameraRemoved(toRemove);
  13029. }
  13030. return index;
  13031. };
  13032. Scene.prototype.addLight = function (newLight) {
  13033. newLight.uniqueId = this._uniqueIdCounter++;
  13034. var position = this.lights.push(newLight);
  13035. if (this.onNewLightAdded) {
  13036. this.onNewLightAdded(newLight, position, this);
  13037. }
  13038. };
  13039. Scene.prototype.addCamera = function (newCamera) {
  13040. newCamera.uniqueId = this._uniqueIdCounter++;
  13041. var position = this.cameras.push(newCamera);
  13042. if (this.onNewCameraAdded) {
  13043. this.onNewCameraAdded(newCamera, position, this);
  13044. }
  13045. };
  13046. /**
  13047. * Switch active camera
  13048. * @param {Camera} newCamera - new active camera
  13049. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13050. */
  13051. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13052. if (attachControl === void 0) { attachControl = true; }
  13053. var canvas = this._engine.getRenderingCanvas();
  13054. this.activeCamera.detachControl(canvas);
  13055. this.activeCamera = newCamera;
  13056. if (attachControl) {
  13057. newCamera.attachControl(canvas);
  13058. }
  13059. };
  13060. /**
  13061. * sets the active camera of the scene using its ID
  13062. * @param {string} id - the camera's ID
  13063. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13064. * @see activeCamera
  13065. */
  13066. Scene.prototype.setActiveCameraByID = function (id) {
  13067. var camera = this.getCameraByID(id);
  13068. if (camera) {
  13069. this.activeCamera = camera;
  13070. return camera;
  13071. }
  13072. return null;
  13073. };
  13074. /**
  13075. * sets the active camera of the scene using its name
  13076. * @param {string} name - the camera's name
  13077. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13078. * @see activeCamera
  13079. */
  13080. Scene.prototype.setActiveCameraByName = function (name) {
  13081. var camera = this.getCameraByName(name);
  13082. if (camera) {
  13083. this.activeCamera = camera;
  13084. return camera;
  13085. }
  13086. return null;
  13087. };
  13088. /**
  13089. * get a material using its id
  13090. * @param {string} the material's ID
  13091. * @return {BABYLON.Material|null} the material or null if none found.
  13092. */
  13093. Scene.prototype.getMaterialByID = function (id) {
  13094. for (var index = 0; index < this.materials.length; index++) {
  13095. if (this.materials[index].id === id) {
  13096. return this.materials[index];
  13097. }
  13098. }
  13099. return null;
  13100. };
  13101. /**
  13102. * get a material using its name
  13103. * @param {string} the material's name
  13104. * @return {BABYLON.Material|null} the material or null if none found.
  13105. */
  13106. Scene.prototype.getMaterialByName = function (name) {
  13107. for (var index = 0; index < this.materials.length; index++) {
  13108. if (this.materials[index].name === name) {
  13109. return this.materials[index];
  13110. }
  13111. }
  13112. return null;
  13113. };
  13114. Scene.prototype.getLensFlareSystemByName = function (name) {
  13115. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13116. if (this.lensFlareSystems[index].name === name) {
  13117. return this.lensFlareSystems[index];
  13118. }
  13119. }
  13120. return null;
  13121. };
  13122. Scene.prototype.getCameraByID = function (id) {
  13123. for (var index = 0; index < this.cameras.length; index++) {
  13124. if (this.cameras[index].id === id) {
  13125. return this.cameras[index];
  13126. }
  13127. }
  13128. return null;
  13129. };
  13130. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13131. for (var index = 0; index < this.cameras.length; index++) {
  13132. if (this.cameras[index].uniqueId === uniqueId) {
  13133. return this.cameras[index];
  13134. }
  13135. }
  13136. return null;
  13137. };
  13138. /**
  13139. * get a camera using its name
  13140. * @param {string} the camera's name
  13141. * @return {BABYLON.Camera|null} the camera or null if none found.
  13142. */
  13143. Scene.prototype.getCameraByName = function (name) {
  13144. for (var index = 0; index < this.cameras.length; index++) {
  13145. if (this.cameras[index].name === name) {
  13146. return this.cameras[index];
  13147. }
  13148. }
  13149. return null;
  13150. };
  13151. /**
  13152. * get a bone using its id
  13153. * @param {string} the bone's id
  13154. * @return {BABYLON.Bone|null} the bone or null if not found
  13155. */
  13156. Scene.prototype.getBoneByID = function (id) {
  13157. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13158. var skeleton = this.skeletons[skeletonIndex];
  13159. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13160. if (skeleton.bones[boneIndex].id === id) {
  13161. return skeleton.bones[boneIndex];
  13162. }
  13163. }
  13164. }
  13165. return null;
  13166. };
  13167. /**
  13168. * get a bone using its id
  13169. * @param {string} the bone's name
  13170. * @return {BABYLON.Bone|null} the bone or null if not found
  13171. */
  13172. Scene.prototype.getBoneByName = function (name) {
  13173. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13174. var skeleton = this.skeletons[skeletonIndex];
  13175. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13176. if (skeleton.bones[boneIndex].name === name) {
  13177. return skeleton.bones[boneIndex];
  13178. }
  13179. }
  13180. }
  13181. return null;
  13182. };
  13183. /**
  13184. * get a light node using its name
  13185. * @param {string} the light's name
  13186. * @return {BABYLON.Light|null} the light or null if none found.
  13187. */
  13188. Scene.prototype.getLightByName = function (name) {
  13189. for (var index = 0; index < this.lights.length; index++) {
  13190. if (this.lights[index].name === name) {
  13191. return this.lights[index];
  13192. }
  13193. }
  13194. return null;
  13195. };
  13196. /**
  13197. * get a light node using its ID
  13198. * @param {string} the light's id
  13199. * @return {BABYLON.Light|null} the light or null if none found.
  13200. */
  13201. Scene.prototype.getLightByID = function (id) {
  13202. for (var index = 0; index < this.lights.length; index++) {
  13203. if (this.lights[index].id === id) {
  13204. return this.lights[index];
  13205. }
  13206. }
  13207. return null;
  13208. };
  13209. /**
  13210. * get a light node using its scene-generated unique ID
  13211. * @param {number} the light's unique id
  13212. * @return {BABYLON.Light|null} the light or null if none found.
  13213. */
  13214. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13215. for (var index = 0; index < this.lights.length; index++) {
  13216. if (this.lights[index].uniqueId === uniqueId) {
  13217. return this.lights[index];
  13218. }
  13219. }
  13220. return null;
  13221. };
  13222. /**
  13223. * get a particle system by id
  13224. * @param id {number} the particle system id
  13225. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13226. */
  13227. Scene.prototype.getParticleSystemByID = function (id) {
  13228. for (var index = 0; index < this.particleSystems.length; index++) {
  13229. if (this.particleSystems[index].id === id) {
  13230. return this.particleSystems[index];
  13231. }
  13232. }
  13233. return null;
  13234. };
  13235. /**
  13236. * get a geometry using its ID
  13237. * @param {string} the geometry's id
  13238. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13239. */
  13240. Scene.prototype.getGeometryByID = function (id) {
  13241. for (var index = 0; index < this._geometries.length; index++) {
  13242. if (this._geometries[index].id === id) {
  13243. return this._geometries[index];
  13244. }
  13245. }
  13246. return null;
  13247. };
  13248. /**
  13249. * add a new geometry to this scene.
  13250. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13251. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13252. * @return {boolean} was the geometry added or not
  13253. */
  13254. Scene.prototype.pushGeometry = function (geometry, force) {
  13255. if (!force && this.getGeometryByID(geometry.id)) {
  13256. return false;
  13257. }
  13258. this._geometries.push(geometry);
  13259. //notify the collision coordinator
  13260. this.collisionCoordinator.onGeometryAdded(geometry);
  13261. if (this.onGeometryAdded) {
  13262. this.onGeometryAdded(geometry);
  13263. }
  13264. return true;
  13265. };
  13266. /**
  13267. * Removes an existing geometry
  13268. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13269. * @return {boolean} was the geometry removed or not
  13270. */
  13271. Scene.prototype.removeGeometry = function (geometry) {
  13272. var index = this._geometries.indexOf(geometry);
  13273. if (index > -1) {
  13274. this._geometries.splice(index, 1);
  13275. //notify the collision coordinator
  13276. this.collisionCoordinator.onGeometryDeleted(geometry);
  13277. if (this.onGeometryRemoved) {
  13278. this.onGeometryRemoved(geometry);
  13279. }
  13280. return true;
  13281. }
  13282. return false;
  13283. };
  13284. Scene.prototype.getGeometries = function () {
  13285. return this._geometries;
  13286. };
  13287. /**
  13288. * Get the first added mesh found of a given ID
  13289. * @param {string} id - the id to search for
  13290. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13291. */
  13292. Scene.prototype.getMeshByID = function (id) {
  13293. for (var index = 0; index < this.meshes.length; index++) {
  13294. if (this.meshes[index].id === id) {
  13295. return this.meshes[index];
  13296. }
  13297. }
  13298. return null;
  13299. };
  13300. /**
  13301. * Get a mesh with its auto-generated unique id
  13302. * @param {number} uniqueId - the unique id to search for
  13303. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13304. */
  13305. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13306. for (var index = 0; index < this.meshes.length; index++) {
  13307. if (this.meshes[index].uniqueId === uniqueId) {
  13308. return this.meshes[index];
  13309. }
  13310. }
  13311. return null;
  13312. };
  13313. /**
  13314. * Get a the last added mesh found of a given ID
  13315. * @param {string} id - the id to search for
  13316. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13317. */
  13318. Scene.prototype.getLastMeshByID = function (id) {
  13319. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13320. if (this.meshes[index].id === id) {
  13321. return this.meshes[index];
  13322. }
  13323. }
  13324. return null;
  13325. };
  13326. /**
  13327. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13328. * @param {string} id - the id to search for
  13329. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13330. */
  13331. Scene.prototype.getLastEntryByID = function (id) {
  13332. var index;
  13333. for (index = this.meshes.length - 1; index >= 0; index--) {
  13334. if (this.meshes[index].id === id) {
  13335. return this.meshes[index];
  13336. }
  13337. }
  13338. for (index = this.cameras.length - 1; index >= 0; index--) {
  13339. if (this.cameras[index].id === id) {
  13340. return this.cameras[index];
  13341. }
  13342. }
  13343. for (index = this.lights.length - 1; index >= 0; index--) {
  13344. if (this.lights[index].id === id) {
  13345. return this.lights[index];
  13346. }
  13347. }
  13348. return null;
  13349. };
  13350. Scene.prototype.getNodeByID = function (id) {
  13351. var mesh = this.getMeshByID(id);
  13352. if (mesh) {
  13353. return mesh;
  13354. }
  13355. var light = this.getLightByID(id);
  13356. if (light) {
  13357. return light;
  13358. }
  13359. var camera = this.getCameraByID(id);
  13360. if (camera) {
  13361. return camera;
  13362. }
  13363. var bone = this.getBoneByID(id);
  13364. return bone;
  13365. };
  13366. Scene.prototype.getNodeByName = function (name) {
  13367. var mesh = this.getMeshByName(name);
  13368. if (mesh) {
  13369. return mesh;
  13370. }
  13371. var light = this.getLightByName(name);
  13372. if (light) {
  13373. return light;
  13374. }
  13375. var camera = this.getCameraByName(name);
  13376. if (camera) {
  13377. return camera;
  13378. }
  13379. var bone = this.getBoneByName(name);
  13380. return bone;
  13381. };
  13382. Scene.prototype.getMeshByName = function (name) {
  13383. for (var index = 0; index < this.meshes.length; index++) {
  13384. if (this.meshes[index].name === name) {
  13385. return this.meshes[index];
  13386. }
  13387. }
  13388. return null;
  13389. };
  13390. Scene.prototype.getSoundByName = function (name) {
  13391. var index;
  13392. if (BABYLON.AudioEngine) {
  13393. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13394. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13395. return this.mainSoundTrack.soundCollection[index];
  13396. }
  13397. }
  13398. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13399. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13400. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13401. return this.soundTracks[sdIndex].soundCollection[index];
  13402. }
  13403. }
  13404. }
  13405. }
  13406. return null;
  13407. };
  13408. Scene.prototype.getLastSkeletonByID = function (id) {
  13409. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13410. if (this.skeletons[index].id === id) {
  13411. return this.skeletons[index];
  13412. }
  13413. }
  13414. return null;
  13415. };
  13416. Scene.prototype.getSkeletonById = function (id) {
  13417. for (var index = 0; index < this.skeletons.length; index++) {
  13418. if (this.skeletons[index].id === id) {
  13419. return this.skeletons[index];
  13420. }
  13421. }
  13422. return null;
  13423. };
  13424. Scene.prototype.getSkeletonByName = function (name) {
  13425. for (var index = 0; index < this.skeletons.length; index++) {
  13426. if (this.skeletons[index].name === name) {
  13427. return this.skeletons[index];
  13428. }
  13429. }
  13430. return null;
  13431. };
  13432. Scene.prototype.isActiveMesh = function (mesh) {
  13433. return (this._activeMeshes.indexOf(mesh) !== -1);
  13434. };
  13435. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13436. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13437. var material = subMesh.getMaterial();
  13438. if (mesh.showSubMeshesBoundingBox) {
  13439. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13440. }
  13441. if (material) {
  13442. // Render targets
  13443. if (material.getRenderTargetTextures) {
  13444. if (this._processedMaterials.indexOf(material) === -1) {
  13445. this._processedMaterials.push(material);
  13446. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13447. }
  13448. }
  13449. // Dispatch
  13450. this._activeIndices += subMesh.indexCount;
  13451. this._renderingManager.dispatch(subMesh);
  13452. }
  13453. }
  13454. };
  13455. Scene.prototype._evaluateActiveMeshes = function () {
  13456. this.activeCamera._activeMeshes.reset();
  13457. this._activeMeshes.reset();
  13458. this._renderingManager.reset();
  13459. this._processedMaterials.reset();
  13460. this._activeParticleSystems.reset();
  13461. this._activeSkeletons.reset();
  13462. this._softwareSkinnedMeshes.reset();
  13463. this._boundingBoxRenderer.reset();
  13464. this._edgesRenderers.reset();
  13465. if (!this._frustumPlanes) {
  13466. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13467. }
  13468. else {
  13469. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13470. }
  13471. // Meshes
  13472. var meshes;
  13473. var len;
  13474. if (this._selectionOctree) {
  13475. var selection = this._selectionOctree.select(this._frustumPlanes);
  13476. meshes = selection.data;
  13477. len = selection.length;
  13478. }
  13479. else {
  13480. len = this.meshes.length;
  13481. meshes = this.meshes;
  13482. }
  13483. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13484. var mesh = meshes[meshIndex];
  13485. if (mesh.isBlocked) {
  13486. continue;
  13487. }
  13488. this._totalVertices += mesh.getTotalVertices();
  13489. if (!mesh.isReady() || !mesh.isEnabled()) {
  13490. continue;
  13491. }
  13492. mesh.computeWorldMatrix();
  13493. // Intersections
  13494. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13495. this._meshesForIntersections.pushNoDuplicate(mesh);
  13496. }
  13497. // Switch to current LOD
  13498. var meshLOD = mesh.getLOD(this.activeCamera);
  13499. if (!meshLOD) {
  13500. continue;
  13501. }
  13502. mesh._preActivate();
  13503. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13504. this._activeMeshes.push(mesh);
  13505. this.activeCamera._activeMeshes.push(mesh);
  13506. mesh._activate(this._renderId);
  13507. this._activeMesh(meshLOD);
  13508. }
  13509. }
  13510. // Particle systems
  13511. var beforeParticlesDate = BABYLON.Tools.Now;
  13512. if (this.particlesEnabled) {
  13513. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13514. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13515. var particleSystem = this.particleSystems[particleIndex];
  13516. if (!particleSystem.isStarted()) {
  13517. continue;
  13518. }
  13519. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13520. this._activeParticleSystems.push(particleSystem);
  13521. particleSystem.animate();
  13522. }
  13523. }
  13524. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13525. }
  13526. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13527. };
  13528. Scene.prototype._activeMesh = function (mesh) {
  13529. if (mesh.skeleton && this.skeletonsEnabled) {
  13530. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13531. if (!mesh.computeBonesUsingShaders) {
  13532. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13533. }
  13534. }
  13535. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13536. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13537. }
  13538. if (mesh._edgesRenderer) {
  13539. this._edgesRenderers.push(mesh._edgesRenderer);
  13540. }
  13541. if (mesh && mesh.subMeshes) {
  13542. // Submeshes Octrees
  13543. var len;
  13544. var subMeshes;
  13545. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13546. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13547. len = intersections.length;
  13548. subMeshes = intersections.data;
  13549. }
  13550. else {
  13551. subMeshes = mesh.subMeshes;
  13552. len = subMeshes.length;
  13553. }
  13554. for (var subIndex = 0; subIndex < len; subIndex++) {
  13555. var subMesh = subMeshes[subIndex];
  13556. this._evaluateSubMesh(subMesh, mesh);
  13557. }
  13558. }
  13559. };
  13560. Scene.prototype.updateTransformMatrix = function (force) {
  13561. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13562. };
  13563. Scene.prototype._renderForCamera = function (camera) {
  13564. var engine = this._engine;
  13565. this.activeCamera = camera;
  13566. if (!this.activeCamera)
  13567. throw new Error("Active camera not set");
  13568. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13569. // Viewport
  13570. engine.setViewport(this.activeCamera.viewport);
  13571. // Camera
  13572. this.resetCachedMaterial();
  13573. this._renderId++;
  13574. this.updateTransformMatrix();
  13575. if (this.beforeCameraRender) {
  13576. this.beforeCameraRender(this.activeCamera);
  13577. }
  13578. // Meshes
  13579. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13580. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13581. this._evaluateActiveMeshes();
  13582. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13583. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13584. // Skeletons
  13585. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13586. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13587. skeleton.prepare();
  13588. }
  13589. // Software skinning
  13590. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13591. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13592. mesh.applySkeleton(mesh.skeleton);
  13593. }
  13594. // Render targets
  13595. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13596. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13597. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13598. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13599. var renderTarget = this._renderTargets.data[renderIndex];
  13600. if (renderTarget._shouldRender()) {
  13601. this._renderId++;
  13602. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13603. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13604. }
  13605. }
  13606. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13607. this._renderId++;
  13608. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13609. }
  13610. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13611. // Prepare Frame
  13612. this.postProcessManager._prepareFrame();
  13613. var beforeRenderDate = BABYLON.Tools.Now;
  13614. // Backgrounds
  13615. var layerIndex;
  13616. var layer;
  13617. if (this.layers.length) {
  13618. engine.setDepthBuffer(false);
  13619. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13620. layer = this.layers[layerIndex];
  13621. if (layer.isBackground) {
  13622. layer.render();
  13623. }
  13624. }
  13625. engine.setDepthBuffer(true);
  13626. }
  13627. // Render
  13628. BABYLON.Tools.StartPerformanceCounter("Main render");
  13629. this._renderingManager.render(null, null, true, true);
  13630. BABYLON.Tools.EndPerformanceCounter("Main render");
  13631. // Bounding boxes
  13632. this._boundingBoxRenderer.render();
  13633. // Edges
  13634. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13635. this._edgesRenderers.data[edgesRendererIndex].render();
  13636. }
  13637. // Lens flares
  13638. if (this.lensFlaresEnabled) {
  13639. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13640. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13641. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13642. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13643. lensFlareSystem.render();
  13644. }
  13645. }
  13646. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13647. }
  13648. // Foregrounds
  13649. if (this.layers.length) {
  13650. engine.setDepthBuffer(false);
  13651. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13652. layer = this.layers[layerIndex];
  13653. if (!layer.isBackground) {
  13654. layer.render();
  13655. }
  13656. }
  13657. engine.setDepthBuffer(true);
  13658. }
  13659. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13660. // Finalize frame
  13661. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13662. // Update camera
  13663. this.activeCamera._updateFromScene();
  13664. // Reset some special arrays
  13665. this._renderTargets.reset();
  13666. if (this.afterCameraRender) {
  13667. this.afterCameraRender(this.activeCamera);
  13668. }
  13669. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13670. };
  13671. Scene.prototype._processSubCameras = function (camera) {
  13672. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13673. this._renderForCamera(camera);
  13674. return;
  13675. }
  13676. // rig cameras
  13677. for (var index = 0; index < camera._rigCameras.length; index++) {
  13678. this._renderForCamera(camera._rigCameras[index]);
  13679. }
  13680. this.activeCamera = camera;
  13681. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13682. // Update camera
  13683. this.activeCamera._updateFromScene();
  13684. };
  13685. Scene.prototype._checkIntersections = function () {
  13686. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13687. var sourceMesh = this._meshesForIntersections.data[index];
  13688. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13689. var action = sourceMesh.actionManager.actions[actionIndex];
  13690. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13691. var parameters = action.getTriggerParameter();
  13692. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13693. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13694. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13695. if (areIntersecting && currentIntersectionInProgress === -1) {
  13696. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13697. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13698. sourceMesh._intersectionsInProgress.push(otherMesh);
  13699. }
  13700. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13701. sourceMesh._intersectionsInProgress.push(otherMesh);
  13702. }
  13703. }
  13704. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13705. //They intersected, and now they don't.
  13706. //is this trigger an exit trigger? execute an event.
  13707. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13708. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13709. }
  13710. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13711. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13712. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13713. }
  13714. }
  13715. }
  13716. }
  13717. }
  13718. };
  13719. Scene.prototype.render = function () {
  13720. var startDate = BABYLON.Tools.Now;
  13721. this._particlesDuration = 0;
  13722. this._spritesDuration = 0;
  13723. this._activeParticles = 0;
  13724. this._renderDuration = 0;
  13725. this._renderTargetsDuration = 0;
  13726. this._evaluateActiveMeshesDuration = 0;
  13727. this._totalVertices = 0;
  13728. this._activeIndices = 0;
  13729. this._activeBones = 0;
  13730. this.getEngine().resetDrawCalls();
  13731. this._meshesForIntersections.reset();
  13732. this.resetCachedMaterial();
  13733. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13734. // Actions
  13735. if (this.actionManager) {
  13736. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13737. }
  13738. //Simplification Queue
  13739. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13740. this.simplificationQueue.executeNext();
  13741. }
  13742. // Animations
  13743. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13744. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13745. this._animate();
  13746. // Physics
  13747. if (this._physicsEngine) {
  13748. BABYLON.Tools.StartPerformanceCounter("Physics");
  13749. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13750. BABYLON.Tools.EndPerformanceCounter("Physics");
  13751. }
  13752. // Before render
  13753. if (this.beforeRender) {
  13754. this.beforeRender();
  13755. }
  13756. var callbackIndex;
  13757. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13758. this._onBeforeRenderCallbacks[callbackIndex]();
  13759. }
  13760. // Customs render targets
  13761. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13762. var engine = this.getEngine();
  13763. var currentActiveCamera = this.activeCamera;
  13764. if (this.renderTargetsEnabled) {
  13765. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13766. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13767. var renderTarget = this.customRenderTargets[customIndex];
  13768. if (renderTarget._shouldRender()) {
  13769. this._renderId++;
  13770. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13771. if (!this.activeCamera)
  13772. throw new Error("Active camera not set");
  13773. // Viewport
  13774. engine.setViewport(this.activeCamera.viewport);
  13775. // Camera
  13776. this.updateTransformMatrix();
  13777. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13778. }
  13779. }
  13780. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13781. this._renderId++;
  13782. }
  13783. if (this.customRenderTargets.length > 0) {
  13784. engine.restoreDefaultFramebuffer();
  13785. }
  13786. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13787. this.activeCamera = currentActiveCamera;
  13788. // Procedural textures
  13789. if (this.proceduralTexturesEnabled) {
  13790. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13791. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13792. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13793. if (proceduralTexture._shouldRender()) {
  13794. proceduralTexture.render();
  13795. }
  13796. }
  13797. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13798. }
  13799. // Clear
  13800. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13801. // Shadows
  13802. if (this.shadowsEnabled) {
  13803. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13804. var light = this.lights[lightIndex];
  13805. var shadowGenerator = light.getShadowGenerator();
  13806. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13807. this._renderTargets.push(shadowGenerator.getShadowMap());
  13808. }
  13809. }
  13810. }
  13811. // Depth renderer
  13812. if (this._depthRenderer) {
  13813. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13814. }
  13815. // RenderPipeline
  13816. this.postProcessRenderPipelineManager.update();
  13817. // Multi-cameras?
  13818. if (this.activeCameras.length > 0) {
  13819. var currentRenderId = this._renderId;
  13820. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13821. this._renderId = currentRenderId;
  13822. if (cameraIndex > 0) {
  13823. this._engine.clear(0, false, true);
  13824. }
  13825. this._processSubCameras(this.activeCameras[cameraIndex]);
  13826. }
  13827. }
  13828. else {
  13829. if (!this.activeCamera) {
  13830. throw new Error("No camera defined");
  13831. }
  13832. this._processSubCameras(this.activeCamera);
  13833. }
  13834. // Intersection checks
  13835. this._checkIntersections();
  13836. // Update the audio listener attached to the camera
  13837. if (BABYLON.AudioEngine) {
  13838. this._updateAudioParameters();
  13839. }
  13840. // After render
  13841. if (this.afterRender) {
  13842. this.afterRender();
  13843. }
  13844. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13845. this._onAfterRenderCallbacks[callbackIndex]();
  13846. }
  13847. // Cleaning
  13848. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13849. this._toBeDisposed.data[index].dispose();
  13850. this._toBeDisposed[index] = null;
  13851. }
  13852. this._toBeDisposed.reset();
  13853. if (this.dumpNextRenderTargets) {
  13854. this.dumpNextRenderTargets = false;
  13855. }
  13856. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13857. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13858. };
  13859. Scene.prototype._updateAudioParameters = function () {
  13860. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13861. return;
  13862. }
  13863. var listeningCamera;
  13864. var audioEngine = BABYLON.Engine.audioEngine;
  13865. if (this.activeCameras.length > 0) {
  13866. listeningCamera = this.activeCameras[0];
  13867. }
  13868. else {
  13869. listeningCamera = this.activeCamera;
  13870. }
  13871. if (listeningCamera && audioEngine.canUseWebAudio) {
  13872. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13873. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13874. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13875. cameraDirection.normalize();
  13876. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13877. var i;
  13878. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13879. var sound = this.mainSoundTrack.soundCollection[i];
  13880. if (sound.useCustomAttenuation) {
  13881. sound.updateDistanceFromListener();
  13882. }
  13883. }
  13884. for (i = 0; i < this.soundTracks.length; i++) {
  13885. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13886. sound = this.soundTracks[i].soundCollection[j];
  13887. if (sound.useCustomAttenuation) {
  13888. sound.updateDistanceFromListener();
  13889. }
  13890. }
  13891. }
  13892. }
  13893. };
  13894. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13895. // Audio
  13896. get: function () {
  13897. return this._audioEnabled;
  13898. },
  13899. set: function (value) {
  13900. this._audioEnabled = value;
  13901. if (BABYLON.AudioEngine) {
  13902. if (this._audioEnabled) {
  13903. this._enableAudio();
  13904. }
  13905. else {
  13906. this._disableAudio();
  13907. }
  13908. }
  13909. },
  13910. enumerable: true,
  13911. configurable: true
  13912. });
  13913. Scene.prototype._disableAudio = function () {
  13914. var i;
  13915. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13916. this.mainSoundTrack.soundCollection[i].pause();
  13917. }
  13918. for (i = 0; i < this.soundTracks.length; i++) {
  13919. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13920. this.soundTracks[i].soundCollection[j].pause();
  13921. }
  13922. }
  13923. };
  13924. Scene.prototype._enableAudio = function () {
  13925. var i;
  13926. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13927. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13928. this.mainSoundTrack.soundCollection[i].play();
  13929. }
  13930. }
  13931. for (i = 0; i < this.soundTracks.length; i++) {
  13932. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13933. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13934. this.soundTracks[i].soundCollection[j].play();
  13935. }
  13936. }
  13937. }
  13938. };
  13939. Object.defineProperty(Scene.prototype, "headphone", {
  13940. get: function () {
  13941. return this._headphone;
  13942. },
  13943. set: function (value) {
  13944. this._headphone = value;
  13945. if (BABYLON.AudioEngine) {
  13946. if (this._headphone) {
  13947. this._switchAudioModeForHeadphones();
  13948. }
  13949. else {
  13950. this._switchAudioModeForNormalSpeakers();
  13951. }
  13952. }
  13953. },
  13954. enumerable: true,
  13955. configurable: true
  13956. });
  13957. Scene.prototype._switchAudioModeForHeadphones = function () {
  13958. this.mainSoundTrack.switchPanningModelToHRTF();
  13959. for (var i = 0; i < this.soundTracks.length; i++) {
  13960. this.soundTracks[i].switchPanningModelToHRTF();
  13961. }
  13962. };
  13963. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13964. this.mainSoundTrack.switchPanningModelToEqualPower();
  13965. for (var i = 0; i < this.soundTracks.length; i++) {
  13966. this.soundTracks[i].switchPanningModelToEqualPower();
  13967. }
  13968. };
  13969. Scene.prototype.enableDepthRenderer = function () {
  13970. if (this._depthRenderer) {
  13971. return this._depthRenderer;
  13972. }
  13973. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13974. return this._depthRenderer;
  13975. };
  13976. Scene.prototype.disableDepthRenderer = function () {
  13977. if (!this._depthRenderer) {
  13978. return;
  13979. }
  13980. this._depthRenderer.dispose();
  13981. this._depthRenderer = null;
  13982. };
  13983. Scene.prototype.freezeMaterials = function () {
  13984. for (var i = 0; i < this.materials.length; i++) {
  13985. this.materials[i].freeze();
  13986. }
  13987. };
  13988. Scene.prototype.unfreezeMaterials = function () {
  13989. for (var i = 0; i < this.materials.length; i++) {
  13990. this.materials[i].unfreeze();
  13991. }
  13992. };
  13993. Scene.prototype.dispose = function () {
  13994. this.beforeRender = null;
  13995. this.afterRender = null;
  13996. this.skeletons = [];
  13997. this._boundingBoxRenderer.dispose();
  13998. if (this._depthRenderer) {
  13999. this._depthRenderer.dispose();
  14000. }
  14001. // Debug layer
  14002. this.debugLayer.hide();
  14003. // Events
  14004. if (this.onDispose) {
  14005. this.onDispose();
  14006. }
  14007. this._onBeforeRenderCallbacks = [];
  14008. this._onAfterRenderCallbacks = [];
  14009. this.detachControl();
  14010. // Release sounds & sounds tracks
  14011. if (BABYLON.AudioEngine) {
  14012. this.disposeSounds();
  14013. }
  14014. // Detach cameras
  14015. var canvas = this._engine.getRenderingCanvas();
  14016. var index;
  14017. for (index = 0; index < this.cameras.length; index++) {
  14018. this.cameras[index].detachControl(canvas);
  14019. }
  14020. // Release lights
  14021. while (this.lights.length) {
  14022. this.lights[0].dispose();
  14023. }
  14024. // Release meshes
  14025. while (this.meshes.length) {
  14026. this.meshes[0].dispose(true);
  14027. }
  14028. // Release cameras
  14029. while (this.cameras.length) {
  14030. this.cameras[0].dispose();
  14031. }
  14032. // Release materials
  14033. while (this.materials.length) {
  14034. this.materials[0].dispose();
  14035. }
  14036. // Release particles
  14037. while (this.particleSystems.length) {
  14038. this.particleSystems[0].dispose();
  14039. }
  14040. // Release sprites
  14041. while (this.spriteManagers.length) {
  14042. this.spriteManagers[0].dispose();
  14043. }
  14044. // Release layers
  14045. while (this.layers.length) {
  14046. this.layers[0].dispose();
  14047. }
  14048. // Release textures
  14049. while (this.textures.length) {
  14050. this.textures[0].dispose();
  14051. }
  14052. // Post-processes
  14053. this.postProcessManager.dispose();
  14054. // Physics
  14055. if (this._physicsEngine) {
  14056. this.disablePhysicsEngine();
  14057. }
  14058. // Remove from engine
  14059. index = this._engine.scenes.indexOf(this);
  14060. if (index > -1) {
  14061. this._engine.scenes.splice(index, 1);
  14062. }
  14063. this._engine.wipeCaches();
  14064. };
  14065. // Release sounds & sounds tracks
  14066. Scene.prototype.disposeSounds = function () {
  14067. this.mainSoundTrack.dispose();
  14068. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14069. this.soundTracks[scIndex].dispose();
  14070. }
  14071. };
  14072. // Octrees
  14073. Scene.prototype.getWorldExtends = function () {
  14074. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14075. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14076. for (var index = 0; index < this.meshes.length; index++) {
  14077. var mesh = this.meshes[index];
  14078. mesh.computeWorldMatrix(true);
  14079. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14080. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14081. BABYLON.Tools.CheckExtends(minBox, min, max);
  14082. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14083. }
  14084. return {
  14085. min: min,
  14086. max: max
  14087. };
  14088. };
  14089. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14090. if (maxCapacity === void 0) { maxCapacity = 64; }
  14091. if (maxDepth === void 0) { maxDepth = 2; }
  14092. if (!this._selectionOctree) {
  14093. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14094. }
  14095. var worldExtends = this.getWorldExtends();
  14096. // Update octree
  14097. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14098. return this._selectionOctree;
  14099. };
  14100. // Picking
  14101. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14102. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14103. var engine = this._engine;
  14104. if (!camera) {
  14105. if (!this.activeCamera)
  14106. throw new Error("Active camera not set");
  14107. camera = this.activeCamera;
  14108. }
  14109. var cameraViewport = camera.viewport;
  14110. var viewport = cameraViewport.toGlobal(engine);
  14111. // Moving coordinates to local viewport world
  14112. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14113. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14114. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14115. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14116. };
  14117. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14118. var engine = this._engine;
  14119. if (!camera) {
  14120. if (!this.activeCamera)
  14121. throw new Error("Active camera not set");
  14122. camera = this.activeCamera;
  14123. }
  14124. var cameraViewport = camera.viewport;
  14125. var viewport = cameraViewport.toGlobal(engine);
  14126. var identity = BABYLON.Matrix.Identity();
  14127. // Moving coordinates to local viewport world
  14128. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14129. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14130. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14131. };
  14132. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14133. var pickingInfo = null;
  14134. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14135. var mesh = this.meshes[meshIndex];
  14136. if (predicate) {
  14137. if (!predicate(mesh)) {
  14138. continue;
  14139. }
  14140. }
  14141. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14142. continue;
  14143. }
  14144. var world = mesh.getWorldMatrix();
  14145. var ray = rayFunction(world);
  14146. var result = mesh.intersects(ray, fastCheck);
  14147. if (!result || !result.hit)
  14148. continue;
  14149. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14150. continue;
  14151. pickingInfo = result;
  14152. if (fastCheck) {
  14153. break;
  14154. }
  14155. }
  14156. return pickingInfo || new BABYLON.PickingInfo();
  14157. };
  14158. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14159. var pickingInfo = null;
  14160. camera = camera || this.activeCamera;
  14161. if (this.spriteManagers.length > 0) {
  14162. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14163. var spriteManager = this.spriteManagers[spriteIndex];
  14164. if (!spriteManager.isPickable) {
  14165. continue;
  14166. }
  14167. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14168. if (!result || !result.hit)
  14169. continue;
  14170. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14171. continue;
  14172. pickingInfo = result;
  14173. if (fastCheck) {
  14174. break;
  14175. }
  14176. }
  14177. }
  14178. return pickingInfo || new BABYLON.PickingInfo();
  14179. };
  14180. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14181. var _this = this;
  14182. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14183. /// <param name="x">X position on screen</param>
  14184. /// <param name="y">Y position on screen</param>
  14185. /// <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>
  14186. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14187. /// <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>
  14188. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14189. };
  14190. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14191. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14192. /// <param name="x">X position on screen</param>
  14193. /// <param name="y">Y position on screen</param>
  14194. /// <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>
  14195. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14196. /// <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>
  14197. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14198. };
  14199. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14200. var _this = this;
  14201. return this._internalPick(function (world) {
  14202. if (!_this._pickWithRayInverseMatrix) {
  14203. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14204. }
  14205. world.invertToRef(_this._pickWithRayInverseMatrix);
  14206. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14207. }, predicate, fastCheck);
  14208. };
  14209. Scene.prototype.setPointerOverMesh = function (mesh) {
  14210. if (this._pointerOverMesh === mesh) {
  14211. return;
  14212. }
  14213. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14214. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14215. }
  14216. this._pointerOverMesh = mesh;
  14217. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14218. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14219. }
  14220. };
  14221. Scene.prototype.getPointerOverMesh = function () {
  14222. return this._pointerOverMesh;
  14223. };
  14224. Scene.prototype.setPointerOverSprite = function (sprite) {
  14225. if (this._pointerOverSprite === sprite) {
  14226. return;
  14227. }
  14228. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14229. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14230. }
  14231. this._pointerOverSprite = sprite;
  14232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14233. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14234. }
  14235. };
  14236. Scene.prototype.getPointerOverSprite = function () {
  14237. return this._pointerOverSprite;
  14238. };
  14239. // Physics
  14240. Scene.prototype.getPhysicsEngine = function () {
  14241. return this._physicsEngine;
  14242. };
  14243. /**
  14244. * Enables physics to the current scene
  14245. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14246. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14247. * @return {boolean} was the physics engine initialized
  14248. */
  14249. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14250. if (this._physicsEngine) {
  14251. return true;
  14252. }
  14253. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14254. if (!this._physicsEngine.isSupported()) {
  14255. this._physicsEngine = null;
  14256. return false;
  14257. }
  14258. this._physicsEngine._initialize(gravity);
  14259. return true;
  14260. };
  14261. Scene.prototype.disablePhysicsEngine = function () {
  14262. if (!this._physicsEngine) {
  14263. return;
  14264. }
  14265. this._physicsEngine.dispose();
  14266. this._physicsEngine = undefined;
  14267. };
  14268. Scene.prototype.isPhysicsEnabled = function () {
  14269. return this._physicsEngine !== undefined;
  14270. };
  14271. /**
  14272. * Sets the gravity of the physics engine (and NOT of the scene)
  14273. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14274. */
  14275. Scene.prototype.setGravity = function (gravity) {
  14276. if (!this._physicsEngine) {
  14277. return;
  14278. }
  14279. this._physicsEngine._setGravity(gravity);
  14280. };
  14281. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14282. if (parts.parts) {
  14283. options = parts;
  14284. parts = parts.parts;
  14285. }
  14286. if (!this._physicsEngine) {
  14287. return null;
  14288. }
  14289. for (var index = 0; index < parts.length; index++) {
  14290. var mesh = parts[index].mesh;
  14291. mesh._physicImpostor = parts[index].impostor;
  14292. mesh._physicsMass = options.mass / parts.length;
  14293. mesh._physicsFriction = options.friction;
  14294. mesh._physicRestitution = options.restitution;
  14295. }
  14296. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14297. };
  14298. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14299. for (var index = 0; index < compound.parts.length; index++) {
  14300. var mesh = compound.parts[index].mesh;
  14301. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14302. this._physicsEngine._unregisterMesh(mesh);
  14303. }
  14304. };
  14305. // Misc.
  14306. Scene.prototype.createDefaultCameraOrLight = function () {
  14307. // Light
  14308. if (this.lights.length === 0) {
  14309. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14310. }
  14311. // Camera
  14312. if (!this.activeCamera) {
  14313. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14314. // Compute position
  14315. var worldExtends = this.getWorldExtends();
  14316. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14317. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14318. camera.setTarget(worldCenter);
  14319. this.activeCamera = camera;
  14320. }
  14321. };
  14322. // Tags
  14323. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14324. if (tagsQuery === undefined) {
  14325. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14326. return list;
  14327. }
  14328. var listByTags = [];
  14329. forEach = forEach || (function (item) { return; });
  14330. for (var i in list) {
  14331. var item = list[i];
  14332. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14333. listByTags.push(item);
  14334. forEach(item);
  14335. }
  14336. }
  14337. return listByTags;
  14338. };
  14339. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14340. return this._getByTags(this.meshes, tagsQuery, forEach);
  14341. };
  14342. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14343. return this._getByTags(this.cameras, tagsQuery, forEach);
  14344. };
  14345. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14346. return this._getByTags(this.lights, tagsQuery, forEach);
  14347. };
  14348. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14349. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14350. };
  14351. // Statics
  14352. Scene._FOGMODE_NONE = 0;
  14353. Scene._FOGMODE_EXP = 1;
  14354. Scene._FOGMODE_EXP2 = 2;
  14355. Scene._FOGMODE_LINEAR = 3;
  14356. Scene.MinDeltaTime = 1.0;
  14357. Scene.MaxDeltaTime = 1000.0;
  14358. return Scene;
  14359. })();
  14360. BABYLON.Scene = Scene;
  14361. })(BABYLON || (BABYLON = {}));
  14362. var BABYLON;
  14363. (function (BABYLON) {
  14364. var VertexBuffer = (function () {
  14365. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14366. if (engine instanceof BABYLON.Mesh) {
  14367. this._engine = engine.getScene().getEngine();
  14368. }
  14369. else {
  14370. this._engine = engine;
  14371. }
  14372. this._updatable = updatable;
  14373. this._data = data;
  14374. if (!postponeInternalCreation) {
  14375. this.create();
  14376. }
  14377. this._kind = kind;
  14378. if (stride) {
  14379. this._strideSize = stride;
  14380. return;
  14381. }
  14382. // Deduce stride from kind
  14383. switch (kind) {
  14384. case VertexBuffer.PositionKind:
  14385. this._strideSize = 3;
  14386. break;
  14387. case VertexBuffer.NormalKind:
  14388. this._strideSize = 3;
  14389. break;
  14390. case VertexBuffer.UVKind:
  14391. case VertexBuffer.UV2Kind:
  14392. case VertexBuffer.UV3Kind:
  14393. case VertexBuffer.UV4Kind:
  14394. case VertexBuffer.UV5Kind:
  14395. case VertexBuffer.UV6Kind:
  14396. this._strideSize = 2;
  14397. break;
  14398. case VertexBuffer.ColorKind:
  14399. this._strideSize = 4;
  14400. break;
  14401. case VertexBuffer.MatricesIndicesKind:
  14402. case VertexBuffer.MatricesIndicesExtraKind:
  14403. this._strideSize = 4;
  14404. break;
  14405. case VertexBuffer.MatricesWeightsKind:
  14406. case VertexBuffer.MatricesWeightsExtraKind:
  14407. this._strideSize = 4;
  14408. break;
  14409. }
  14410. }
  14411. // Properties
  14412. VertexBuffer.prototype.isUpdatable = function () {
  14413. return this._updatable;
  14414. };
  14415. VertexBuffer.prototype.getData = function () {
  14416. return this._data;
  14417. };
  14418. VertexBuffer.prototype.getBuffer = function () {
  14419. return this._buffer;
  14420. };
  14421. VertexBuffer.prototype.getStrideSize = function () {
  14422. return this._strideSize;
  14423. };
  14424. // Methods
  14425. VertexBuffer.prototype.create = function (data) {
  14426. if (!data && this._buffer) {
  14427. return; // nothing to do
  14428. }
  14429. data = data || this._data;
  14430. if (!this._buffer) {
  14431. if (this._updatable) {
  14432. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14433. }
  14434. else {
  14435. this._buffer = this._engine.createVertexBuffer(data);
  14436. }
  14437. }
  14438. if (this._updatable) {
  14439. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14440. this._data = data;
  14441. }
  14442. };
  14443. VertexBuffer.prototype.update = function (data) {
  14444. this.create(data);
  14445. };
  14446. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14447. if (!this._buffer) {
  14448. return;
  14449. }
  14450. if (this._updatable) {
  14451. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14452. this._data = null;
  14453. }
  14454. };
  14455. VertexBuffer.prototype.dispose = function () {
  14456. if (!this._buffer) {
  14457. return;
  14458. }
  14459. if (this._engine._releaseBuffer(this._buffer)) {
  14460. this._buffer = null;
  14461. }
  14462. };
  14463. Object.defineProperty(VertexBuffer, "PositionKind", {
  14464. get: function () {
  14465. return VertexBuffer._PositionKind;
  14466. },
  14467. enumerable: true,
  14468. configurable: true
  14469. });
  14470. Object.defineProperty(VertexBuffer, "NormalKind", {
  14471. get: function () {
  14472. return VertexBuffer._NormalKind;
  14473. },
  14474. enumerable: true,
  14475. configurable: true
  14476. });
  14477. Object.defineProperty(VertexBuffer, "UVKind", {
  14478. get: function () {
  14479. return VertexBuffer._UVKind;
  14480. },
  14481. enumerable: true,
  14482. configurable: true
  14483. });
  14484. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14485. get: function () {
  14486. return VertexBuffer._UV2Kind;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14492. get: function () {
  14493. return VertexBuffer._UV3Kind;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14499. get: function () {
  14500. return VertexBuffer._UV4Kind;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14506. get: function () {
  14507. return VertexBuffer._UV5Kind;
  14508. },
  14509. enumerable: true,
  14510. configurable: true
  14511. });
  14512. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14513. get: function () {
  14514. return VertexBuffer._UV6Kind;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. Object.defineProperty(VertexBuffer, "ColorKind", {
  14520. get: function () {
  14521. return VertexBuffer._ColorKind;
  14522. },
  14523. enumerable: true,
  14524. configurable: true
  14525. });
  14526. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14527. get: function () {
  14528. return VertexBuffer._MatricesIndicesKind;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14534. get: function () {
  14535. return VertexBuffer._MatricesWeightsKind;
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14541. get: function () {
  14542. return VertexBuffer._MatricesIndicesExtraKind;
  14543. },
  14544. enumerable: true,
  14545. configurable: true
  14546. });
  14547. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14548. get: function () {
  14549. return VertexBuffer._MatricesWeightsExtraKind;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. // Enums
  14555. VertexBuffer._PositionKind = "position";
  14556. VertexBuffer._NormalKind = "normal";
  14557. VertexBuffer._UVKind = "uv";
  14558. VertexBuffer._UV2Kind = "uv2";
  14559. VertexBuffer._UV3Kind = "uv3";
  14560. VertexBuffer._UV4Kind = "uv4";
  14561. VertexBuffer._UV5Kind = "uv5";
  14562. VertexBuffer._UV6Kind = "uv6";
  14563. VertexBuffer._ColorKind = "color";
  14564. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14565. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14566. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14567. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14568. return VertexBuffer;
  14569. })();
  14570. BABYLON.VertexBuffer = VertexBuffer;
  14571. })(BABYLON || (BABYLON = {}));
  14572. var BABYLON;
  14573. (function (BABYLON) {
  14574. /**
  14575. * Creates an instance based on a source mesh.
  14576. */
  14577. var InstancedMesh = (function (_super) {
  14578. __extends(InstancedMesh, _super);
  14579. function InstancedMesh(name, source) {
  14580. _super.call(this, name, source.getScene());
  14581. source.instances.push(this);
  14582. this._sourceMesh = source;
  14583. this.position.copyFrom(source.position);
  14584. this.rotation.copyFrom(source.rotation);
  14585. this.scaling.copyFrom(source.scaling);
  14586. if (source.rotationQuaternion) {
  14587. this.rotationQuaternion = source.rotationQuaternion.clone();
  14588. }
  14589. this.infiniteDistance = source.infiniteDistance;
  14590. this.setPivotMatrix(source.getPivotMatrix());
  14591. this.refreshBoundingInfo();
  14592. this._syncSubMeshes();
  14593. }
  14594. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14595. // Methods
  14596. get: function () {
  14597. return this._sourceMesh.receiveShadows;
  14598. },
  14599. enumerable: true,
  14600. configurable: true
  14601. });
  14602. Object.defineProperty(InstancedMesh.prototype, "material", {
  14603. get: function () {
  14604. return this._sourceMesh.material;
  14605. },
  14606. enumerable: true,
  14607. configurable: true
  14608. });
  14609. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14610. get: function () {
  14611. return this._sourceMesh.visibility;
  14612. },
  14613. enumerable: true,
  14614. configurable: true
  14615. });
  14616. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14617. get: function () {
  14618. return this._sourceMesh.skeleton;
  14619. },
  14620. enumerable: true,
  14621. configurable: true
  14622. });
  14623. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14624. get: function () {
  14625. return this._sourceMesh.renderingGroupId;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. InstancedMesh.prototype.getTotalVertices = function () {
  14631. return this._sourceMesh.getTotalVertices();
  14632. };
  14633. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14634. get: function () {
  14635. return this._sourceMesh;
  14636. },
  14637. enumerable: true,
  14638. configurable: true
  14639. });
  14640. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14641. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14642. };
  14643. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14644. return this._sourceMesh.isVerticesDataPresent(kind);
  14645. };
  14646. InstancedMesh.prototype.getIndices = function () {
  14647. return this._sourceMesh.getIndices();
  14648. };
  14649. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14650. get: function () {
  14651. return this._sourceMesh._positions;
  14652. },
  14653. enumerable: true,
  14654. configurable: true
  14655. });
  14656. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14657. var meshBB = this._sourceMesh.getBoundingInfo();
  14658. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14659. this._updateBoundingInfo();
  14660. };
  14661. InstancedMesh.prototype._preActivate = function () {
  14662. if (this._currentLOD) {
  14663. this._currentLOD._preActivate();
  14664. }
  14665. };
  14666. InstancedMesh.prototype._activate = function (renderId) {
  14667. if (this._currentLOD) {
  14668. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14669. }
  14670. };
  14671. InstancedMesh.prototype.getLOD = function (camera) {
  14672. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14673. if (this._currentLOD === this.sourceMesh) {
  14674. return this;
  14675. }
  14676. return this._currentLOD;
  14677. };
  14678. InstancedMesh.prototype._syncSubMeshes = function () {
  14679. this.releaseSubMeshes();
  14680. if (this._sourceMesh.subMeshes) {
  14681. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14682. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14683. }
  14684. }
  14685. };
  14686. InstancedMesh.prototype._generatePointsArray = function () {
  14687. return this._sourceMesh._generatePointsArray();
  14688. };
  14689. // Clone
  14690. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14691. var result = this._sourceMesh.createInstance(name);
  14692. // Deep copy
  14693. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14694. // Bounding info
  14695. this.refreshBoundingInfo();
  14696. // Parent
  14697. if (newParent) {
  14698. result.parent = newParent;
  14699. }
  14700. if (!doNotCloneChildren) {
  14701. // Children
  14702. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14703. var mesh = this.getScene().meshes[index];
  14704. if (mesh.parent === this) {
  14705. mesh.clone(mesh.name, result);
  14706. }
  14707. }
  14708. }
  14709. result.computeWorldMatrix(true);
  14710. return result;
  14711. };
  14712. // Dispoe
  14713. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14714. // Remove from mesh
  14715. var index = this._sourceMesh.instances.indexOf(this);
  14716. this._sourceMesh.instances.splice(index, 1);
  14717. _super.prototype.dispose.call(this, doNotRecurse);
  14718. };
  14719. return InstancedMesh;
  14720. })(BABYLON.AbstractMesh);
  14721. BABYLON.InstancedMesh = InstancedMesh;
  14722. })(BABYLON || (BABYLON = {}));
  14723. var BABYLON;
  14724. (function (BABYLON) {
  14725. var _InstancesBatch = (function () {
  14726. function _InstancesBatch() {
  14727. this.mustReturn = false;
  14728. this.visibleInstances = new Array();
  14729. this.renderSelf = new Array();
  14730. }
  14731. return _InstancesBatch;
  14732. })();
  14733. BABYLON._InstancesBatch = _InstancesBatch;
  14734. var Mesh = (function (_super) {
  14735. __extends(Mesh, _super);
  14736. /**
  14737. * @constructor
  14738. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14739. * @param {Scene} scene - The scene to add this mesh to.
  14740. * @param {Node} parent - The parent of this mesh, if it has one
  14741. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14742. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14743. * When false, achieved by calling a clone(), also passing False.
  14744. * This will make creation of children, recursive.
  14745. */
  14746. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14747. if (parent === void 0) { parent = null; }
  14748. _super.call(this, name, scene);
  14749. // Members
  14750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14751. this.instances = new Array();
  14752. this._LODLevels = new Array();
  14753. this._onBeforeRenderCallbacks = new Array();
  14754. this._onAfterRenderCallbacks = new Array();
  14755. this._visibleInstances = {};
  14756. this._renderIdForInstances = new Array();
  14757. this._batchCache = new _InstancesBatch();
  14758. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14759. this._sideOrientation = Mesh._DEFAULTSIDE;
  14760. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14761. if (source) {
  14762. // Geometry
  14763. if (source._geometry) {
  14764. source._geometry.applyToMesh(this);
  14765. }
  14766. // Deep copy
  14767. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14768. this.id = name + "." + source.id;
  14769. // Material
  14770. this.material = source.material;
  14771. var index;
  14772. if (!doNotCloneChildren) {
  14773. // Children
  14774. for (index = 0; index < scene.meshes.length; index++) {
  14775. var mesh = scene.meshes[index];
  14776. if (mesh.parent === source) {
  14777. // doNotCloneChildren is always going to be False
  14778. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14779. }
  14780. }
  14781. }
  14782. // Particles
  14783. for (index = 0; index < scene.particleSystems.length; index++) {
  14784. var system = scene.particleSystems[index];
  14785. if (system.emitter === source) {
  14786. system.clone(system.name, this);
  14787. }
  14788. }
  14789. this.computeWorldMatrix(true);
  14790. }
  14791. // Parent
  14792. if (parent !== null) {
  14793. this.parent = parent;
  14794. }
  14795. }
  14796. Object.defineProperty(Mesh, "FRONTSIDE", {
  14797. get: function () {
  14798. return Mesh._FRONTSIDE;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Mesh, "BACKSIDE", {
  14804. get: function () {
  14805. return Mesh._BACKSIDE;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14811. get: function () {
  14812. return Mesh._DOUBLESIDE;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14818. get: function () {
  14819. return Mesh._DEFAULTSIDE;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Mesh, "NO_CAP", {
  14825. get: function () {
  14826. return Mesh._NO_CAP;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Mesh, "CAP_START", {
  14832. get: function () {
  14833. return Mesh._CAP_START;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(Mesh, "CAP_END", {
  14839. get: function () {
  14840. return Mesh._CAP_END;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. Object.defineProperty(Mesh, "CAP_ALL", {
  14846. get: function () {
  14847. return Mesh._CAP_ALL;
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14853. // Methods
  14854. get: function () {
  14855. return this._LODLevels.length > 0;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Mesh.prototype._sortLODLevels = function () {
  14861. this._LODLevels.sort(function (a, b) {
  14862. if (a.distance < b.distance) {
  14863. return 1;
  14864. }
  14865. if (a.distance > b.distance) {
  14866. return -1;
  14867. }
  14868. return 0;
  14869. });
  14870. };
  14871. /**
  14872. * Add a mesh as LOD level triggered at the given distance.
  14873. * @param {number} distance - the distance from the center of the object to show this level
  14874. * @param {Mesh} mesh - the mesh to be added as LOD level
  14875. * @return {Mesh} this mesh (for chaining)
  14876. */
  14877. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14878. if (mesh && mesh._masterMesh) {
  14879. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14880. return this;
  14881. }
  14882. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14883. this._LODLevels.push(level);
  14884. if (mesh) {
  14885. mesh._masterMesh = this;
  14886. }
  14887. this._sortLODLevels();
  14888. return this;
  14889. };
  14890. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14891. for (var index = 0; index < this._LODLevels.length; index++) {
  14892. var level = this._LODLevels[index];
  14893. if (level.distance === distance) {
  14894. return level.mesh;
  14895. }
  14896. }
  14897. return null;
  14898. };
  14899. /**
  14900. * Remove a mesh from the LOD array
  14901. * @param {Mesh} mesh - the mesh to be removed.
  14902. * @return {Mesh} this mesh (for chaining)
  14903. */
  14904. Mesh.prototype.removeLODLevel = function (mesh) {
  14905. for (var index = 0; index < this._LODLevels.length; index++) {
  14906. if (this._LODLevels[index].mesh === mesh) {
  14907. this._LODLevels.splice(index, 1);
  14908. if (mesh) {
  14909. mesh._masterMesh = null;
  14910. }
  14911. }
  14912. }
  14913. this._sortLODLevels();
  14914. return this;
  14915. };
  14916. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14917. if (!this._LODLevels || this._LODLevels.length === 0) {
  14918. return this;
  14919. }
  14920. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14921. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14922. if (this.onLODLevelSelection) {
  14923. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14924. }
  14925. return this;
  14926. }
  14927. for (var index = 0; index < this._LODLevels.length; index++) {
  14928. var level = this._LODLevels[index];
  14929. if (level.distance < distanceToCamera) {
  14930. if (level.mesh) {
  14931. level.mesh._preActivate();
  14932. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14933. }
  14934. if (this.onLODLevelSelection) {
  14935. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14936. }
  14937. return level.mesh;
  14938. }
  14939. }
  14940. if (this.onLODLevelSelection) {
  14941. this.onLODLevelSelection(distanceToCamera, this, this);
  14942. }
  14943. return this;
  14944. };
  14945. Object.defineProperty(Mesh.prototype, "geometry", {
  14946. get: function () {
  14947. return this._geometry;
  14948. },
  14949. enumerable: true,
  14950. configurable: true
  14951. });
  14952. Mesh.prototype.getTotalVertices = function () {
  14953. if (!this._geometry) {
  14954. return 0;
  14955. }
  14956. return this._geometry.getTotalVertices();
  14957. };
  14958. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14959. if (!this._geometry) {
  14960. return null;
  14961. }
  14962. return this._geometry.getVerticesData(kind, copyWhenShared);
  14963. };
  14964. Mesh.prototype.getVertexBuffer = function (kind) {
  14965. if (!this._geometry) {
  14966. return undefined;
  14967. }
  14968. return this._geometry.getVertexBuffer(kind);
  14969. };
  14970. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14971. if (!this._geometry) {
  14972. if (this._delayInfo) {
  14973. return this._delayInfo.indexOf(kind) !== -1;
  14974. }
  14975. return false;
  14976. }
  14977. return this._geometry.isVerticesDataPresent(kind);
  14978. };
  14979. Mesh.prototype.getVerticesDataKinds = function () {
  14980. if (!this._geometry) {
  14981. var result = [];
  14982. if (this._delayInfo) {
  14983. for (var kind in this._delayInfo) {
  14984. result.push(kind);
  14985. }
  14986. }
  14987. return result;
  14988. }
  14989. return this._geometry.getVerticesDataKinds();
  14990. };
  14991. Mesh.prototype.getTotalIndices = function () {
  14992. if (!this._geometry) {
  14993. return 0;
  14994. }
  14995. return this._geometry.getTotalIndices();
  14996. };
  14997. Mesh.prototype.getIndices = function (copyWhenShared) {
  14998. if (!this._geometry) {
  14999. return [];
  15000. }
  15001. return this._geometry.getIndices(copyWhenShared);
  15002. };
  15003. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15004. get: function () {
  15005. return this._masterMesh !== null && this._masterMesh !== undefined;
  15006. },
  15007. enumerable: true,
  15008. configurable: true
  15009. });
  15010. Mesh.prototype.isReady = function () {
  15011. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15012. return false;
  15013. }
  15014. return _super.prototype.isReady.call(this);
  15015. };
  15016. Mesh.prototype.isDisposed = function () {
  15017. return this._isDisposed;
  15018. };
  15019. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15020. get: function () {
  15021. return this._sideOrientation;
  15022. },
  15023. set: function (sideO) {
  15024. this._sideOrientation = sideO;
  15025. },
  15026. enumerable: true,
  15027. configurable: true
  15028. });
  15029. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15030. get: function () {
  15031. return this._areNormalsFrozen;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15037. Mesh.prototype.freezeNormals = function () {
  15038. this._areNormalsFrozen = true;
  15039. };
  15040. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15041. Mesh.prototype.unfreezeNormals = function () {
  15042. this._areNormalsFrozen = false;
  15043. };
  15044. // Methods
  15045. Mesh.prototype._preActivate = function () {
  15046. var sceneRenderId = this.getScene().getRenderId();
  15047. if (this._preActivateId === sceneRenderId) {
  15048. return;
  15049. }
  15050. this._preActivateId = sceneRenderId;
  15051. this._visibleInstances = null;
  15052. };
  15053. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15054. if (!this._visibleInstances) {
  15055. this._visibleInstances = {};
  15056. this._visibleInstances.defaultRenderId = renderId;
  15057. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15058. }
  15059. if (!this._visibleInstances[renderId]) {
  15060. this._visibleInstances[renderId] = new Array();
  15061. }
  15062. this._visibleInstances[renderId].push(instance);
  15063. };
  15064. Mesh.prototype.refreshBoundingInfo = function () {
  15065. if (this._boundingInfo.isLocked) {
  15066. return;
  15067. }
  15068. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15069. if (data) {
  15070. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15071. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15072. }
  15073. if (this.subMeshes) {
  15074. for (var index = 0; index < this.subMeshes.length; index++) {
  15075. this.subMeshes[index].refreshBoundingInfo();
  15076. }
  15077. }
  15078. this._updateBoundingInfo();
  15079. };
  15080. Mesh.prototype._createGlobalSubMesh = function () {
  15081. var totalVertices = this.getTotalVertices();
  15082. if (!totalVertices || !this.getIndices()) {
  15083. return null;
  15084. }
  15085. this.releaseSubMeshes();
  15086. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15087. };
  15088. Mesh.prototype.subdivide = function (count) {
  15089. if (count < 1) {
  15090. return;
  15091. }
  15092. var totalIndices = this.getTotalIndices();
  15093. var subdivisionSize = (totalIndices / count) | 0;
  15094. var offset = 0;
  15095. // Ensure that subdivisionSize is a multiple of 3
  15096. while (subdivisionSize % 3 !== 0) {
  15097. subdivisionSize++;
  15098. }
  15099. this.releaseSubMeshes();
  15100. for (var index = 0; index < count; index++) {
  15101. if (offset >= totalIndices) {
  15102. break;
  15103. }
  15104. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15105. offset += subdivisionSize;
  15106. }
  15107. this.synchronizeInstances();
  15108. };
  15109. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15110. if (!this._geometry) {
  15111. var vertexData = new BABYLON.VertexData();
  15112. vertexData.set(data, kind);
  15113. var scene = this.getScene();
  15114. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15115. }
  15116. else {
  15117. this._geometry.setVerticesData(kind, data, updatable, stride);
  15118. }
  15119. };
  15120. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15121. if (!this._geometry) {
  15122. return;
  15123. }
  15124. if (!makeItUnique) {
  15125. this._geometry.updateVerticesData(kind, data, updateExtends);
  15126. }
  15127. else {
  15128. this.makeGeometryUnique();
  15129. this.updateVerticesData(kind, data, updateExtends, false);
  15130. }
  15131. };
  15132. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15133. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15134. if (!this._geometry) {
  15135. return;
  15136. }
  15137. if (!makeItUnique) {
  15138. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15139. }
  15140. else {
  15141. this.makeGeometryUnique();
  15142. this.updateVerticesDataDirectly(kind, data, offset, false);
  15143. }
  15144. };
  15145. // Mesh positions update function :
  15146. // updates the mesh positions according to the positionFunction returned values.
  15147. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15148. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15149. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15150. if (computeNormals === void 0) { computeNormals = true; }
  15151. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15152. positionFunction(positions);
  15153. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15154. if (computeNormals) {
  15155. var indices = this.getIndices();
  15156. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15157. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15158. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15159. }
  15160. };
  15161. Mesh.prototype.makeGeometryUnique = function () {
  15162. if (!this._geometry) {
  15163. return;
  15164. }
  15165. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15166. geometry.applyToMesh(this);
  15167. };
  15168. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15169. if (!this._geometry) {
  15170. var vertexData = new BABYLON.VertexData();
  15171. vertexData.indices = indices;
  15172. var scene = this.getScene();
  15173. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15174. }
  15175. else {
  15176. this._geometry.setIndices(indices, totalVertices);
  15177. }
  15178. };
  15179. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15180. var engine = this.getScene().getEngine();
  15181. // Wireframe
  15182. var indexToBind;
  15183. if (this._unIndexed) {
  15184. indexToBind = null;
  15185. }
  15186. else {
  15187. switch (fillMode) {
  15188. case BABYLON.Material.PointFillMode:
  15189. indexToBind = null;
  15190. break;
  15191. case BABYLON.Material.WireFrameFillMode:
  15192. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15193. break;
  15194. default:
  15195. case BABYLON.Material.TriangleFillMode:
  15196. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15197. break;
  15198. }
  15199. }
  15200. // VBOs
  15201. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15202. };
  15203. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15204. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15205. return;
  15206. }
  15207. if (this.onBeforeDraw) {
  15208. this.onBeforeDraw();
  15209. }
  15210. var engine = this.getScene().getEngine();
  15211. // Draw order
  15212. switch (fillMode) {
  15213. case BABYLON.Material.PointFillMode:
  15214. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15215. break;
  15216. case BABYLON.Material.WireFrameFillMode:
  15217. if (this._unIndexed) {
  15218. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15219. }
  15220. else {
  15221. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15222. }
  15223. break;
  15224. default:
  15225. if (this._unIndexed) {
  15226. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15227. }
  15228. else {
  15229. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15230. }
  15231. }
  15232. };
  15233. Mesh.prototype.registerBeforeRender = function (func) {
  15234. this._onBeforeRenderCallbacks.push(func);
  15235. };
  15236. Mesh.prototype.unregisterBeforeRender = function (func) {
  15237. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15238. if (index > -1) {
  15239. this._onBeforeRenderCallbacks.splice(index, 1);
  15240. }
  15241. };
  15242. Mesh.prototype.registerAfterRender = function (func) {
  15243. this._onAfterRenderCallbacks.push(func);
  15244. };
  15245. Mesh.prototype.unregisterAfterRender = function (func) {
  15246. var index = this._onAfterRenderCallbacks.indexOf(func);
  15247. if (index > -1) {
  15248. this._onAfterRenderCallbacks.splice(index, 1);
  15249. }
  15250. };
  15251. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15252. var scene = this.getScene();
  15253. this._batchCache.mustReturn = false;
  15254. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15255. this._batchCache.visibleInstances[subMeshId] = null;
  15256. if (this._visibleInstances) {
  15257. var currentRenderId = scene.getRenderId();
  15258. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15259. var selfRenderId = this._renderId;
  15260. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15261. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15262. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15263. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15264. }
  15265. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15266. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15267. this._batchCache.mustReturn = true;
  15268. return this._batchCache;
  15269. }
  15270. if (currentRenderId !== selfRenderId) {
  15271. this._batchCache.renderSelf[subMeshId] = false;
  15272. }
  15273. }
  15274. this._renderIdForInstances[subMeshId] = currentRenderId;
  15275. }
  15276. return this._batchCache;
  15277. };
  15278. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15279. var visibleInstances = batch.visibleInstances[subMesh._id];
  15280. var matricesCount = visibleInstances.length + 1;
  15281. var bufferSize = matricesCount * 16 * 4;
  15282. while (this._instancesBufferSize < bufferSize) {
  15283. this._instancesBufferSize *= 2;
  15284. }
  15285. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15286. if (this._worldMatricesInstancesBuffer) {
  15287. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15288. }
  15289. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15290. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15291. }
  15292. var offset = 0;
  15293. var instancesCount = 0;
  15294. var world = this.getWorldMatrix();
  15295. if (batch.renderSelf[subMesh._id]) {
  15296. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15297. offset += 16;
  15298. instancesCount++;
  15299. }
  15300. if (visibleInstances) {
  15301. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15302. var instance = visibleInstances[instanceIndex];
  15303. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15304. offset += 16;
  15305. instancesCount++;
  15306. }
  15307. }
  15308. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15309. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15310. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15311. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15312. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15313. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15314. this._draw(subMesh, fillMode, instancesCount);
  15315. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15316. };
  15317. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15318. var scene = this.getScene();
  15319. var engine = scene.getEngine();
  15320. if (hardwareInstancedRendering) {
  15321. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15322. }
  15323. else {
  15324. if (batch.renderSelf[subMesh._id]) {
  15325. // Draw
  15326. if (onBeforeDraw) {
  15327. onBeforeDraw(false, this.getWorldMatrix());
  15328. }
  15329. this._draw(subMesh, fillMode);
  15330. }
  15331. if (batch.visibleInstances[subMesh._id]) {
  15332. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15333. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15334. // World
  15335. var world = instance.getWorldMatrix();
  15336. if (onBeforeDraw) {
  15337. onBeforeDraw(true, world);
  15338. }
  15339. // Draw
  15340. this._draw(subMesh, fillMode);
  15341. }
  15342. }
  15343. }
  15344. };
  15345. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15346. var scene = this.getScene();
  15347. // Managing instances
  15348. var batch = this._getInstancesRenderList(subMesh._id);
  15349. if (batch.mustReturn) {
  15350. return;
  15351. }
  15352. // Checking geometry state
  15353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15354. return;
  15355. }
  15356. var callbackIndex;
  15357. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15358. this._onBeforeRenderCallbacks[callbackIndex](this);
  15359. }
  15360. var engine = scene.getEngine();
  15361. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15362. // Material
  15363. var effectiveMaterial = subMesh.getMaterial();
  15364. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15365. return;
  15366. }
  15367. // Outline - step 1
  15368. var savedDepthWrite = engine.getDepthWrite();
  15369. if (this.renderOutline) {
  15370. engine.setDepthWrite(false);
  15371. scene.getOutlineRenderer().render(subMesh, batch);
  15372. engine.setDepthWrite(savedDepthWrite);
  15373. }
  15374. effectiveMaterial._preBind();
  15375. var effect = effectiveMaterial.getEffect();
  15376. // Bind
  15377. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15378. this._bind(subMesh, effect, fillMode);
  15379. var world = this.getWorldMatrix();
  15380. effectiveMaterial.bind(world, this);
  15381. // Alpha mode
  15382. if (enableAlphaMode) {
  15383. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15384. }
  15385. // Draw
  15386. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15387. if (isInstance) {
  15388. effectiveMaterial.bindOnlyWorldMatrix(world);
  15389. }
  15390. });
  15391. // Unbind
  15392. effectiveMaterial.unbind();
  15393. // Outline - step 2
  15394. if (this.renderOutline && savedDepthWrite) {
  15395. engine.setDepthWrite(true);
  15396. engine.setColorWrite(false);
  15397. scene.getOutlineRenderer().render(subMesh, batch);
  15398. engine.setColorWrite(true);
  15399. }
  15400. // Overlay
  15401. if (this.renderOverlay) {
  15402. var currentMode = engine.getAlphaMode();
  15403. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15404. scene.getOutlineRenderer().render(subMesh, batch, true);
  15405. engine.setAlphaMode(currentMode);
  15406. }
  15407. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15408. this._onAfterRenderCallbacks[callbackIndex](this);
  15409. }
  15410. };
  15411. Mesh.prototype.getEmittedParticleSystems = function () {
  15412. var results = new Array();
  15413. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15414. var particleSystem = this.getScene().particleSystems[index];
  15415. if (particleSystem.emitter === this) {
  15416. results.push(particleSystem);
  15417. }
  15418. }
  15419. return results;
  15420. };
  15421. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15422. var results = new Array();
  15423. var descendants = this.getDescendants();
  15424. descendants.push(this);
  15425. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15426. var particleSystem = this.getScene().particleSystems[index];
  15427. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15428. results.push(particleSystem);
  15429. }
  15430. }
  15431. return results;
  15432. };
  15433. Mesh.prototype.getChildren = function () {
  15434. var results = [];
  15435. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15436. var mesh = this.getScene().meshes[index];
  15437. if (mesh.parent === this) {
  15438. results.push(mesh);
  15439. }
  15440. }
  15441. return results;
  15442. };
  15443. Mesh.prototype._checkDelayState = function () {
  15444. var _this = this;
  15445. var that = this;
  15446. var scene = this.getScene();
  15447. if (this._geometry) {
  15448. this._geometry.load(scene);
  15449. }
  15450. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15451. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15452. scene._addPendingData(that);
  15453. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15454. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15455. if (data instanceof ArrayBuffer) {
  15456. _this._delayLoadingFunction(data, _this);
  15457. }
  15458. else {
  15459. _this._delayLoadingFunction(JSON.parse(data), _this);
  15460. }
  15461. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15462. scene._removePendingData(_this);
  15463. }, function () { }, scene.database, getBinaryData);
  15464. }
  15465. };
  15466. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15467. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15468. return false;
  15469. }
  15470. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15471. return false;
  15472. }
  15473. this._checkDelayState();
  15474. return true;
  15475. };
  15476. Mesh.prototype.setMaterialByID = function (id) {
  15477. var materials = this.getScene().materials;
  15478. var index;
  15479. for (index = 0; index < materials.length; index++) {
  15480. if (materials[index].id === id) {
  15481. this.material = materials[index];
  15482. return;
  15483. }
  15484. }
  15485. // Multi
  15486. var multiMaterials = this.getScene().multiMaterials;
  15487. for (index = 0; index < multiMaterials.length; index++) {
  15488. if (multiMaterials[index].id === id) {
  15489. this.material = multiMaterials[index];
  15490. return;
  15491. }
  15492. }
  15493. };
  15494. Mesh.prototype.getAnimatables = function () {
  15495. var results = [];
  15496. if (this.material) {
  15497. results.push(this.material);
  15498. }
  15499. if (this.skeleton) {
  15500. results.push(this.skeleton);
  15501. }
  15502. return results;
  15503. };
  15504. // Geometry
  15505. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15506. // Position
  15507. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15508. return;
  15509. }
  15510. this._resetPointsArrayCache();
  15511. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15512. var temp = [];
  15513. var index;
  15514. for (index = 0; index < data.length; index += 3) {
  15515. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15516. }
  15517. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15518. // Normals
  15519. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15520. return;
  15521. }
  15522. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15523. temp = [];
  15524. for (index = 0; index < data.length; index += 3) {
  15525. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15526. }
  15527. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15528. // flip faces?
  15529. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15530. this.flipFaces();
  15531. }
  15532. };
  15533. // Will apply current transform to mesh and reset world matrix
  15534. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15535. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15536. this.scaling.copyFromFloats(1, 1, 1);
  15537. this.position.copyFromFloats(0, 0, 0);
  15538. this.rotation.copyFromFloats(0, 0, 0);
  15539. //only if quaternion is already set
  15540. if (this.rotationQuaternion) {
  15541. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15542. }
  15543. this._worldMatrix = BABYLON.Matrix.Identity();
  15544. };
  15545. // Cache
  15546. Mesh.prototype._resetPointsArrayCache = function () {
  15547. this._positions = null;
  15548. };
  15549. Mesh.prototype._generatePointsArray = function () {
  15550. if (this._positions)
  15551. return true;
  15552. this._positions = [];
  15553. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15554. if (!data) {
  15555. return false;
  15556. }
  15557. for (var index = 0; index < data.length; index += 3) {
  15558. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15559. }
  15560. return true;
  15561. };
  15562. // Clone
  15563. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15564. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15565. };
  15566. // Dispose
  15567. Mesh.prototype.dispose = function (doNotRecurse) {
  15568. if (this._geometry) {
  15569. this._geometry.releaseForMesh(this, true);
  15570. }
  15571. // Instances
  15572. if (this._worldMatricesInstancesBuffer) {
  15573. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15574. this._worldMatricesInstancesBuffer = null;
  15575. }
  15576. while (this.instances.length) {
  15577. this.instances[0].dispose();
  15578. }
  15579. _super.prototype.dispose.call(this, doNotRecurse);
  15580. };
  15581. // Geometric tools
  15582. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15583. var _this = this;
  15584. var scene = this.getScene();
  15585. var onload = function (img) {
  15586. // Getting height map data
  15587. var canvas = document.createElement("canvas");
  15588. var context = canvas.getContext("2d");
  15589. var heightMapWidth = img.width;
  15590. var heightMapHeight = img.height;
  15591. canvas.width = heightMapWidth;
  15592. canvas.height = heightMapHeight;
  15593. context.drawImage(img, 0, 0);
  15594. // Create VertexData from map data
  15595. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15596. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15597. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15598. //execute success callback, if set
  15599. if (onSuccess) {
  15600. onSuccess(_this);
  15601. }
  15602. };
  15603. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15604. };
  15605. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15607. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15608. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15609. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15610. return;
  15611. }
  15612. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15613. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15614. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15615. var position = BABYLON.Vector3.Zero();
  15616. var normal = BABYLON.Vector3.Zero();
  15617. var uv = BABYLON.Vector2.Zero();
  15618. for (var index = 0; index < positions.length; index += 3) {
  15619. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15620. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15621. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15622. // Compute height
  15623. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15624. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15625. var pos = (u + v * heightMapWidth) * 4;
  15626. var r = buffer[pos] / 255.0;
  15627. var g = buffer[pos + 1] / 255.0;
  15628. var b = buffer[pos + 2] / 255.0;
  15629. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15630. normal.normalize();
  15631. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15632. position = position.add(normal);
  15633. position.toArray(positions, index);
  15634. }
  15635. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15636. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15637. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15638. };
  15639. Mesh.prototype.convertToFlatShadedMesh = function () {
  15640. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15641. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15642. var kinds = this.getVerticesDataKinds();
  15643. var vbs = [];
  15644. var data = [];
  15645. var newdata = [];
  15646. var updatableNormals = false;
  15647. var kindIndex;
  15648. var kind;
  15649. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15650. kind = kinds[kindIndex];
  15651. var vertexBuffer = this.getVertexBuffer(kind);
  15652. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15653. updatableNormals = vertexBuffer.isUpdatable();
  15654. kinds.splice(kindIndex, 1);
  15655. kindIndex--;
  15656. continue;
  15657. }
  15658. vbs[kind] = vertexBuffer;
  15659. data[kind] = vbs[kind].getData();
  15660. newdata[kind] = [];
  15661. }
  15662. // Save previous submeshes
  15663. var previousSubmeshes = this.subMeshes.slice(0);
  15664. var indices = this.getIndices();
  15665. var totalIndices = this.getTotalIndices();
  15666. // Generating unique vertices per face
  15667. var index;
  15668. for (index = 0; index < totalIndices; index++) {
  15669. var vertexIndex = indices[index];
  15670. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15671. kind = kinds[kindIndex];
  15672. var stride = vbs[kind].getStrideSize();
  15673. for (var offset = 0; offset < stride; offset++) {
  15674. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15675. }
  15676. }
  15677. }
  15678. // Updating faces & normal
  15679. var normals = [];
  15680. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15681. for (index = 0; index < totalIndices; index += 3) {
  15682. indices[index] = index;
  15683. indices[index + 1] = index + 1;
  15684. indices[index + 2] = index + 2;
  15685. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15686. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15687. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15688. var p1p2 = p1.subtract(p2);
  15689. var p3p2 = p3.subtract(p2);
  15690. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15691. // Store same normals for every vertex
  15692. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15693. normals.push(normal.x);
  15694. normals.push(normal.y);
  15695. normals.push(normal.z);
  15696. }
  15697. }
  15698. this.setIndices(indices);
  15699. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15700. // Updating vertex buffers
  15701. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15702. kind = kinds[kindIndex];
  15703. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15704. }
  15705. // Updating submeshes
  15706. this.releaseSubMeshes();
  15707. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15708. var previousOne = previousSubmeshes[submeshIndex];
  15709. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15710. }
  15711. this.synchronizeInstances();
  15712. };
  15713. Mesh.prototype.convertToUnIndexedMesh = function () {
  15714. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15715. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15716. var kinds = this.getVerticesDataKinds();
  15717. var vbs = [];
  15718. var data = [];
  15719. var newdata = [];
  15720. var updatableNormals = false;
  15721. var kindIndex;
  15722. var kind;
  15723. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15724. kind = kinds[kindIndex];
  15725. var vertexBuffer = this.getVertexBuffer(kind);
  15726. vbs[kind] = vertexBuffer;
  15727. data[kind] = vbs[kind].getData();
  15728. newdata[kind] = [];
  15729. }
  15730. // Save previous submeshes
  15731. var previousSubmeshes = this.subMeshes.slice(0);
  15732. var indices = this.getIndices();
  15733. var totalIndices = this.getTotalIndices();
  15734. // Generating unique vertices per face
  15735. var index;
  15736. for (index = 0; index < totalIndices; index++) {
  15737. var vertexIndex = indices[index];
  15738. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15739. kind = kinds[kindIndex];
  15740. var stride = vbs[kind].getStrideSize();
  15741. for (var offset = 0; offset < stride; offset++) {
  15742. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15743. }
  15744. }
  15745. }
  15746. // Updating indices
  15747. for (index = 0; index < totalIndices; index += 3) {
  15748. indices[index] = index;
  15749. indices[index + 1] = index + 1;
  15750. indices[index + 2] = index + 2;
  15751. }
  15752. this.setIndices(indices);
  15753. // Updating vertex buffers
  15754. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15755. kind = kinds[kindIndex];
  15756. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15757. }
  15758. // Updating submeshes
  15759. this.releaseSubMeshes();
  15760. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15761. var previousOne = previousSubmeshes[submeshIndex];
  15762. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15763. }
  15764. this._unIndexed = true;
  15765. this.synchronizeInstances();
  15766. };
  15767. // will inverse faces orientations, and invert normals too if specified
  15768. Mesh.prototype.flipFaces = function (flipNormals) {
  15769. if (flipNormals === void 0) { flipNormals = false; }
  15770. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15771. var i;
  15772. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15773. for (i = 0; i < vertex_data.normals.length; i++) {
  15774. vertex_data.normals[i] *= -1;
  15775. }
  15776. }
  15777. var temp;
  15778. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15779. // reassign indices
  15780. temp = vertex_data.indices[i + 1];
  15781. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15782. vertex_data.indices[i + 2] = temp;
  15783. }
  15784. vertex_data.applyToMesh(this);
  15785. };
  15786. // Instances
  15787. Mesh.prototype.createInstance = function (name) {
  15788. return new BABYLON.InstancedMesh(name, this);
  15789. };
  15790. Mesh.prototype.synchronizeInstances = function () {
  15791. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15792. var instance = this.instances[instanceIndex];
  15793. instance._syncSubMeshes();
  15794. }
  15795. };
  15796. /**
  15797. * Simplify the mesh according to the given array of settings.
  15798. * Function will return immediately and will simplify async.
  15799. * @param settings a collection of simplification settings.
  15800. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15801. * @param type the type of simplification to run.
  15802. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15803. */
  15804. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15805. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15806. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15807. this.getScene().simplificationQueue.addTask({
  15808. settings: settings,
  15809. parallelProcessing: parallelProcessing,
  15810. mesh: this,
  15811. simplificationType: simplificationType,
  15812. successCallback: successCallback
  15813. });
  15814. };
  15815. /**
  15816. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15817. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15818. * This should be used together with the simplification to avoid disappearing triangles.
  15819. * @param successCallback an optional success callback to be called after the optimization finished.
  15820. */
  15821. Mesh.prototype.optimizeIndices = function (successCallback) {
  15822. var _this = this;
  15823. var indices = this.getIndices();
  15824. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15825. var vectorPositions = [];
  15826. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15827. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15828. }
  15829. var dupes = [];
  15830. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15831. var realPos = vectorPositions.length - 1 - iteration;
  15832. var testedPosition = vectorPositions[realPos];
  15833. for (var j = 0; j < realPos; ++j) {
  15834. var againstPosition = vectorPositions[j];
  15835. if (testedPosition.equals(againstPosition)) {
  15836. dupes[realPos] = j;
  15837. break;
  15838. }
  15839. }
  15840. }, function () {
  15841. for (var i = 0; i < indices.length; ++i) {
  15842. indices[i] = dupes[indices[i]] || indices[i];
  15843. }
  15844. //indices are now reordered
  15845. var originalSubMeshes = _this.subMeshes.slice(0);
  15846. _this.setIndices(indices);
  15847. _this.subMeshes = originalSubMeshes;
  15848. if (successCallback) {
  15849. successCallback(_this);
  15850. }
  15851. });
  15852. };
  15853. // Statics
  15854. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15855. var mesh = new Mesh(parsedMesh.name, scene);
  15856. mesh.id = parsedMesh.id;
  15857. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15858. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15859. if (parsedMesh.rotationQuaternion) {
  15860. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15861. }
  15862. else if (parsedMesh.rotation) {
  15863. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15864. }
  15865. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15866. if (parsedMesh.localMatrix) {
  15867. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15868. }
  15869. else if (parsedMesh.pivotMatrix) {
  15870. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15871. }
  15872. mesh.setEnabled(parsedMesh.isEnabled);
  15873. mesh.isVisible = parsedMesh.isVisible;
  15874. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15875. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15876. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15877. if (parsedMesh.applyFog !== undefined) {
  15878. mesh.applyFog = parsedMesh.applyFog;
  15879. }
  15880. if (parsedMesh.pickable !== undefined) {
  15881. mesh.isPickable = parsedMesh.pickable;
  15882. }
  15883. if (parsedMesh.alphaIndex !== undefined) {
  15884. mesh.alphaIndex = parsedMesh.alphaIndex;
  15885. }
  15886. mesh.receiveShadows = parsedMesh.receiveShadows;
  15887. mesh.billboardMode = parsedMesh.billboardMode;
  15888. if (parsedMesh.visibility !== undefined) {
  15889. mesh.visibility = parsedMesh.visibility;
  15890. }
  15891. mesh.checkCollisions = parsedMesh.checkCollisions;
  15892. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15893. // freezeWorldMatrix
  15894. if (parsedMesh.freezeWorldMatrix) {
  15895. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15896. }
  15897. // Parent
  15898. if (parsedMesh.parentId) {
  15899. mesh._waitingParentId = parsedMesh.parentId;
  15900. }
  15901. // Actions
  15902. if (parsedMesh.actions !== undefined) {
  15903. mesh._waitingActions = parsedMesh.actions;
  15904. }
  15905. // Geometry
  15906. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15907. if (parsedMesh.delayLoadingFile) {
  15908. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15909. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15910. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15911. if (parsedMesh._binaryInfo) {
  15912. mesh._binaryInfo = parsedMesh._binaryInfo;
  15913. }
  15914. mesh._delayInfo = [];
  15915. if (parsedMesh.hasUVs) {
  15916. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15917. }
  15918. if (parsedMesh.hasUVs2) {
  15919. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15920. }
  15921. if (parsedMesh.hasUVs3) {
  15922. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15923. }
  15924. if (parsedMesh.hasUVs4) {
  15925. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15926. }
  15927. if (parsedMesh.hasUVs5) {
  15928. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15929. }
  15930. if (parsedMesh.hasUVs6) {
  15931. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15932. }
  15933. if (parsedMesh.hasColors) {
  15934. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15935. }
  15936. if (parsedMesh.hasMatricesIndices) {
  15937. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15938. }
  15939. if (parsedMesh.hasMatricesWeights) {
  15940. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15941. }
  15942. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15943. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15944. mesh._checkDelayState();
  15945. }
  15946. }
  15947. else {
  15948. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15949. }
  15950. // Material
  15951. if (parsedMesh.materialId) {
  15952. mesh.setMaterialByID(parsedMesh.materialId);
  15953. }
  15954. else {
  15955. mesh.material = null;
  15956. }
  15957. // Skeleton
  15958. if (parsedMesh.skeletonId > -1) {
  15959. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15960. if (parsedMesh.numBoneInfluencers) {
  15961. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15962. }
  15963. }
  15964. // Physics
  15965. if (parsedMesh.physicsImpostor) {
  15966. if (!scene.isPhysicsEnabled()) {
  15967. scene.enablePhysics();
  15968. }
  15969. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15970. }
  15971. // Animations
  15972. if (parsedMesh.animations) {
  15973. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15974. var parsedAnimation = parsedMesh.animations[animationIndex];
  15975. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15976. }
  15977. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15978. }
  15979. if (parsedMesh.autoAnimate) {
  15980. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15981. }
  15982. // Layer Mask
  15983. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15984. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15985. }
  15986. else {
  15987. mesh.layerMask = 0x0FFFFFFF;
  15988. }
  15989. // Instances
  15990. if (parsedMesh.instances) {
  15991. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15992. var parsedInstance = parsedMesh.instances[index];
  15993. var instance = mesh.createInstance(parsedInstance.name);
  15994. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15995. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15996. if (parsedInstance.rotationQuaternion) {
  15997. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15998. }
  15999. else if (parsedInstance.rotation) {
  16000. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16001. }
  16002. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16003. instance.checkCollisions = mesh.checkCollisions;
  16004. if (parsedMesh.animations) {
  16005. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16006. parsedAnimation = parsedMesh.animations[animationIndex];
  16007. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16008. }
  16009. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16010. }
  16011. }
  16012. }
  16013. return mesh;
  16014. };
  16015. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16016. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16017. pathArray: pathArray,
  16018. closeArray: closeArray,
  16019. closePath: closePath,
  16020. offset: offset,
  16021. updatable: updatable,
  16022. sideOrientation: sideOrientation,
  16023. instance: instance
  16024. }, scene);
  16025. };
  16026. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16027. var options = {
  16028. radius: radius,
  16029. tessellation: tessellation,
  16030. sideOrientation: sideOrientation,
  16031. updatable: updatable
  16032. };
  16033. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16034. };
  16035. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16036. var options = {
  16037. size: size,
  16038. sideOrientation: sideOrientation,
  16039. updatable: updatable
  16040. };
  16041. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16042. };
  16043. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16044. var options = {
  16045. segments: segments,
  16046. diameterX: diameter,
  16047. diameterY: diameter,
  16048. diameterZ: diameter,
  16049. sideOrientation: sideOrientation,
  16050. updatable: updatable
  16051. };
  16052. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16053. };
  16054. // Cylinder and cone
  16055. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16056. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16057. if (scene !== undefined) {
  16058. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16059. updatable = scene;
  16060. }
  16061. scene = subdivisions;
  16062. subdivisions = 1;
  16063. }
  16064. var options = {
  16065. height: height,
  16066. diameterTop: diameterTop,
  16067. diameterBottom: diameterBottom,
  16068. tessellation: tessellation,
  16069. subdivisions: subdivisions,
  16070. sideOrientation: sideOrientation,
  16071. updatable: updatable
  16072. };
  16073. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16074. };
  16075. // Torus (Code from SharpDX.org)
  16076. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16077. var options = {
  16078. diameter: diameter,
  16079. thickness: thickness,
  16080. tessellation: tessellation,
  16081. sideOrientation: sideOrientation,
  16082. updatable: updatable
  16083. };
  16084. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16085. };
  16086. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16087. var options = {
  16088. radius: radius,
  16089. tube: tube,
  16090. radialSegments: radialSegments,
  16091. tubularSegments: tubularSegments,
  16092. p: p,
  16093. q: q,
  16094. sideOrientation: sideOrientation,
  16095. updatable: updatable
  16096. };
  16097. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16098. };
  16099. // Lines
  16100. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16101. var options = {
  16102. points: points,
  16103. updatable: updatable,
  16104. instance: instance
  16105. };
  16106. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16107. };
  16108. // Dashed Lines
  16109. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16110. var options = {
  16111. points: points,
  16112. dashSize: dashSize,
  16113. gapSize: gapSize,
  16114. dashNb: dashNb,
  16115. updatable: updatable
  16116. };
  16117. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16118. };
  16119. // Extrusion
  16120. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16121. var options = {
  16122. shape: shape,
  16123. path: path,
  16124. scale: scale,
  16125. rotation: rotation,
  16126. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16127. sideOrientation: sideOrientation,
  16128. instance: instance,
  16129. updatable: updatable
  16130. };
  16131. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16132. };
  16133. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16134. var options = {
  16135. shape: shape,
  16136. path: path,
  16137. scaleFunction: scaleFunction,
  16138. rotationFunction: rotationFunction,
  16139. ribbonCloseArray: ribbonCloseArray,
  16140. ribbonClosePath: ribbonClosePath,
  16141. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16142. sideOrientation: sideOrientation,
  16143. instance: instance,
  16144. updatable: updatable
  16145. };
  16146. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16147. };
  16148. // Lathe
  16149. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16150. var options = {
  16151. shape: shape,
  16152. radius: radius,
  16153. tessellation: tessellation,
  16154. sideOrientation: sideOrientation,
  16155. updatable: updatable
  16156. };
  16157. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16158. };
  16159. // Plane & ground
  16160. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16161. var options = {
  16162. size: size,
  16163. width: size,
  16164. height: size,
  16165. sideOrientation: sideOrientation,
  16166. updatable: updatable
  16167. };
  16168. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16169. };
  16170. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16171. var options = {
  16172. width: width,
  16173. height: height,
  16174. subdivisions: subdivisions,
  16175. updatable: updatable
  16176. };
  16177. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16178. };
  16179. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16180. var options = {
  16181. xmin: xmin,
  16182. zmin: zmin,
  16183. xmax: xmax,
  16184. zmax: zmax,
  16185. subdivisions: subdivisions,
  16186. precision: precision,
  16187. updatable: updatable
  16188. };
  16189. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16190. };
  16191. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16192. var options = {
  16193. width: width,
  16194. height: height,
  16195. subdivisions: subdivisions,
  16196. minHeight: minHeight,
  16197. maxHeight: maxHeight,
  16198. updatable: updatable,
  16199. onReady: onReady
  16200. };
  16201. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16202. };
  16203. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16204. var options = {
  16205. path: path,
  16206. radius: radius,
  16207. tessellation: tessellation,
  16208. radiusFunction: radiusFunction,
  16209. arc: 1,
  16210. cap: cap,
  16211. updatable: updatable,
  16212. sideOrientation: sideOrientation,
  16213. instance: instance
  16214. };
  16215. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16216. };
  16217. Mesh.CreatePolyhedron = function (name, options, scene) {
  16218. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16219. };
  16220. Mesh.CreateIcoSphere = function (name, options, scene) {
  16221. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16222. };
  16223. // Decals
  16224. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16225. var options = {
  16226. position: position,
  16227. normal: normal,
  16228. size: size,
  16229. angle: angle
  16230. };
  16231. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16232. };
  16233. // Skeletons
  16234. /**
  16235. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16236. */
  16237. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16238. var source;
  16239. if (!this._sourcePositions) {
  16240. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16241. this._sourcePositions = new Float32Array(source);
  16242. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16243. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16244. }
  16245. }
  16246. return this._sourcePositions;
  16247. };
  16248. /**
  16249. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16250. */
  16251. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16252. var source;
  16253. if (!this._sourceNormals) {
  16254. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16255. this._sourceNormals = new Float32Array(source);
  16256. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16257. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16258. }
  16259. }
  16260. return this._sourceNormals;
  16261. };
  16262. /**
  16263. * Update the vertex buffers by applying transformation from the bones
  16264. * @param {skeleton} skeleton to apply
  16265. */
  16266. Mesh.prototype.applySkeleton = function (skeleton) {
  16267. if (!this.geometry) {
  16268. return;
  16269. }
  16270. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16271. return;
  16272. }
  16273. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16274. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16275. return this;
  16276. }
  16277. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16278. return this;
  16279. }
  16280. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16281. return this;
  16282. }
  16283. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16284. return this;
  16285. }
  16286. if (!this._sourcePositions) {
  16287. this.setPositionsForCPUSkinning();
  16288. }
  16289. if (!this._sourceNormals) {
  16290. this.setNormalsForCPUSkinning();
  16291. }
  16292. // positionsData checks for not being Float32Array will only pass at most once
  16293. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16294. if (!(positionsData instanceof Float32Array)) {
  16295. positionsData = new Float32Array(positionsData);
  16296. }
  16297. // normalsData checks for not being Float32Array will only pass at most once
  16298. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16299. if (!(normalsData instanceof Float32Array)) {
  16300. normalsData = new Float32Array(normalsData);
  16301. }
  16302. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16303. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16304. var needExtras = this.numBoneInfluencers > 4;
  16305. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16306. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16307. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16308. var tempVector3 = BABYLON.Vector3.Zero();
  16309. var finalMatrix = new BABYLON.Matrix();
  16310. var tempMatrix = new BABYLON.Matrix();
  16311. var matWeightIdx = 0;
  16312. var inf;
  16313. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16314. var weight;
  16315. for (inf = 0; inf < 4; inf++) {
  16316. weight = matricesWeightsData[matWeightIdx + inf];
  16317. if (weight > 0) {
  16318. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16319. finalMatrix.addToSelf(tempMatrix);
  16320. }
  16321. else
  16322. break;
  16323. }
  16324. if (needExtras) {
  16325. for (inf = 0; inf < 4; inf++) {
  16326. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16327. if (weight > 0) {
  16328. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16329. finalMatrix.addToSelf(tempMatrix);
  16330. }
  16331. else
  16332. break;
  16333. }
  16334. }
  16335. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16336. tempVector3.toArray(positionsData, index);
  16337. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16338. tempVector3.toArray(normalsData, index);
  16339. finalMatrix.reset();
  16340. }
  16341. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16342. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16343. return this;
  16344. };
  16345. // Tools
  16346. Mesh.MinMax = function (meshes) {
  16347. var minVector = null;
  16348. var maxVector = null;
  16349. for (var i in meshes) {
  16350. var mesh = meshes[i];
  16351. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16352. if (!minVector) {
  16353. minVector = boundingBox.minimumWorld;
  16354. maxVector = boundingBox.maximumWorld;
  16355. continue;
  16356. }
  16357. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16358. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16359. }
  16360. return {
  16361. min: minVector,
  16362. max: maxVector
  16363. };
  16364. };
  16365. Mesh.Center = function (meshesOrMinMaxVector) {
  16366. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16367. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16368. };
  16369. /**
  16370. * Merge the array of meshes into a single mesh for performance reasons.
  16371. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16372. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16373. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16374. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16375. */
  16376. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16377. if (disposeSource === void 0) { disposeSource = true; }
  16378. var index;
  16379. if (!allow32BitsIndices) {
  16380. var totalVertices = 0;
  16381. // Counting vertices
  16382. for (index = 0; index < meshes.length; index++) {
  16383. if (meshes[index]) {
  16384. totalVertices += meshes[index].getTotalVertices();
  16385. if (totalVertices > 65536) {
  16386. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16387. return null;
  16388. }
  16389. }
  16390. }
  16391. }
  16392. // Merge
  16393. var vertexData;
  16394. var otherVertexData;
  16395. var source;
  16396. for (index = 0; index < meshes.length; index++) {
  16397. if (meshes[index]) {
  16398. meshes[index].computeWorldMatrix(true);
  16399. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16400. otherVertexData.transform(meshes[index].getWorldMatrix());
  16401. if (vertexData) {
  16402. vertexData.merge(otherVertexData);
  16403. }
  16404. else {
  16405. vertexData = otherVertexData;
  16406. source = meshes[index];
  16407. }
  16408. }
  16409. }
  16410. if (!meshSubclass) {
  16411. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16412. }
  16413. vertexData.applyToMesh(meshSubclass);
  16414. // Setting properties
  16415. meshSubclass.material = source.material;
  16416. meshSubclass.checkCollisions = source.checkCollisions;
  16417. // Cleaning
  16418. if (disposeSource) {
  16419. for (index = 0; index < meshes.length; index++) {
  16420. if (meshes[index]) {
  16421. meshes[index].dispose();
  16422. }
  16423. }
  16424. }
  16425. return meshSubclass;
  16426. };
  16427. // Consts
  16428. Mesh._FRONTSIDE = 0;
  16429. Mesh._BACKSIDE = 1;
  16430. Mesh._DOUBLESIDE = 2;
  16431. Mesh._DEFAULTSIDE = 0;
  16432. Mesh._NO_CAP = 0;
  16433. Mesh._CAP_START = 1;
  16434. Mesh._CAP_END = 2;
  16435. Mesh._CAP_ALL = 3;
  16436. return Mesh;
  16437. })(BABYLON.AbstractMesh);
  16438. BABYLON.Mesh = Mesh;
  16439. })(BABYLON || (BABYLON = {}));
  16440. var BABYLON;
  16441. (function (BABYLON) {
  16442. var SubMesh = (function () {
  16443. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16444. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16445. this.materialIndex = materialIndex;
  16446. this.verticesStart = verticesStart;
  16447. this.verticesCount = verticesCount;
  16448. this.indexStart = indexStart;
  16449. this.indexCount = indexCount;
  16450. this._renderId = 0;
  16451. this._mesh = mesh;
  16452. this._renderingMesh = renderingMesh || mesh;
  16453. mesh.subMeshes.push(this);
  16454. this._trianglePlanes = [];
  16455. this._id = mesh.subMeshes.length - 1;
  16456. if (createBoundingBox) {
  16457. this.refreshBoundingInfo();
  16458. mesh.computeWorldMatrix(true);
  16459. }
  16460. }
  16461. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16462. get: function () {
  16463. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. SubMesh.prototype.getBoundingInfo = function () {
  16469. if (this.IsGlobal) {
  16470. return this._mesh.getBoundingInfo();
  16471. }
  16472. return this._boundingInfo;
  16473. };
  16474. SubMesh.prototype.getMesh = function () {
  16475. return this._mesh;
  16476. };
  16477. SubMesh.prototype.getRenderingMesh = function () {
  16478. return this._renderingMesh;
  16479. };
  16480. SubMesh.prototype.getMaterial = function () {
  16481. var rootMaterial = this._renderingMesh.material;
  16482. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16483. var multiMaterial = rootMaterial;
  16484. return multiMaterial.getSubMaterial(this.materialIndex);
  16485. }
  16486. if (!rootMaterial) {
  16487. return this._mesh.getScene().defaultMaterial;
  16488. }
  16489. return rootMaterial;
  16490. };
  16491. // Methods
  16492. SubMesh.prototype.refreshBoundingInfo = function () {
  16493. if (this.IsGlobal) {
  16494. return;
  16495. }
  16496. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16497. if (!data) {
  16498. this._boundingInfo = this._mesh._boundingInfo;
  16499. return;
  16500. }
  16501. var indices = this._renderingMesh.getIndices();
  16502. var extend;
  16503. //is this the only submesh?
  16504. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16505. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16506. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16507. }
  16508. else {
  16509. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16510. }
  16511. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16512. };
  16513. SubMesh.prototype._checkCollision = function (collider) {
  16514. return this.getBoundingInfo()._checkCollision(collider);
  16515. };
  16516. SubMesh.prototype.updateBoundingInfo = function (world) {
  16517. if (!this.getBoundingInfo()) {
  16518. this.refreshBoundingInfo();
  16519. }
  16520. this.getBoundingInfo().update(world);
  16521. };
  16522. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16523. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16524. };
  16525. SubMesh.prototype.render = function (enableAlphaMode) {
  16526. this._renderingMesh.render(this, enableAlphaMode);
  16527. };
  16528. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16529. if (!this._linesIndexBuffer) {
  16530. var linesIndices = [];
  16531. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16532. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16533. }
  16534. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16535. this.linesIndexCount = linesIndices.length;
  16536. }
  16537. return this._linesIndexBuffer;
  16538. };
  16539. SubMesh.prototype.canIntersects = function (ray) {
  16540. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16541. };
  16542. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16543. var intersectInfo = null;
  16544. // Triangles test
  16545. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16546. var p0 = positions[indices[index]];
  16547. var p1 = positions[indices[index + 1]];
  16548. var p2 = positions[indices[index + 2]];
  16549. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16550. if (currentIntersectInfo) {
  16551. if (currentIntersectInfo.distance < 0) {
  16552. continue;
  16553. }
  16554. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16555. intersectInfo = currentIntersectInfo;
  16556. intersectInfo.faceId = index / 3;
  16557. if (fastCheck) {
  16558. break;
  16559. }
  16560. }
  16561. }
  16562. }
  16563. return intersectInfo;
  16564. };
  16565. // Clone
  16566. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16567. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16568. if (!this.IsGlobal) {
  16569. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16570. }
  16571. return result;
  16572. };
  16573. // Dispose
  16574. SubMesh.prototype.dispose = function () {
  16575. if (this._linesIndexBuffer) {
  16576. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16577. this._linesIndexBuffer = null;
  16578. }
  16579. // Remove from mesh
  16580. var index = this._mesh.subMeshes.indexOf(this);
  16581. this._mesh.subMeshes.splice(index, 1);
  16582. };
  16583. // Statics
  16584. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16585. var minVertexIndex = Number.MAX_VALUE;
  16586. var maxVertexIndex = -Number.MAX_VALUE;
  16587. renderingMesh = renderingMesh || mesh;
  16588. var indices = renderingMesh.getIndices();
  16589. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16590. var vertexIndex = indices[index];
  16591. if (vertexIndex < minVertexIndex)
  16592. minVertexIndex = vertexIndex;
  16593. if (vertexIndex > maxVertexIndex)
  16594. maxVertexIndex = vertexIndex;
  16595. }
  16596. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16597. };
  16598. return SubMesh;
  16599. })();
  16600. BABYLON.SubMesh = SubMesh;
  16601. })(BABYLON || (BABYLON = {}));
  16602. var BABYLON;
  16603. (function (BABYLON) {
  16604. var MeshBuilder = (function () {
  16605. function MeshBuilder() {
  16606. }
  16607. MeshBuilder.CreateBox = function (name, options, scene) {
  16608. var box = new BABYLON.Mesh(name, scene);
  16609. var vertexData = BABYLON.VertexData.CreateBox(options);
  16610. vertexData.applyToMesh(box, options.updatable);
  16611. return box;
  16612. };
  16613. MeshBuilder.CreateSphere = function (name, options, scene) {
  16614. var sphere = new BABYLON.Mesh(name, scene);
  16615. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16616. vertexData.applyToMesh(sphere, options.updatable);
  16617. return sphere;
  16618. };
  16619. MeshBuilder.CreateDisc = function (name, options, scene) {
  16620. var disc = new BABYLON.Mesh(name, scene);
  16621. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16622. vertexData.applyToMesh(disc, options.updatable);
  16623. return disc;
  16624. };
  16625. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16626. var sphere = new BABYLON.Mesh(name, scene);
  16627. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16628. vertexData.applyToMesh(sphere, options.updatable);
  16629. return sphere;
  16630. };
  16631. ;
  16632. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16633. var pathArray = options.pathArray;
  16634. var closeArray = options.closeArray;
  16635. var closePath = options.closePath;
  16636. var offset = options.offset;
  16637. var sideOrientation = options.sideOrientation;
  16638. var instance = options.instance;
  16639. var updatable = options.updatable;
  16640. if (instance) {
  16641. // positionFunction : ribbon case
  16642. // only pathArray and sideOrientation parameters are taken into account for positions update
  16643. var positionFunction = function (positions) {
  16644. var minlg = pathArray[0].length;
  16645. var i = 0;
  16646. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16647. for (var si = 1; si <= ns; si++) {
  16648. for (var p = 0; p < pathArray.length; p++) {
  16649. var path = pathArray[p];
  16650. var l = path.length;
  16651. minlg = (minlg < l) ? minlg : l;
  16652. var j = 0;
  16653. while (j < minlg) {
  16654. positions[i] = path[j].x;
  16655. positions[i + 1] = path[j].y;
  16656. positions[i + 2] = path[j].z;
  16657. j++;
  16658. i += 3;
  16659. }
  16660. if (instance._closePath) {
  16661. positions[i] = path[0].x;
  16662. positions[i + 1] = path[0].y;
  16663. positions[i + 2] = path[0].z;
  16664. i += 3;
  16665. }
  16666. }
  16667. }
  16668. };
  16669. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16670. positionFunction(positions);
  16671. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16672. if (!(instance.areNormalsFrozen)) {
  16673. var indices = instance.getIndices();
  16674. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16675. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16676. if (instance._closePath) {
  16677. var indexFirst = 0;
  16678. var indexLast = 0;
  16679. for (var p = 0; p < pathArray.length; p++) {
  16680. indexFirst = instance._idx[p] * 3;
  16681. if (p + 1 < pathArray.length) {
  16682. indexLast = (instance._idx[p + 1] - 1) * 3;
  16683. }
  16684. else {
  16685. indexLast = normals.length - 3;
  16686. }
  16687. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16688. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16689. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16690. normals[indexLast] = normals[indexFirst];
  16691. normals[indexLast + 1] = normals[indexFirst + 1];
  16692. normals[indexLast + 2] = normals[indexFirst + 2];
  16693. }
  16694. }
  16695. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16696. }
  16697. return instance;
  16698. }
  16699. else {
  16700. var ribbon = new BABYLON.Mesh(name, scene);
  16701. ribbon.sideOrientation = sideOrientation;
  16702. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16703. if (closePath) {
  16704. ribbon._idx = vertexData._idx;
  16705. }
  16706. ribbon._closePath = closePath;
  16707. ribbon._closeArray = closeArray;
  16708. vertexData.applyToMesh(ribbon, updatable);
  16709. return ribbon;
  16710. }
  16711. };
  16712. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16713. var cylinder = new BABYLON.Mesh(name, scene);
  16714. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16715. vertexData.applyToMesh(cylinder, options.updatable);
  16716. return cylinder;
  16717. };
  16718. MeshBuilder.CreateTorus = function (name, options, scene) {
  16719. var torus = new BABYLON.Mesh(name, scene);
  16720. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16721. vertexData.applyToMesh(torus, options.updatable);
  16722. return torus;
  16723. };
  16724. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16725. var torusKnot = new BABYLON.Mesh(name, scene);
  16726. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16727. vertexData.applyToMesh(torusKnot, options.updatable);
  16728. return torusKnot;
  16729. };
  16730. MeshBuilder.CreateLines = function (name, options, scene) {
  16731. var instance = options.instance;
  16732. var points = options.points;
  16733. if (instance) {
  16734. var positionFunction = function (positions) {
  16735. var i = 0;
  16736. for (var p = 0; p < points.length; p++) {
  16737. positions[i] = points[p].x;
  16738. positions[i + 1] = points[p].y;
  16739. positions[i + 2] = points[p].z;
  16740. i += 3;
  16741. }
  16742. };
  16743. instance.updateMeshPositions(positionFunction, false);
  16744. return instance;
  16745. }
  16746. // lines creation
  16747. var lines = new BABYLON.LinesMesh(name, scene);
  16748. var vertexData = BABYLON.VertexData.CreateLines(options);
  16749. vertexData.applyToMesh(lines, options.updatable);
  16750. return lines;
  16751. };
  16752. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16753. var points = options.points;
  16754. var instance = options.instance;
  16755. var gapSize = options.gapSize;
  16756. var dashNb = options.dashNb;
  16757. var dashSize = options.dashSize;
  16758. if (instance) {
  16759. var positionFunction = function (positions) {
  16760. var curvect = BABYLON.Vector3.Zero();
  16761. var nbSeg = positions.length / 6;
  16762. var lg = 0;
  16763. var nb = 0;
  16764. var shft = 0;
  16765. var dashshft = 0;
  16766. var curshft = 0;
  16767. var p = 0;
  16768. var i = 0;
  16769. var j = 0;
  16770. for (i = 0; i < points.length - 1; i++) {
  16771. points[i + 1].subtractToRef(points[i], curvect);
  16772. lg += curvect.length();
  16773. }
  16774. shft = lg / nbSeg;
  16775. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16776. for (i = 0; i < points.length - 1; i++) {
  16777. points[i + 1].subtractToRef(points[i], curvect);
  16778. nb = Math.floor(curvect.length() / shft);
  16779. curvect.normalize();
  16780. j = 0;
  16781. while (j < nb && p < positions.length) {
  16782. curshft = shft * j;
  16783. positions[p] = points[i].x + curshft * curvect.x;
  16784. positions[p + 1] = points[i].y + curshft * curvect.y;
  16785. positions[p + 2] = points[i].z + curshft * curvect.z;
  16786. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16787. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16788. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16789. p += 6;
  16790. j++;
  16791. }
  16792. }
  16793. while (p < positions.length) {
  16794. positions[p] = points[i].x;
  16795. positions[p + 1] = points[i].y;
  16796. positions[p + 2] = points[i].z;
  16797. p += 3;
  16798. }
  16799. };
  16800. instance.updateMeshPositions(positionFunction, false);
  16801. return instance;
  16802. }
  16803. // dashed lines creation
  16804. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16805. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16806. vertexData.applyToMesh(dashedLines, options.updatable);
  16807. dashedLines.dashSize = dashSize;
  16808. dashedLines.gapSize = gapSize;
  16809. return dashedLines;
  16810. };
  16811. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16812. var path = options.path;
  16813. var shape = options.shape;
  16814. var scale = options.scale || 1;
  16815. var rotation = options.rotation || 0;
  16816. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16817. var updatable = options.updatable;
  16818. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16819. var instance = options.instance;
  16820. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16821. };
  16822. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16823. var path = options.path;
  16824. var shape = options.shape;
  16825. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16826. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16827. var ribbonCloseArray = options.ribbonCloseArray || false;
  16828. var ribbonClosePath = options.ribbonClosePath || false;
  16829. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16830. var updatable = options.updatable;
  16831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16832. var instance = options.instance;
  16833. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16834. };
  16835. MeshBuilder.CreateLathe = function (name, options, scene) {
  16836. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16837. var closed = (options.closed === undefined) ? true : options.closed;
  16838. var shape = options.shape;
  16839. var radius = options.radius || 1;
  16840. var tessellation = options.tessellation || 64;
  16841. var updatable = options.updatable;
  16842. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16843. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16844. var pi2 = Math.PI * 2;
  16845. var paths = new Array();
  16846. var i = 0;
  16847. var p = 0;
  16848. var step = pi2 / tessellation * arc;
  16849. var rotated;
  16850. var path = new Array();
  16851. ;
  16852. for (i = 0; i <= tessellation; i++) {
  16853. var path = [];
  16854. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16855. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16856. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16857. }
  16858. for (p = 0; p < shape.length; p++) {
  16859. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16860. path.push(rotated);
  16861. }
  16862. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16863. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16864. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16865. }
  16866. paths.push(path);
  16867. }
  16868. // lathe ribbon
  16869. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16870. return lathe;
  16871. };
  16872. MeshBuilder.CreatePlane = function (name, options, scene) {
  16873. var plane = new BABYLON.Mesh(name, scene);
  16874. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16875. vertexData.applyToMesh(plane, options.updatable);
  16876. if (options.sourcePlane) {
  16877. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16878. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16879. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16880. plane.rotate(vectorProduct, product);
  16881. }
  16882. return plane;
  16883. };
  16884. MeshBuilder.CreateGround = function (name, options, scene) {
  16885. var ground = new BABYLON.GroundMesh(name, scene);
  16886. ground._setReady(false);
  16887. ground._subdivisions = options.subdivisions || 1;
  16888. ground._width = options.width || 1;
  16889. ground._height = options.height || 1;
  16890. ground._maxX = ground._width / 2;
  16891. ground._maxZ = ground._height / 2;
  16892. ground._minX = -ground._maxX;
  16893. ground._minZ = -ground._maxZ;
  16894. var vertexData = BABYLON.VertexData.CreateGround(options);
  16895. vertexData.applyToMesh(ground, options.updatable);
  16896. ground._setReady(true);
  16897. return ground;
  16898. };
  16899. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16900. var tiledGround = new BABYLON.Mesh(name, scene);
  16901. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16902. vertexData.applyToMesh(tiledGround, options.updatable);
  16903. return tiledGround;
  16904. };
  16905. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16906. var width = options.width || 10;
  16907. var height = options.height || 10;
  16908. var subdivisions = options.subdivisions || 1;
  16909. var minHeight = options.minHeight;
  16910. var maxHeight = options.maxHeight || 10;
  16911. var updatable = options.updatable;
  16912. var onReady = options.onReady;
  16913. var ground = new BABYLON.GroundMesh(name, scene);
  16914. ground._subdivisions = subdivisions;
  16915. ground._width = width;
  16916. ground._height = height;
  16917. ground._maxX = ground._width / 2;
  16918. ground._maxZ = ground._height / 2;
  16919. ground._minX = -ground._maxX;
  16920. ground._minZ = -ground._maxZ;
  16921. ground._setReady(false);
  16922. var onload = function (img) {
  16923. // Getting height map data
  16924. var canvas = document.createElement("canvas");
  16925. var context = canvas.getContext("2d");
  16926. var bufferWidth = img.width;
  16927. var bufferHeight = img.height;
  16928. canvas.width = bufferWidth;
  16929. canvas.height = bufferHeight;
  16930. context.drawImage(img, 0, 0);
  16931. // Create VertexData from map data
  16932. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16933. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16934. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16935. width: width, height: height,
  16936. subdivisions: subdivisions,
  16937. minHeight: minHeight, maxHeight: maxHeight,
  16938. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16939. });
  16940. vertexData.applyToMesh(ground, updatable);
  16941. ground._setReady(true);
  16942. //execute ready callback, if set
  16943. if (onReady) {
  16944. onReady(ground);
  16945. }
  16946. };
  16947. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16948. return ground;
  16949. };
  16950. MeshBuilder.CreateTube = function (name, options, scene) {
  16951. var path = options.path;
  16952. var radius = options.radius || 1;
  16953. var tessellation = options.tessellation || 64;
  16954. var radiusFunction = options.radiusFunction;
  16955. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16956. var updatable = options.updatable;
  16957. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16958. var instance = options.instance;
  16959. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16960. // tube geometry
  16961. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16962. var tangents = path3D.getTangents();
  16963. var normals = path3D.getNormals();
  16964. var distances = path3D.getDistances();
  16965. var pi2 = Math.PI * 2;
  16966. var step = pi2 / tessellation * arc;
  16967. var returnRadius = function () { return radius; };
  16968. var radiusFunctionFinal = radiusFunction || returnRadius;
  16969. var circlePath;
  16970. var rad;
  16971. var normal;
  16972. var rotated;
  16973. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16974. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16975. for (var i = 0; i < path.length; i++) {
  16976. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16977. circlePath = Array(); // current circle array
  16978. normal = normals[i]; // current normal
  16979. for (var t = 0; t < tessellation; t++) {
  16980. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16981. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16982. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16983. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16984. circlePath[t] = rotated;
  16985. }
  16986. circlePaths[index] = circlePath;
  16987. index++;
  16988. }
  16989. // cap
  16990. var capPath = function (nbPoints, pathIndex) {
  16991. var pointCap = Array();
  16992. for (var i = 0; i < nbPoints; i++) {
  16993. pointCap.push(path[pathIndex]);
  16994. }
  16995. return pointCap;
  16996. };
  16997. switch (cap) {
  16998. case BABYLON.Mesh.NO_CAP:
  16999. break;
  17000. case BABYLON.Mesh.CAP_START:
  17001. circlePaths[0] = capPath(tessellation, 0);
  17002. circlePaths[1] = circlePaths[2].slice(0);
  17003. break;
  17004. case BABYLON.Mesh.CAP_END:
  17005. circlePaths[index] = circlePaths[index - 1].slice(0);
  17006. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17007. break;
  17008. case BABYLON.Mesh.CAP_ALL:
  17009. circlePaths[0] = capPath(tessellation, 0);
  17010. circlePaths[1] = circlePaths[2].slice(0);
  17011. circlePaths[index] = circlePaths[index - 1].slice(0);
  17012. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17013. break;
  17014. default:
  17015. break;
  17016. }
  17017. return circlePaths;
  17018. };
  17019. var path3D;
  17020. var pathArray;
  17021. if (instance) {
  17022. var arc = options.arc || instance.arc;
  17023. path3D = (instance.path3D).update(path);
  17024. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17025. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17026. instance.path3D = path3D;
  17027. instance.pathArray = pathArray;
  17028. instance.arc = arc;
  17029. return instance;
  17030. }
  17031. // tube creation
  17032. path3D = new BABYLON.Path3D(path);
  17033. var newPathArray = new Array();
  17034. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17035. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17036. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17037. tube.pathArray = pathArray;
  17038. tube.path3D = path3D;
  17039. tube.tessellation = tessellation;
  17040. tube.cap = cap;
  17041. tube.arc = options.arc;
  17042. return tube;
  17043. };
  17044. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17045. var polyhedron = new BABYLON.Mesh(name, scene);
  17046. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17047. vertexData.applyToMesh(polyhedron, options.updatable);
  17048. return polyhedron;
  17049. };
  17050. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17051. var indices = sourceMesh.getIndices();
  17052. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17053. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17054. var position = options.position || BABYLON.Vector3.Zero();
  17055. var normal = options.normal || BABYLON.Vector3.Up();
  17056. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17057. var angle = options.angle || 0;
  17058. // Getting correct rotation
  17059. if (!normal) {
  17060. var target = new BABYLON.Vector3(0, 0, 1);
  17061. var camera = sourceMesh.getScene().activeCamera;
  17062. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17063. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17064. }
  17065. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17066. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17067. var pitch = Math.atan2(normal.y, len);
  17068. // Matrix
  17069. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17070. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17071. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17072. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17073. var vertexData = new BABYLON.VertexData();
  17074. vertexData.indices = [];
  17075. vertexData.positions = [];
  17076. vertexData.normals = [];
  17077. vertexData.uvs = [];
  17078. var currentVertexDataIndex = 0;
  17079. var extractDecalVector3 = function (indexId) {
  17080. var vertexId = indices[indexId];
  17081. var result = new BABYLON.PositionNormalVertex();
  17082. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17083. // Send vector to decal local world
  17084. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17085. // Get normal
  17086. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17087. return result;
  17088. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17089. var clip = function (vertices, axis) {
  17090. if (vertices.length === 0) {
  17091. return vertices;
  17092. }
  17093. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17094. var clipVertices = function (v0, v1) {
  17095. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17096. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17097. };
  17098. var result = new Array();
  17099. for (var index = 0; index < vertices.length; index += 3) {
  17100. var v1Out;
  17101. var v2Out;
  17102. var v3Out;
  17103. var total = 0;
  17104. var nV1, nV2, nV3, nV4;
  17105. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17106. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17107. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17108. v1Out = d1 > 0;
  17109. v2Out = d2 > 0;
  17110. v3Out = d3 > 0;
  17111. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17112. switch (total) {
  17113. case 0:
  17114. result.push(vertices[index]);
  17115. result.push(vertices[index + 1]);
  17116. result.push(vertices[index + 2]);
  17117. break;
  17118. case 1:
  17119. if (v1Out) {
  17120. nV1 = vertices[index + 1];
  17121. nV2 = vertices[index + 2];
  17122. nV3 = clipVertices(vertices[index], nV1);
  17123. nV4 = clipVertices(vertices[index], nV2);
  17124. }
  17125. if (v2Out) {
  17126. nV1 = vertices[index];
  17127. nV2 = vertices[index + 2];
  17128. nV3 = clipVertices(vertices[index + 1], nV1);
  17129. nV4 = clipVertices(vertices[index + 1], nV2);
  17130. result.push(nV3);
  17131. result.push(nV2.clone());
  17132. result.push(nV1.clone());
  17133. result.push(nV2.clone());
  17134. result.push(nV3.clone());
  17135. result.push(nV4);
  17136. break;
  17137. }
  17138. if (v3Out) {
  17139. nV1 = vertices[index];
  17140. nV2 = vertices[index + 1];
  17141. nV3 = clipVertices(vertices[index + 2], nV1);
  17142. nV4 = clipVertices(vertices[index + 2], nV2);
  17143. }
  17144. result.push(nV1.clone());
  17145. result.push(nV2.clone());
  17146. result.push(nV3);
  17147. result.push(nV4);
  17148. result.push(nV3.clone());
  17149. result.push(nV2.clone());
  17150. break;
  17151. case 2:
  17152. if (!v1Out) {
  17153. nV1 = vertices[index].clone();
  17154. nV2 = clipVertices(nV1, vertices[index + 1]);
  17155. nV3 = clipVertices(nV1, vertices[index + 2]);
  17156. result.push(nV1);
  17157. result.push(nV2);
  17158. result.push(nV3);
  17159. }
  17160. if (!v2Out) {
  17161. nV1 = vertices[index + 1].clone();
  17162. nV2 = clipVertices(nV1, vertices[index + 2]);
  17163. nV3 = clipVertices(nV1, vertices[index]);
  17164. result.push(nV1);
  17165. result.push(nV2);
  17166. result.push(nV3);
  17167. }
  17168. if (!v3Out) {
  17169. nV1 = vertices[index + 2].clone();
  17170. nV2 = clipVertices(nV1, vertices[index]);
  17171. nV3 = clipVertices(nV1, vertices[index + 1]);
  17172. result.push(nV1);
  17173. result.push(nV2);
  17174. result.push(nV3);
  17175. }
  17176. break;
  17177. case 3:
  17178. break;
  17179. }
  17180. }
  17181. return result;
  17182. };
  17183. for (var index = 0; index < indices.length; index += 3) {
  17184. var faceVertices = new Array();
  17185. faceVertices.push(extractDecalVector3(index));
  17186. faceVertices.push(extractDecalVector3(index + 1));
  17187. faceVertices.push(extractDecalVector3(index + 2));
  17188. // Clip
  17189. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17190. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17191. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17192. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17193. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17194. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17195. if (faceVertices.length === 0) {
  17196. continue;
  17197. }
  17198. // Add UVs and get back to world
  17199. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17200. var vertex = faceVertices[vIndex];
  17201. //TODO check for Int32Array
  17202. vertexData.indices.push(currentVertexDataIndex);
  17203. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17204. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17205. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17206. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17207. currentVertexDataIndex++;
  17208. }
  17209. }
  17210. // Return mesh
  17211. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17212. vertexData.applyToMesh(decal);
  17213. decal.position = position.clone();
  17214. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17215. return decal;
  17216. };
  17217. // Privates
  17218. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17219. // extrusion geometry
  17220. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17221. var tangents = path3D.getTangents();
  17222. var normals = path3D.getNormals();
  17223. var binormals = path3D.getBinormals();
  17224. var distances = path3D.getDistances();
  17225. var angle = 0;
  17226. var returnScale = function () { return scale; };
  17227. var returnRotation = function () { return rotation; };
  17228. var rotate = custom ? rotateFunction : returnRotation;
  17229. var scl = custom ? scaleFunction : returnScale;
  17230. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17231. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17232. for (var i = 0; i < curve.length; i++) {
  17233. var shapePath = new Array();
  17234. var angleStep = rotate(i, distances[i]);
  17235. var scaleRatio = scl(i, distances[i]);
  17236. for (var p = 0; p < shape.length; p++) {
  17237. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17238. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17239. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17240. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17241. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17242. shapePath[p] = rotated;
  17243. }
  17244. shapePaths[index] = shapePath;
  17245. angle += angleStep;
  17246. index++;
  17247. }
  17248. // cap
  17249. var capPath = function (shapePath) {
  17250. var pointCap = Array();
  17251. var barycenter = BABYLON.Vector3.Zero();
  17252. var i;
  17253. for (i = 0; i < shapePath.length; i++) {
  17254. barycenter.addInPlace(shapePath[i]);
  17255. }
  17256. barycenter.scaleInPlace(1 / shapePath.length);
  17257. for (i = 0; i < shapePath.length; i++) {
  17258. pointCap.push(barycenter);
  17259. }
  17260. return pointCap;
  17261. };
  17262. switch (cap) {
  17263. case BABYLON.Mesh.NO_CAP:
  17264. break;
  17265. case BABYLON.Mesh.CAP_START:
  17266. shapePaths[0] = capPath(shapePaths[2]);
  17267. shapePaths[1] = shapePaths[2].slice(0);
  17268. break;
  17269. case BABYLON.Mesh.CAP_END:
  17270. shapePaths[index] = shapePaths[index - 1];
  17271. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17272. break;
  17273. case BABYLON.Mesh.CAP_ALL:
  17274. shapePaths[0] = capPath(shapePaths[2]);
  17275. shapePaths[1] = shapePaths[2].slice(0);
  17276. shapePaths[index] = shapePaths[index - 1];
  17277. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17278. break;
  17279. default:
  17280. break;
  17281. }
  17282. return shapePaths;
  17283. };
  17284. var path3D;
  17285. var pathArray;
  17286. if (instance) {
  17287. path3D = (instance.path3D).update(curve);
  17288. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17289. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17290. return instance;
  17291. }
  17292. // extruded shape creation
  17293. path3D = new BABYLON.Path3D(curve);
  17294. var newShapePaths = new Array();
  17295. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17296. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17297. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17298. extrudedGeneric.pathArray = pathArray;
  17299. extrudedGeneric.path3D = path3D;
  17300. extrudedGeneric.cap = cap;
  17301. return extrudedGeneric;
  17302. };
  17303. return MeshBuilder;
  17304. })();
  17305. BABYLON.MeshBuilder = MeshBuilder;
  17306. })(BABYLON || (BABYLON = {}));
  17307. var BABYLON;
  17308. (function (BABYLON) {
  17309. var BaseTexture = (function () {
  17310. function BaseTexture(scene) {
  17311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17312. this.hasAlpha = false;
  17313. this.getAlphaFromRGB = false;
  17314. this.level = 1;
  17315. this.isCube = false;
  17316. this.isRenderTarget = false;
  17317. this.animations = new Array();
  17318. this.coordinatesIndex = 0;
  17319. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17320. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17321. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17322. this.anisotropicFilteringLevel = 4;
  17323. this._scene = scene;
  17324. this._scene.textures.push(this);
  17325. }
  17326. BaseTexture.prototype.getScene = function () {
  17327. return this._scene;
  17328. };
  17329. BaseTexture.prototype.getTextureMatrix = function () {
  17330. return null;
  17331. };
  17332. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17333. return null;
  17334. };
  17335. BaseTexture.prototype.getInternalTexture = function () {
  17336. return this._texture;
  17337. };
  17338. BaseTexture.prototype.isReady = function () {
  17339. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17340. return true;
  17341. }
  17342. if (this._texture) {
  17343. return this._texture.isReady;
  17344. }
  17345. return false;
  17346. };
  17347. BaseTexture.prototype.getSize = function () {
  17348. if (this._texture._width) {
  17349. return { width: this._texture._width, height: this._texture._height };
  17350. }
  17351. if (this._texture._size) {
  17352. return { width: this._texture._size, height: this._texture._size };
  17353. }
  17354. return { width: 0, height: 0 };
  17355. };
  17356. BaseTexture.prototype.getBaseSize = function () {
  17357. if (!this.isReady())
  17358. return { width: 0, height: 0 };
  17359. if (this._texture._size) {
  17360. return { width: this._texture._size, height: this._texture._size };
  17361. }
  17362. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17363. };
  17364. BaseTexture.prototype.scale = function (ratio) {
  17365. };
  17366. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17367. get: function () {
  17368. return false;
  17369. },
  17370. enumerable: true,
  17371. configurable: true
  17372. });
  17373. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17374. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17375. for (var index = 0; index < texturesCache.length; index++) {
  17376. var texturesCacheEntry = texturesCache[index];
  17377. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17378. texturesCache.splice(index, 1);
  17379. return;
  17380. }
  17381. }
  17382. };
  17383. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17384. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17385. for (var index = 0; index < texturesCache.length; index++) {
  17386. var texturesCacheEntry = texturesCache[index];
  17387. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17388. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17389. texturesCacheEntry.references++;
  17390. return texturesCacheEntry;
  17391. }
  17392. }
  17393. }
  17394. return null;
  17395. };
  17396. BaseTexture.prototype.delayLoad = function () {
  17397. };
  17398. BaseTexture.prototype.clone = function () {
  17399. return null;
  17400. };
  17401. BaseTexture.prototype.releaseInternalTexture = function () {
  17402. if (this._texture) {
  17403. this._scene.getEngine().releaseInternalTexture(this._texture);
  17404. delete this._texture;
  17405. }
  17406. };
  17407. BaseTexture.prototype.dispose = function () {
  17408. // Animations
  17409. this.getScene().stopAnimation(this);
  17410. // Remove from scene
  17411. var index = this._scene.textures.indexOf(this);
  17412. if (index >= 0) {
  17413. this._scene.textures.splice(index, 1);
  17414. }
  17415. if (this._texture === undefined) {
  17416. return;
  17417. }
  17418. // Release
  17419. this.releaseInternalTexture();
  17420. // Callback
  17421. if (this.onDispose) {
  17422. this.onDispose();
  17423. }
  17424. };
  17425. BaseTexture.prototype.serialize = function () {
  17426. var serializationObject = {};
  17427. if (!this.name) {
  17428. return null;
  17429. }
  17430. serializationObject.name = this.name;
  17431. serializationObject.hasAlpha = this.hasAlpha;
  17432. serializationObject.level = this.level;
  17433. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17434. serializationObject.coordinatesMode = this.coordinatesMode;
  17435. serializationObject.wrapU = this.wrapU;
  17436. serializationObject.wrapV = this.wrapV;
  17437. // Animations
  17438. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17439. return serializationObject;
  17440. };
  17441. return BaseTexture;
  17442. })();
  17443. BABYLON.BaseTexture = BaseTexture;
  17444. })(BABYLON || (BABYLON = {}));
  17445. var BABYLON;
  17446. (function (BABYLON) {
  17447. var Texture = (function (_super) {
  17448. __extends(Texture, _super);
  17449. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17450. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17451. if (onLoad === void 0) { onLoad = null; }
  17452. if (onError === void 0) { onError = null; }
  17453. if (buffer === void 0) { buffer = null; }
  17454. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17455. _super.call(this, scene);
  17456. this.uOffset = 0;
  17457. this.vOffset = 0;
  17458. this.uScale = 1.0;
  17459. this.vScale = 1.0;
  17460. this.uAng = 0;
  17461. this.vAng = 0;
  17462. this.wAng = 0;
  17463. this.name = url;
  17464. this.url = url;
  17465. this._noMipmap = noMipmap;
  17466. this._invertY = invertY;
  17467. this._samplingMode = samplingMode;
  17468. this._buffer = buffer;
  17469. this._deleteBuffer = deleteBuffer;
  17470. if (!url) {
  17471. return;
  17472. }
  17473. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17474. if (!this._texture) {
  17475. if (!scene.useDelayedTextureLoading) {
  17476. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17477. if (deleteBuffer) {
  17478. delete this._buffer;
  17479. }
  17480. }
  17481. else {
  17482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17483. }
  17484. }
  17485. else {
  17486. BABYLON.Tools.SetImmediate(function () {
  17487. if (onLoad) {
  17488. onLoad();
  17489. }
  17490. });
  17491. }
  17492. }
  17493. Texture.prototype.delayLoad = function () {
  17494. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17495. return;
  17496. }
  17497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17498. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17499. if (!this._texture) {
  17500. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17501. if (this._deleteBuffer) {
  17502. delete this._buffer;
  17503. }
  17504. }
  17505. };
  17506. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17507. if (!this._texture) {
  17508. return;
  17509. }
  17510. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17511. };
  17512. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17513. x *= this.uScale;
  17514. y *= this.vScale;
  17515. x -= 0.5 * this.uScale;
  17516. y -= 0.5 * this.vScale;
  17517. z -= 0.5;
  17518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17519. t.x += 0.5 * this.uScale + this.uOffset;
  17520. t.y += 0.5 * this.vScale + this.vOffset;
  17521. t.z += 0.5;
  17522. };
  17523. Texture.prototype.getTextureMatrix = function () {
  17524. if (this.uOffset === this._cachedUOffset &&
  17525. this.vOffset === this._cachedVOffset &&
  17526. this.uScale === this._cachedUScale &&
  17527. this.vScale === this._cachedVScale &&
  17528. this.uAng === this._cachedUAng &&
  17529. this.vAng === this._cachedVAng &&
  17530. this.wAng === this._cachedWAng) {
  17531. return this._cachedTextureMatrix;
  17532. }
  17533. this._cachedUOffset = this.uOffset;
  17534. this._cachedVOffset = this.vOffset;
  17535. this._cachedUScale = this.uScale;
  17536. this._cachedVScale = this.vScale;
  17537. this._cachedUAng = this.uAng;
  17538. this._cachedVAng = this.vAng;
  17539. this._cachedWAng = this.wAng;
  17540. if (!this._cachedTextureMatrix) {
  17541. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17542. this._rowGenerationMatrix = new BABYLON.Matrix();
  17543. this._t0 = BABYLON.Vector3.Zero();
  17544. this._t1 = BABYLON.Vector3.Zero();
  17545. this._t2 = BABYLON.Vector3.Zero();
  17546. }
  17547. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17548. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17549. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17550. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17551. this._t1.subtractInPlace(this._t0);
  17552. this._t2.subtractInPlace(this._t0);
  17553. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17554. this._cachedTextureMatrix.m[0] = this._t1.x;
  17555. this._cachedTextureMatrix.m[1] = this._t1.y;
  17556. this._cachedTextureMatrix.m[2] = this._t1.z;
  17557. this._cachedTextureMatrix.m[4] = this._t2.x;
  17558. this._cachedTextureMatrix.m[5] = this._t2.y;
  17559. this._cachedTextureMatrix.m[6] = this._t2.z;
  17560. this._cachedTextureMatrix.m[8] = this._t0.x;
  17561. this._cachedTextureMatrix.m[9] = this._t0.y;
  17562. this._cachedTextureMatrix.m[10] = this._t0.z;
  17563. return this._cachedTextureMatrix;
  17564. };
  17565. Texture.prototype.getReflectionTextureMatrix = function () {
  17566. if (this.uOffset === this._cachedUOffset &&
  17567. this.vOffset === this._cachedVOffset &&
  17568. this.uScale === this._cachedUScale &&
  17569. this.vScale === this._cachedVScale &&
  17570. this.coordinatesMode === this._cachedCoordinatesMode) {
  17571. return this._cachedTextureMatrix;
  17572. }
  17573. if (!this._cachedTextureMatrix) {
  17574. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17575. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17576. }
  17577. this._cachedCoordinatesMode = this.coordinatesMode;
  17578. switch (this.coordinatesMode) {
  17579. case Texture.PLANAR_MODE:
  17580. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17581. this._cachedTextureMatrix[0] = this.uScale;
  17582. this._cachedTextureMatrix[5] = this.vScale;
  17583. this._cachedTextureMatrix[12] = this.uOffset;
  17584. this._cachedTextureMatrix[13] = this.vOffset;
  17585. break;
  17586. case Texture.PROJECTION_MODE:
  17587. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17588. this._projectionModeMatrix.m[0] = 0.5;
  17589. this._projectionModeMatrix.m[5] = -0.5;
  17590. this._projectionModeMatrix.m[10] = 0.0;
  17591. this._projectionModeMatrix.m[12] = 0.5;
  17592. this._projectionModeMatrix.m[13] = 0.5;
  17593. this._projectionModeMatrix.m[14] = 1.0;
  17594. this._projectionModeMatrix.m[15] = 1.0;
  17595. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17596. break;
  17597. default:
  17598. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17599. break;
  17600. }
  17601. return this._cachedTextureMatrix;
  17602. };
  17603. Texture.prototype.clone = function () {
  17604. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17605. // Base texture
  17606. newTexture.hasAlpha = this.hasAlpha;
  17607. newTexture.level = this.level;
  17608. newTexture.wrapU = this.wrapU;
  17609. newTexture.wrapV = this.wrapV;
  17610. newTexture.coordinatesIndex = this.coordinatesIndex;
  17611. newTexture.coordinatesMode = this.coordinatesMode;
  17612. // Texture
  17613. newTexture.uOffset = this.uOffset;
  17614. newTexture.vOffset = this.vOffset;
  17615. newTexture.uScale = this.uScale;
  17616. newTexture.vScale = this.vScale;
  17617. newTexture.uAng = this.uAng;
  17618. newTexture.vAng = this.vAng;
  17619. newTexture.wAng = this.wAng;
  17620. return newTexture;
  17621. };
  17622. Texture.prototype.serialize = function () {
  17623. if (!this.name) {
  17624. return null;
  17625. }
  17626. var serializationObject = _super.prototype.serialize.call(this);
  17627. serializationObject.uOffset = this.uOffset;
  17628. serializationObject.vOffset = this.vOffset;
  17629. serializationObject.uScale = this.uScale;
  17630. serializationObject.vScale = this.vScale;
  17631. serializationObject.uAng = this.uAng;
  17632. serializationObject.vAng = this.vAng;
  17633. serializationObject.wAng = this.wAng;
  17634. return serializationObject;
  17635. };
  17636. // Statics
  17637. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17638. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17639. if (onLoad === void 0) { onLoad = null; }
  17640. if (onError === void 0) { onError = null; }
  17641. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17642. };
  17643. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17644. if (parsedTexture.isCube) {
  17645. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17646. }
  17647. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17648. return null;
  17649. }
  17650. var texture;
  17651. if (parsedTexture.mirrorPlane) {
  17652. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17653. texture._waitingRenderList = parsedTexture.renderList;
  17654. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17655. }
  17656. else if (parsedTexture.isRenderTarget) {
  17657. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17658. texture._waitingRenderList = parsedTexture.renderList;
  17659. }
  17660. else {
  17661. if (parsedTexture.base64String) {
  17662. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17663. }
  17664. else {
  17665. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17666. }
  17667. }
  17668. texture.name = parsedTexture.name;
  17669. texture.hasAlpha = parsedTexture.hasAlpha;
  17670. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17671. texture.level = parsedTexture.level;
  17672. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17673. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17674. texture.uOffset = parsedTexture.uOffset;
  17675. texture.vOffset = parsedTexture.vOffset;
  17676. texture.uScale = parsedTexture.uScale;
  17677. texture.vScale = parsedTexture.vScale;
  17678. texture.uAng = parsedTexture.uAng;
  17679. texture.vAng = parsedTexture.vAng;
  17680. texture.wAng = parsedTexture.wAng;
  17681. texture.wrapU = parsedTexture.wrapU;
  17682. texture.wrapV = parsedTexture.wrapV;
  17683. // Animations
  17684. if (parsedTexture.animations) {
  17685. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17686. var parsedAnimation = parsedTexture.animations[animationIndex];
  17687. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17688. }
  17689. }
  17690. return texture;
  17691. };
  17692. // Constants
  17693. Texture.NEAREST_SAMPLINGMODE = 1;
  17694. Texture.BILINEAR_SAMPLINGMODE = 2;
  17695. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17696. Texture.EXPLICIT_MODE = 0;
  17697. Texture.SPHERICAL_MODE = 1;
  17698. Texture.PLANAR_MODE = 2;
  17699. Texture.CUBIC_MODE = 3;
  17700. Texture.PROJECTION_MODE = 4;
  17701. Texture.SKYBOX_MODE = 5;
  17702. Texture.INVCUBIC_MODE = 6;
  17703. Texture.EQUIRECTANGULAR_MODE = 7;
  17704. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17705. Texture.CLAMP_ADDRESSMODE = 0;
  17706. Texture.WRAP_ADDRESSMODE = 1;
  17707. Texture.MIRROR_ADDRESSMODE = 2;
  17708. return Texture;
  17709. })(BABYLON.BaseTexture);
  17710. BABYLON.Texture = Texture;
  17711. })(BABYLON || (BABYLON = {}));
  17712. var BABYLON;
  17713. (function (BABYLON) {
  17714. var CubeTexture = (function (_super) {
  17715. __extends(CubeTexture, _super);
  17716. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17717. _super.call(this, scene);
  17718. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17719. this.name = rootUrl;
  17720. this.url = rootUrl;
  17721. this._noMipmap = noMipmap;
  17722. this.hasAlpha = false;
  17723. if (!rootUrl && !files) {
  17724. return;
  17725. }
  17726. this._texture = this._getFromCache(rootUrl, noMipmap);
  17727. if (!files) {
  17728. if (!extensions) {
  17729. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17730. }
  17731. files = [];
  17732. for (var index = 0; index < extensions.length; index++) {
  17733. files.push(rootUrl + extensions[index]);
  17734. }
  17735. this._extensions = extensions;
  17736. }
  17737. this._files = files;
  17738. if (!this._texture) {
  17739. if (!scene.useDelayedTextureLoading) {
  17740. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17741. }
  17742. else {
  17743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17744. }
  17745. }
  17746. this.isCube = true;
  17747. this._textureMatrix = BABYLON.Matrix.Identity();
  17748. }
  17749. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17750. return new CubeTexture("", scene, null, noMipmap, files);
  17751. };
  17752. CubeTexture.prototype.clone = function () {
  17753. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17754. // Base texture
  17755. newTexture.level = this.level;
  17756. newTexture.wrapU = this.wrapU;
  17757. newTexture.wrapV = this.wrapV;
  17758. newTexture.coordinatesIndex = this.coordinatesIndex;
  17759. newTexture.coordinatesMode = this.coordinatesMode;
  17760. return newTexture;
  17761. };
  17762. // Methods
  17763. CubeTexture.prototype.delayLoad = function () {
  17764. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17765. return;
  17766. }
  17767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17768. this._texture = this._getFromCache(this.url, this._noMipmap);
  17769. if (!this._texture) {
  17770. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17771. }
  17772. };
  17773. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17774. return this._textureMatrix;
  17775. };
  17776. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17777. var texture = null;
  17778. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17779. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17780. texture.name = parsedTexture.name;
  17781. texture.hasAlpha = parsedTexture.hasAlpha;
  17782. texture.level = parsedTexture.level;
  17783. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17784. }
  17785. return texture;
  17786. };
  17787. CubeTexture.prototype.serialize = function () {
  17788. if (!this.name) {
  17789. return null;
  17790. }
  17791. var serializationObject = {};
  17792. serializationObject.name = this.name;
  17793. serializationObject.hasAlpha = this.hasAlpha;
  17794. serializationObject.isCube = true;
  17795. serializationObject.level = this.level;
  17796. serializationObject.coordinatesMode = this.coordinatesMode;
  17797. return serializationObject;
  17798. };
  17799. return CubeTexture;
  17800. })(BABYLON.BaseTexture);
  17801. BABYLON.CubeTexture = CubeTexture;
  17802. })(BABYLON || (BABYLON = {}));
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var RenderTargetTexture = (function (_super) {
  17806. __extends(RenderTargetTexture, _super);
  17807. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17808. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17809. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17810. if (isCube === void 0) { isCube = false; }
  17811. _super.call(this, null, scene, !generateMipMaps);
  17812. this.isCube = isCube;
  17813. this.renderList = new Array();
  17814. this.renderParticles = true;
  17815. this.renderSprites = false;
  17816. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17817. this._currentRefreshId = -1;
  17818. this._refreshRate = 1;
  17819. this.name = name;
  17820. this.isRenderTarget = true;
  17821. this._size = size;
  17822. this._generateMipMaps = generateMipMaps;
  17823. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17824. if (isCube) {
  17825. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17826. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17827. this._textureMatrix = BABYLON.Matrix.Identity();
  17828. }
  17829. else {
  17830. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17831. }
  17832. // Rendering groups
  17833. this._renderingManager = new BABYLON.RenderingManager(scene);
  17834. }
  17835. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17836. get: function () {
  17837. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17843. get: function () {
  17844. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17850. get: function () {
  17851. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17857. this._currentRefreshId = -1;
  17858. };
  17859. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17860. get: function () {
  17861. return this._refreshRate;
  17862. },
  17863. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17864. set: function (value) {
  17865. this._refreshRate = value;
  17866. this.resetRefreshCounter();
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. RenderTargetTexture.prototype._shouldRender = function () {
  17872. if (this._currentRefreshId === -1) {
  17873. this._currentRefreshId = 1;
  17874. return true;
  17875. }
  17876. if (this.refreshRate === this._currentRefreshId) {
  17877. this._currentRefreshId = 1;
  17878. return true;
  17879. }
  17880. this._currentRefreshId++;
  17881. return false;
  17882. };
  17883. RenderTargetTexture.prototype.isReady = function () {
  17884. if (!this.getScene().renderTargetsEnabled) {
  17885. return false;
  17886. }
  17887. return _super.prototype.isReady.call(this);
  17888. };
  17889. RenderTargetTexture.prototype.getRenderSize = function () {
  17890. return this._size;
  17891. };
  17892. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17893. get: function () {
  17894. return true;
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. RenderTargetTexture.prototype.scale = function (ratio) {
  17900. var newSize = this._size * ratio;
  17901. this.resize(newSize, this._generateMipMaps);
  17902. };
  17903. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17904. if (this.isCube) {
  17905. return this._textureMatrix;
  17906. }
  17907. return _super.prototype.getReflectionTextureMatrix.call(this);
  17908. };
  17909. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17910. this.releaseInternalTexture();
  17911. if (this.isCube) {
  17912. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17913. }
  17914. else {
  17915. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17916. }
  17917. };
  17918. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17919. var scene = this.getScene();
  17920. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17921. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17922. }
  17923. if (this._waitingRenderList) {
  17924. this.renderList = [];
  17925. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17926. var id = this._waitingRenderList[index];
  17927. this.renderList.push(scene.getMeshByID(id));
  17928. }
  17929. delete this._waitingRenderList;
  17930. }
  17931. if (this.renderList && this.renderList.length === 0) {
  17932. return;
  17933. }
  17934. // Prepare renderingManager
  17935. this._renderingManager.reset();
  17936. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17937. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17938. var mesh = currentRenderList[meshIndex];
  17939. if (mesh) {
  17940. if (!mesh.isReady()) {
  17941. // Reset _currentRefreshId
  17942. this.resetRefreshCounter();
  17943. continue;
  17944. }
  17945. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17946. mesh._activate(scene.getRenderId());
  17947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17948. var subMesh = mesh.subMeshes[subIndex];
  17949. scene._activeIndices += subMesh.indexCount;
  17950. this._renderingManager.dispatch(subMesh);
  17951. }
  17952. }
  17953. }
  17954. }
  17955. if (this.isCube) {
  17956. for (var face = 0; face < 6; face++) {
  17957. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17958. scene.incrementRenderId();
  17959. }
  17960. }
  17961. else {
  17962. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17963. }
  17964. if (this.onAfterUnbind) {
  17965. this.onAfterUnbind();
  17966. }
  17967. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17968. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17969. }
  17970. scene.resetCachedMaterial();
  17971. };
  17972. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17973. var scene = this.getScene();
  17974. var engine = scene.getEngine();
  17975. // Bind
  17976. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17977. if (this.isCube) {
  17978. engine.bindFramebuffer(this._texture, faceIndex);
  17979. }
  17980. else {
  17981. engine.bindFramebuffer(this._texture);
  17982. }
  17983. }
  17984. if (this.onBeforeRender) {
  17985. this.onBeforeRender(faceIndex);
  17986. }
  17987. // Clear
  17988. if (this.onClear) {
  17989. this.onClear(engine);
  17990. }
  17991. else {
  17992. engine.clear(scene.clearColor, true, true);
  17993. }
  17994. if (!this._doNotChangeAspectRatio) {
  17995. scene.updateTransformMatrix(true);
  17996. }
  17997. // Render
  17998. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17999. if (useCameraPostProcess) {
  18000. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18001. }
  18002. if (!this._doNotChangeAspectRatio) {
  18003. scene.updateTransformMatrix(true);
  18004. }
  18005. if (this.onAfterRender) {
  18006. this.onAfterRender(faceIndex);
  18007. }
  18008. // Dump ?
  18009. if (dumpForDebug) {
  18010. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18011. }
  18012. // Unbind
  18013. if (!this.isCube || faceIndex === 5) {
  18014. if (this.isCube) {
  18015. if (faceIndex === 5) {
  18016. engine.generateMipMapsForCubemap(this._texture);
  18017. }
  18018. }
  18019. engine.unBindFramebuffer(this._texture, this.isCube);
  18020. }
  18021. };
  18022. RenderTargetTexture.prototype.clone = function () {
  18023. var textureSize = this.getSize();
  18024. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18025. // Base texture
  18026. newTexture.hasAlpha = this.hasAlpha;
  18027. newTexture.level = this.level;
  18028. // RenderTarget Texture
  18029. newTexture.coordinatesMode = this.coordinatesMode;
  18030. newTexture.renderList = this.renderList.slice(0);
  18031. return newTexture;
  18032. };
  18033. RenderTargetTexture.prototype.serialize = function () {
  18034. if (!this.name) {
  18035. return null;
  18036. }
  18037. var serializationObject = _super.prototype.serialize.call(this);
  18038. serializationObject.renderTargetSize = this.getRenderSize();
  18039. serializationObject.renderList = [];
  18040. for (var index = 0; index < this.renderList.length; index++) {
  18041. serializationObject.renderList.push(this.renderList[index].id);
  18042. }
  18043. return serializationObject;
  18044. };
  18045. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18046. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18047. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18048. return RenderTargetTexture;
  18049. })(BABYLON.Texture);
  18050. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18051. })(BABYLON || (BABYLON = {}));
  18052. var BABYLON;
  18053. (function (BABYLON) {
  18054. var ProceduralTexture = (function (_super) {
  18055. __extends(ProceduralTexture, _super);
  18056. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18058. if (isCube === void 0) { isCube = false; }
  18059. _super.call(this, null, scene, !generateMipMaps);
  18060. this.isCube = isCube;
  18061. this.isEnabled = true;
  18062. this._currentRefreshId = -1;
  18063. this._refreshRate = 1;
  18064. this._vertexDeclaration = [2];
  18065. this._vertexStrideSize = 2 * 4;
  18066. this._uniforms = new Array();
  18067. this._samplers = new Array();
  18068. this._textures = new Array();
  18069. this._floats = new Array();
  18070. this._floatsArrays = {};
  18071. this._colors3 = new Array();
  18072. this._colors4 = new Array();
  18073. this._vectors2 = new Array();
  18074. this._vectors3 = new Array();
  18075. this._matrices = new Array();
  18076. this._fallbackTextureUsed = false;
  18077. scene._proceduralTextures.push(this);
  18078. this.name = name;
  18079. this.isRenderTarget = true;
  18080. this._size = size;
  18081. this._generateMipMaps = generateMipMaps;
  18082. this.setFragment(fragment);
  18083. this._fallbackTexture = fallbackTexture;
  18084. if (isCube) {
  18085. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18086. this.setFloat("face", 0);
  18087. }
  18088. else {
  18089. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18090. }
  18091. // VBO
  18092. var vertices = [];
  18093. vertices.push(1, 1);
  18094. vertices.push(-1, 1);
  18095. vertices.push(-1, -1);
  18096. vertices.push(1, -1);
  18097. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18098. // Indices
  18099. var indices = [];
  18100. indices.push(0);
  18101. indices.push(1);
  18102. indices.push(2);
  18103. indices.push(0);
  18104. indices.push(2);
  18105. indices.push(3);
  18106. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18107. }
  18108. ProceduralTexture.prototype.reset = function () {
  18109. if (this._effect === undefined) {
  18110. return;
  18111. }
  18112. var engine = this.getScene().getEngine();
  18113. engine._releaseEffect(this._effect);
  18114. };
  18115. ProceduralTexture.prototype.isReady = function () {
  18116. var _this = this;
  18117. var engine = this.getScene().getEngine();
  18118. var shaders;
  18119. if (!this._fragment) {
  18120. return false;
  18121. }
  18122. if (this._fallbackTextureUsed) {
  18123. return true;
  18124. }
  18125. if (this._fragment.fragmentElement !== undefined) {
  18126. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18127. }
  18128. else {
  18129. shaders = { vertex: "procedural", fragment: this._fragment };
  18130. }
  18131. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18132. _this.releaseInternalTexture();
  18133. if (_this._fallbackTexture) {
  18134. _this._texture = _this._fallbackTexture._texture;
  18135. _this._texture.references++;
  18136. }
  18137. _this._fallbackTextureUsed = true;
  18138. });
  18139. return this._effect.isReady();
  18140. };
  18141. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18142. this._currentRefreshId = -1;
  18143. };
  18144. ProceduralTexture.prototype.setFragment = function (fragment) {
  18145. this._fragment = fragment;
  18146. };
  18147. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18148. get: function () {
  18149. return this._refreshRate;
  18150. },
  18151. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18152. set: function (value) {
  18153. this._refreshRate = value;
  18154. this.resetRefreshCounter();
  18155. },
  18156. enumerable: true,
  18157. configurable: true
  18158. });
  18159. ProceduralTexture.prototype._shouldRender = function () {
  18160. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18161. return false;
  18162. }
  18163. if (this._fallbackTextureUsed) {
  18164. return false;
  18165. }
  18166. if (this._currentRefreshId === -1) {
  18167. this._currentRefreshId = 1;
  18168. return true;
  18169. }
  18170. if (this.refreshRate === this._currentRefreshId) {
  18171. this._currentRefreshId = 1;
  18172. return true;
  18173. }
  18174. this._currentRefreshId++;
  18175. return false;
  18176. };
  18177. ProceduralTexture.prototype.getRenderSize = function () {
  18178. return this._size;
  18179. };
  18180. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18181. if (this._fallbackTextureUsed) {
  18182. return;
  18183. }
  18184. this.releaseInternalTexture();
  18185. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18186. };
  18187. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18188. if (this._uniforms.indexOf(uniformName) === -1) {
  18189. this._uniforms.push(uniformName);
  18190. }
  18191. };
  18192. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18193. if (this._samplers.indexOf(name) === -1) {
  18194. this._samplers.push(name);
  18195. }
  18196. this._textures[name] = texture;
  18197. return this;
  18198. };
  18199. ProceduralTexture.prototype.setFloat = function (name, value) {
  18200. this._checkUniform(name);
  18201. this._floats[name] = value;
  18202. return this;
  18203. };
  18204. ProceduralTexture.prototype.setFloats = function (name, value) {
  18205. this._checkUniform(name);
  18206. this._floatsArrays[name] = value;
  18207. return this;
  18208. };
  18209. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18210. this._checkUniform(name);
  18211. this._colors3[name] = value;
  18212. return this;
  18213. };
  18214. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18215. this._checkUniform(name);
  18216. this._colors4[name] = value;
  18217. return this;
  18218. };
  18219. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18220. this._checkUniform(name);
  18221. this._vectors2[name] = value;
  18222. return this;
  18223. };
  18224. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18225. this._checkUniform(name);
  18226. this._vectors3[name] = value;
  18227. return this;
  18228. };
  18229. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18230. this._checkUniform(name);
  18231. this._matrices[name] = value;
  18232. return this;
  18233. };
  18234. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18235. var scene = this.getScene();
  18236. var engine = scene.getEngine();
  18237. // Render
  18238. engine.enableEffect(this._effect);
  18239. engine.setState(false);
  18240. // Texture
  18241. for (var name in this._textures) {
  18242. this._effect.setTexture(name, this._textures[name]);
  18243. }
  18244. // Float
  18245. for (name in this._floats) {
  18246. this._effect.setFloat(name, this._floats[name]);
  18247. }
  18248. // Floats
  18249. for (name in this._floatsArrays) {
  18250. this._effect.setArray(name, this._floatsArrays[name]);
  18251. }
  18252. // Color3
  18253. for (name in this._colors3) {
  18254. this._effect.setColor3(name, this._colors3[name]);
  18255. }
  18256. // Color4
  18257. for (name in this._colors4) {
  18258. var color = this._colors4[name];
  18259. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18260. }
  18261. // Vector2
  18262. for (name in this._vectors2) {
  18263. this._effect.setVector2(name, this._vectors2[name]);
  18264. }
  18265. // Vector3
  18266. for (name in this._vectors3) {
  18267. this._effect.setVector3(name, this._vectors3[name]);
  18268. }
  18269. // Matrix
  18270. for (name in this._matrices) {
  18271. this._effect.setMatrix(name, this._matrices[name]);
  18272. }
  18273. // VBOs
  18274. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18275. if (this.isCube) {
  18276. for (var face = 0; face < 6; face++) {
  18277. engine.bindFramebuffer(this._texture, face);
  18278. this._effect.setFloat("face", face);
  18279. // Clear
  18280. engine.clear(scene.clearColor, true, true);
  18281. // Draw order
  18282. engine.draw(true, 0, 6);
  18283. // Mipmaps
  18284. if (face === 5) {
  18285. engine.generateMipMapsForCubemap(this._texture);
  18286. }
  18287. }
  18288. }
  18289. else {
  18290. engine.bindFramebuffer(this._texture);
  18291. // Clear
  18292. engine.clear(scene.clearColor, true, true);
  18293. // Draw order
  18294. engine.draw(true, 0, 6);
  18295. }
  18296. // Unbind
  18297. engine.unBindFramebuffer(this._texture, this.isCube);
  18298. if (this.onGenerated) {
  18299. this.onGenerated();
  18300. }
  18301. };
  18302. ProceduralTexture.prototype.clone = function () {
  18303. var textureSize = this.getSize();
  18304. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18305. // Base texture
  18306. newTexture.hasAlpha = this.hasAlpha;
  18307. newTexture.level = this.level;
  18308. // RenderTarget Texture
  18309. newTexture.coordinatesMode = this.coordinatesMode;
  18310. return newTexture;
  18311. };
  18312. ProceduralTexture.prototype.dispose = function () {
  18313. var index = this.getScene()._proceduralTextures.indexOf(this);
  18314. if (index >= 0) {
  18315. this.getScene()._proceduralTextures.splice(index, 1);
  18316. }
  18317. _super.prototype.dispose.call(this);
  18318. };
  18319. return ProceduralTexture;
  18320. })(BABYLON.Texture);
  18321. BABYLON.ProceduralTexture = ProceduralTexture;
  18322. })(BABYLON || (BABYLON = {}));
  18323. var BABYLON;
  18324. (function (BABYLON) {
  18325. var MirrorTexture = (function (_super) {
  18326. __extends(MirrorTexture, _super);
  18327. function MirrorTexture(name, size, scene, generateMipMaps) {
  18328. var _this = this;
  18329. _super.call(this, name, size, scene, generateMipMaps, true);
  18330. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18331. this._transformMatrix = BABYLON.Matrix.Zero();
  18332. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18333. this.onBeforeRender = function () {
  18334. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18335. _this._savedViewMatrix = scene.getViewMatrix();
  18336. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18337. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18338. scene.clipPlane = _this.mirrorPlane;
  18339. scene.getEngine().cullBackFaces = false;
  18340. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18341. };
  18342. this.onAfterRender = function () {
  18343. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18344. scene.getEngine().cullBackFaces = true;
  18345. scene._mirroredCameraPosition = null;
  18346. delete scene.clipPlane;
  18347. };
  18348. }
  18349. MirrorTexture.prototype.clone = function () {
  18350. var textureSize = this.getSize();
  18351. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18352. // Base texture
  18353. newTexture.hasAlpha = this.hasAlpha;
  18354. newTexture.level = this.level;
  18355. // Mirror Texture
  18356. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18357. newTexture.renderList = this.renderList.slice(0);
  18358. return newTexture;
  18359. };
  18360. MirrorTexture.prototype.serialize = function () {
  18361. if (!this.name) {
  18362. return null;
  18363. }
  18364. var serializationObject = _super.prototype.serialize.call(this);
  18365. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18366. return serializationObject;
  18367. };
  18368. return MirrorTexture;
  18369. })(BABYLON.RenderTargetTexture);
  18370. BABYLON.MirrorTexture = MirrorTexture;
  18371. })(BABYLON || (BABYLON = {}));
  18372. var BABYLON;
  18373. (function (BABYLON) {
  18374. /**
  18375. * Creates a refraction texture used by refraction channel of the standard material.
  18376. * @param name the texture name
  18377. * @param size size of the underlying texture
  18378. * @param scene root scene
  18379. */
  18380. var RefractionTexture = (function (_super) {
  18381. __extends(RefractionTexture, _super);
  18382. function RefractionTexture(name, size, scene, generateMipMaps) {
  18383. var _this = this;
  18384. _super.call(this, name, size, scene, generateMipMaps, true);
  18385. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18386. this.depth = 2.0;
  18387. this.onBeforeRender = function () {
  18388. scene.clipPlane = _this.refractionPlane;
  18389. };
  18390. this.onAfterRender = function () {
  18391. delete scene.clipPlane;
  18392. };
  18393. }
  18394. RefractionTexture.prototype.clone = function () {
  18395. var textureSize = this.getSize();
  18396. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18397. // Base texture
  18398. newTexture.hasAlpha = this.hasAlpha;
  18399. newTexture.level = this.level;
  18400. // Refraction Texture
  18401. newTexture.refractionPlane = this.refractionPlane.clone();
  18402. newTexture.renderList = this.renderList.slice(0);
  18403. newTexture.depth = this.depth;
  18404. return newTexture;
  18405. };
  18406. RefractionTexture.prototype.serialize = function () {
  18407. if (!this.name) {
  18408. return null;
  18409. }
  18410. var serializationObject = _super.prototype.serialize.call(this);
  18411. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18412. serializationObject.depth = this.depth;
  18413. return serializationObject;
  18414. };
  18415. return RefractionTexture;
  18416. })(BABYLON.RenderTargetTexture);
  18417. BABYLON.RefractionTexture = RefractionTexture;
  18418. })(BABYLON || (BABYLON = {}));
  18419. var BABYLON;
  18420. (function (BABYLON) {
  18421. var DynamicTexture = (function (_super) {
  18422. __extends(DynamicTexture, _super);
  18423. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18425. _super.call(this, null, scene, !generateMipMaps);
  18426. this.name = name;
  18427. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18428. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18429. this._generateMipMaps = generateMipMaps;
  18430. if (options.getContext) {
  18431. this._canvas = options;
  18432. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18433. }
  18434. else {
  18435. this._canvas = document.createElement("canvas");
  18436. if (options.width) {
  18437. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18438. }
  18439. else {
  18440. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18441. }
  18442. }
  18443. var textureSize = this.getSize();
  18444. this._canvas.width = textureSize.width;
  18445. this._canvas.height = textureSize.height;
  18446. this._context = this._canvas.getContext("2d");
  18447. }
  18448. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18449. get: function () {
  18450. return true;
  18451. },
  18452. enumerable: true,
  18453. configurable: true
  18454. });
  18455. DynamicTexture.prototype.scale = function (ratio) {
  18456. var textureSize = this.getSize();
  18457. textureSize.width *= ratio;
  18458. textureSize.height *= ratio;
  18459. this._canvas.width = textureSize.width;
  18460. this._canvas.height = textureSize.height;
  18461. this.releaseInternalTexture();
  18462. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18463. };
  18464. DynamicTexture.prototype.getContext = function () {
  18465. return this._context;
  18466. };
  18467. DynamicTexture.prototype.clear = function () {
  18468. var size = this.getSize();
  18469. this._context.fillRect(0, 0, size.width, size.height);
  18470. };
  18471. DynamicTexture.prototype.update = function (invertY) {
  18472. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18473. };
  18474. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18475. if (update === void 0) { update = true; }
  18476. var size = this.getSize();
  18477. if (clearColor) {
  18478. this._context.fillStyle = clearColor;
  18479. this._context.fillRect(0, 0, size.width, size.height);
  18480. }
  18481. this._context.font = font;
  18482. if (x === null) {
  18483. var textSize = this._context.measureText(text);
  18484. x = (size.width - textSize.width) / 2;
  18485. }
  18486. this._context.fillStyle = color;
  18487. this._context.fillText(text, x, y);
  18488. if (update) {
  18489. this.update(invertY);
  18490. }
  18491. };
  18492. DynamicTexture.prototype.clone = function () {
  18493. var textureSize = this.getSize();
  18494. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18495. // Base texture
  18496. newTexture.hasAlpha = this.hasAlpha;
  18497. newTexture.level = this.level;
  18498. // Dynamic Texture
  18499. newTexture.wrapU = this.wrapU;
  18500. newTexture.wrapV = this.wrapV;
  18501. return newTexture;
  18502. };
  18503. return DynamicTexture;
  18504. })(BABYLON.Texture);
  18505. BABYLON.DynamicTexture = DynamicTexture;
  18506. })(BABYLON || (BABYLON = {}));
  18507. var BABYLON;
  18508. (function (BABYLON) {
  18509. var VideoTexture = (function (_super) {
  18510. __extends(VideoTexture, _super);
  18511. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18512. var _this = this;
  18513. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18514. if (invertY === void 0) { invertY = false; }
  18515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18516. _super.call(this, null, scene, !generateMipMaps, invertY);
  18517. this._autoLaunch = true;
  18518. this.name = name;
  18519. this.video = document.createElement("video");
  18520. this.video.autoplay = false;
  18521. this.video.loop = true;
  18522. this.video.addEventListener("canplaythrough", function () {
  18523. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18524. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18525. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18526. }
  18527. else {
  18528. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18529. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18530. generateMipMaps = false;
  18531. }
  18532. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18533. _this._texture.isReady = true;
  18534. });
  18535. urls.forEach(function (url) {
  18536. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18537. var source = document.createElement("source");
  18538. source.src = url;
  18539. _this.video.appendChild(source);
  18540. });
  18541. this._lastUpdate = BABYLON.Tools.Now;
  18542. }
  18543. VideoTexture.prototype.update = function () {
  18544. if (this._autoLaunch) {
  18545. this._autoLaunch = false;
  18546. this.video.play();
  18547. }
  18548. var now = BABYLON.Tools.Now;
  18549. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18550. return false;
  18551. }
  18552. this._lastUpdate = now;
  18553. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18554. return true;
  18555. };
  18556. return VideoTexture;
  18557. })(BABYLON.Texture);
  18558. BABYLON.VideoTexture = VideoTexture;
  18559. })(BABYLON || (BABYLON = {}));
  18560. var BABYLON;
  18561. (function (BABYLON) {
  18562. var CustomProceduralTexture = (function (_super) {
  18563. __extends(CustomProceduralTexture, _super);
  18564. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18565. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18566. this._animate = true;
  18567. this._time = 0;
  18568. this._texturePath = texturePath;
  18569. //Try to load json
  18570. this.loadJson(texturePath);
  18571. this.refreshRate = 1;
  18572. }
  18573. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18574. var _this = this;
  18575. var that = this;
  18576. function noConfigFile() {
  18577. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18578. try {
  18579. that.setFragment(that._texturePath);
  18580. }
  18581. catch (ex) {
  18582. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18583. }
  18584. }
  18585. var configFileUrl = jsonUrl + "/config.json";
  18586. var xhr = new XMLHttpRequest();
  18587. xhr.open("GET", configFileUrl, true);
  18588. xhr.addEventListener("load", function () {
  18589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18590. try {
  18591. _this._config = JSON.parse(xhr.response);
  18592. _this.updateShaderUniforms();
  18593. _this.updateTextures();
  18594. _this.setFragment(_this._texturePath + "/custom");
  18595. _this._animate = _this._config.animate;
  18596. _this.refreshRate = _this._config.refreshrate;
  18597. }
  18598. catch (ex) {
  18599. noConfigFile();
  18600. }
  18601. }
  18602. else {
  18603. noConfigFile();
  18604. }
  18605. }, false);
  18606. xhr.addEventListener("error", function () {
  18607. noConfigFile();
  18608. }, false);
  18609. try {
  18610. xhr.send();
  18611. }
  18612. catch (ex) {
  18613. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18614. }
  18615. };
  18616. CustomProceduralTexture.prototype.isReady = function () {
  18617. if (!_super.prototype.isReady.call(this)) {
  18618. return false;
  18619. }
  18620. for (var name in this._textures) {
  18621. var texture = this._textures[name];
  18622. if (!texture.isReady()) {
  18623. return false;
  18624. }
  18625. }
  18626. return true;
  18627. };
  18628. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18629. if (this._animate) {
  18630. this._time += this.getScene().getAnimationRatio() * 0.03;
  18631. this.updateShaderUniforms();
  18632. }
  18633. _super.prototype.render.call(this, useCameraPostProcess);
  18634. };
  18635. CustomProceduralTexture.prototype.updateTextures = function () {
  18636. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18637. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18638. }
  18639. };
  18640. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18641. if (this._config) {
  18642. for (var j = 0; j < this._config.uniforms.length; j++) {
  18643. var uniform = this._config.uniforms[j];
  18644. switch (uniform.type) {
  18645. case "float":
  18646. this.setFloat(uniform.name, uniform.value);
  18647. break;
  18648. case "color3":
  18649. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18650. break;
  18651. case "color4":
  18652. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18653. break;
  18654. case "vector2":
  18655. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18656. break;
  18657. case "vector3":
  18658. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18659. break;
  18660. }
  18661. }
  18662. }
  18663. this.setFloat("time", this._time);
  18664. };
  18665. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18666. get: function () {
  18667. return this._animate;
  18668. },
  18669. set: function (value) {
  18670. this._animate = value;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. return CustomProceduralTexture;
  18676. })(BABYLON.ProceduralTexture);
  18677. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18678. })(BABYLON || (BABYLON = {}));
  18679. var BABYLON;
  18680. (function (BABYLON) {
  18681. var EffectFallbacks = (function () {
  18682. function EffectFallbacks() {
  18683. this._defines = {};
  18684. this._currentRank = 32;
  18685. this._maxRank = -1;
  18686. }
  18687. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18688. if (!this._defines[rank]) {
  18689. if (rank < this._currentRank) {
  18690. this._currentRank = rank;
  18691. }
  18692. if (rank > this._maxRank) {
  18693. this._maxRank = rank;
  18694. }
  18695. this._defines[rank] = new Array();
  18696. }
  18697. this._defines[rank].push(define);
  18698. };
  18699. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18700. this._meshRank = rank;
  18701. this._mesh = mesh;
  18702. if (rank > this._maxRank) {
  18703. this._maxRank = rank;
  18704. }
  18705. };
  18706. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18707. get: function () {
  18708. return this._currentRank <= this._maxRank;
  18709. },
  18710. enumerable: true,
  18711. configurable: true
  18712. });
  18713. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18714. var currentFallbacks = this._defines[this._currentRank];
  18715. for (var index = 0; index < currentFallbacks.length; index++) {
  18716. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18717. }
  18718. if (this._mesh && this._currentRank === this._meshRank) {
  18719. this._mesh.computeBonesUsingShaders = false;
  18720. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18721. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18722. }
  18723. this._currentRank++;
  18724. return currentDefines;
  18725. };
  18726. return EffectFallbacks;
  18727. })();
  18728. BABYLON.EffectFallbacks = EffectFallbacks;
  18729. var Effect = (function () {
  18730. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18731. var _this = this;
  18732. this._isReady = false;
  18733. this._compilationError = "";
  18734. this._valueCache = [];
  18735. this._engine = engine;
  18736. this.name = baseName;
  18737. this.defines = defines;
  18738. this._uniformsNames = uniformsNames.concat(samplers);
  18739. this._samplers = samplers;
  18740. this._attributesNames = attributesNames;
  18741. this.onError = onError;
  18742. this.onCompiled = onCompiled;
  18743. var vertexSource;
  18744. var fragmentSource;
  18745. if (baseName.vertexElement) {
  18746. vertexSource = document.getElementById(baseName.vertexElement);
  18747. if (!vertexSource) {
  18748. vertexSource = baseName.vertexElement;
  18749. }
  18750. }
  18751. else {
  18752. vertexSource = baseName.vertex || baseName;
  18753. }
  18754. if (baseName.fragmentElement) {
  18755. fragmentSource = document.getElementById(baseName.fragmentElement);
  18756. if (!fragmentSource) {
  18757. fragmentSource = baseName.fragmentElement;
  18758. }
  18759. }
  18760. else {
  18761. fragmentSource = baseName.fragment || baseName;
  18762. }
  18763. this._loadVertexShader(vertexSource, function (vertexCode) {
  18764. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  18765. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18766. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  18767. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  18768. });
  18769. });
  18770. });
  18771. });
  18772. }
  18773. // Properties
  18774. Effect.prototype.isReady = function () {
  18775. return this._isReady;
  18776. };
  18777. Effect.prototype.getProgram = function () {
  18778. return this._program;
  18779. };
  18780. Effect.prototype.getAttributesNames = function () {
  18781. return this._attributesNames;
  18782. };
  18783. Effect.prototype.getAttributeLocation = function (index) {
  18784. return this._attributes[index];
  18785. };
  18786. Effect.prototype.getAttributeLocationByName = function (name) {
  18787. var index = this._attributesNames.indexOf(name);
  18788. return this._attributes[index];
  18789. };
  18790. Effect.prototype.getAttributesCount = function () {
  18791. return this._attributes.length;
  18792. };
  18793. Effect.prototype.getUniformIndex = function (uniformName) {
  18794. return this._uniformsNames.indexOf(uniformName);
  18795. };
  18796. Effect.prototype.getUniform = function (uniformName) {
  18797. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18798. };
  18799. Effect.prototype.getSamplers = function () {
  18800. return this._samplers;
  18801. };
  18802. Effect.prototype.getCompilationError = function () {
  18803. return this._compilationError;
  18804. };
  18805. // Methods
  18806. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18807. // DOM element ?
  18808. if (vertex instanceof HTMLElement) {
  18809. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18810. callback(vertexCode);
  18811. return;
  18812. }
  18813. // Is in local store ?
  18814. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18815. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18816. return;
  18817. }
  18818. var vertexShaderUrl;
  18819. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18820. vertexShaderUrl = vertex;
  18821. }
  18822. else {
  18823. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18824. }
  18825. // Vertex shader
  18826. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18827. };
  18828. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18829. // DOM element ?
  18830. if (fragment instanceof HTMLElement) {
  18831. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18832. callback(fragmentCode);
  18833. return;
  18834. }
  18835. // Is in local store ?
  18836. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18837. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18838. return;
  18839. }
  18840. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18841. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18842. return;
  18843. }
  18844. var fragmentShaderUrl;
  18845. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18846. fragmentShaderUrl = fragment;
  18847. }
  18848. else {
  18849. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18850. }
  18851. // Fragment shader
  18852. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18853. };
  18854. Effect.prototype._dumpShadersName = function () {
  18855. if (this.name.vertexElement) {
  18856. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18857. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18858. }
  18859. else if (this.name.vertex) {
  18860. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18861. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18862. }
  18863. else {
  18864. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18865. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18866. }
  18867. };
  18868. Effect.prototype._processIncludes = function (sourceCode, callback) {
  18869. var _this = this;
  18870. var regex = /#include<(.+)>(\((.*)\))*/g;
  18871. var match = regex.exec(sourceCode);
  18872. var returnValue = new String(sourceCode);
  18873. while (match != null) {
  18874. var includeFile = match[1];
  18875. if (Effect.IncludesShadersStore[includeFile]) {
  18876. // Substitution
  18877. var includeContent = Effect.IncludesShadersStore[includeFile];
  18878. if (match[2]) {
  18879. var splits = match[2].substr(1, match[2].length - 2).split(",");
  18880. for (var index = 0; index < splits.length; index += 2) {
  18881. var source = new RegExp(splits[index], "g");
  18882. var dest = splits[index + 1];
  18883. includeContent = includeContent.replace(source, dest);
  18884. }
  18885. }
  18886. // Replace
  18887. returnValue = returnValue.replace(match[0], includeContent);
  18888. }
  18889. else {
  18890. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  18891. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  18892. Effect.IncludesShadersStore[includeFile] = fileContent;
  18893. _this._processIncludes(returnValue, callback);
  18894. });
  18895. return;
  18896. }
  18897. match = regex.exec(sourceCode);
  18898. }
  18899. callback(returnValue);
  18900. };
  18901. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18902. try {
  18903. var engine = this._engine;
  18904. // Precision
  18905. if (!engine.getCaps().highPrecisionShaderSupported) {
  18906. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18907. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18908. }
  18909. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18910. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18911. this._attributes = engine.getAttributes(this._program, attributesNames);
  18912. for (var index = 0; index < this._samplers.length; index++) {
  18913. var sampler = this.getUniform(this._samplers[index]);
  18914. if (sampler == null) {
  18915. this._samplers.splice(index, 1);
  18916. index--;
  18917. }
  18918. }
  18919. engine.bindSamplers(this);
  18920. this._isReady = true;
  18921. if (this.onCompiled) {
  18922. this.onCompiled(this);
  18923. }
  18924. }
  18925. catch (e) {
  18926. // Is it a problem with precision?
  18927. if (e.message.indexOf("highp") !== -1) {
  18928. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18929. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18930. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18931. return;
  18932. }
  18933. // Let's go through fallbacks then
  18934. if (fallbacks && fallbacks.isMoreFallbacks) {
  18935. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18936. this._dumpShadersName();
  18937. defines = fallbacks.reduce(defines);
  18938. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18939. }
  18940. else {
  18941. BABYLON.Tools.Error("Unable to compile effect: ");
  18942. this._dumpShadersName();
  18943. BABYLON.Tools.Error("Defines: " + defines);
  18944. BABYLON.Tools.Error("Error: " + e.message);
  18945. this._compilationError = e.message;
  18946. if (this.onError) {
  18947. this.onError(this, this._compilationError);
  18948. }
  18949. }
  18950. }
  18951. };
  18952. Object.defineProperty(Effect.prototype, "isSupported", {
  18953. get: function () {
  18954. return this._compilationError === "";
  18955. },
  18956. enumerable: true,
  18957. configurable: true
  18958. });
  18959. Effect.prototype._bindTexture = function (channel, texture) {
  18960. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18961. };
  18962. Effect.prototype.setTexture = function (channel, texture) {
  18963. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18964. };
  18965. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18966. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18967. };
  18968. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18969. if (!this._valueCache[uniformName]) {
  18970. this._valueCache[uniformName] = new BABYLON.Matrix();
  18971. }
  18972. for (var index = 0; index < 16; index++) {
  18973. this._valueCache[uniformName].m[index] = matrix.m[index];
  18974. }
  18975. };
  18976. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18977. if (!this._valueCache[uniformName]) {
  18978. this._valueCache[uniformName] = [x, y];
  18979. return;
  18980. }
  18981. this._valueCache[uniformName][0] = x;
  18982. this._valueCache[uniformName][1] = y;
  18983. };
  18984. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18985. if (!this._valueCache[uniformName]) {
  18986. this._valueCache[uniformName] = [x, y, z];
  18987. return;
  18988. }
  18989. this._valueCache[uniformName][0] = x;
  18990. this._valueCache[uniformName][1] = y;
  18991. this._valueCache[uniformName][2] = z;
  18992. };
  18993. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18994. if (!this._valueCache[uniformName]) {
  18995. this._valueCache[uniformName] = [x, y, z, w];
  18996. return;
  18997. }
  18998. this._valueCache[uniformName][0] = x;
  18999. this._valueCache[uniformName][1] = y;
  19000. this._valueCache[uniformName][2] = z;
  19001. this._valueCache[uniformName][3] = w;
  19002. };
  19003. Effect.prototype.setArray = function (uniformName, array) {
  19004. this._engine.setArray(this.getUniform(uniformName), array);
  19005. return this;
  19006. };
  19007. Effect.prototype.setArray2 = function (uniformName, array) {
  19008. this._engine.setArray2(this.getUniform(uniformName), array);
  19009. return this;
  19010. };
  19011. Effect.prototype.setArray3 = function (uniformName, array) {
  19012. this._engine.setArray3(this.getUniform(uniformName), array);
  19013. return this;
  19014. };
  19015. Effect.prototype.setArray4 = function (uniformName, array) {
  19016. this._engine.setArray4(this.getUniform(uniformName), array);
  19017. return this;
  19018. };
  19019. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19020. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19021. return this;
  19022. };
  19023. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19024. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19025. // return this;
  19026. // this._cacheMatrix(uniformName, matrix);
  19027. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19028. return this;
  19029. };
  19030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19032. return this;
  19033. };
  19034. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19035. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19036. return this;
  19037. };
  19038. Effect.prototype.setFloat = function (uniformName, value) {
  19039. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19040. return this;
  19041. this._valueCache[uniformName] = value;
  19042. this._engine.setFloat(this.getUniform(uniformName), value);
  19043. return this;
  19044. };
  19045. Effect.prototype.setBool = function (uniformName, bool) {
  19046. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19047. return this;
  19048. this._valueCache[uniformName] = bool;
  19049. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19050. return this;
  19051. };
  19052. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19053. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19054. return this;
  19055. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19056. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19057. return this;
  19058. };
  19059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19060. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19061. return this;
  19062. this._cacheFloat2(uniformName, x, y);
  19063. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19064. return this;
  19065. };
  19066. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19067. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19068. return this;
  19069. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19070. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19071. return this;
  19072. };
  19073. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19074. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19075. return this;
  19076. this._cacheFloat3(uniformName, x, y, z);
  19077. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19078. return this;
  19079. };
  19080. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19081. 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)
  19082. return this;
  19083. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19084. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19085. return this;
  19086. };
  19087. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19088. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19089. return this;
  19090. this._cacheFloat4(uniformName, x, y, z, w);
  19091. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19092. return this;
  19093. };
  19094. Effect.prototype.setColor3 = function (uniformName, color3) {
  19095. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19096. return this;
  19097. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19098. this._engine.setColor3(this.getUniform(uniformName), color3);
  19099. return this;
  19100. };
  19101. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19102. 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)
  19103. return this;
  19104. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19105. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19106. return this;
  19107. };
  19108. // Statics
  19109. Effect.ShadersStore = {};
  19110. Effect.IncludesShadersStore = {};
  19111. return Effect;
  19112. })();
  19113. BABYLON.Effect = Effect;
  19114. })(BABYLON || (BABYLON = {}));
  19115. var BABYLON;
  19116. (function (BABYLON) {
  19117. var MaterialDefines = (function () {
  19118. function MaterialDefines() {
  19119. }
  19120. MaterialDefines.prototype.isEqual = function (other) {
  19121. for (var index = 0; index < this._keys.length; index++) {
  19122. var prop = this._keys[index];
  19123. if (this[prop] !== other[prop]) {
  19124. return false;
  19125. }
  19126. }
  19127. return true;
  19128. };
  19129. MaterialDefines.prototype.cloneTo = function (other) {
  19130. for (var index = 0; index < this._keys.length; index++) {
  19131. var prop = this._keys[index];
  19132. other[prop] = this[prop];
  19133. }
  19134. };
  19135. MaterialDefines.prototype.reset = function () {
  19136. for (var index = 0; index < this._keys.length; index++) {
  19137. var prop = this._keys[index];
  19138. if (typeof (this[prop]) === "number") {
  19139. this[prop] = 0;
  19140. }
  19141. else {
  19142. this[prop] = false;
  19143. }
  19144. }
  19145. };
  19146. MaterialDefines.prototype.toString = function () {
  19147. var result = "";
  19148. for (var index = 0; index < this._keys.length; index++) {
  19149. var prop = this._keys[index];
  19150. if (typeof (this[prop]) === "number") {
  19151. result += "#define " + prop + " " + this[prop] + "\n";
  19152. }
  19153. else if (this[prop]) {
  19154. result += "#define " + prop + "\n";
  19155. }
  19156. }
  19157. return result;
  19158. };
  19159. return MaterialDefines;
  19160. })();
  19161. BABYLON.MaterialDefines = MaterialDefines;
  19162. var Material = (function () {
  19163. function Material(name, scene, doNotAdd) {
  19164. this.name = name;
  19165. this.checkReadyOnEveryCall = false;
  19166. this.checkReadyOnlyOnce = false;
  19167. this.state = "";
  19168. this.alpha = 1.0;
  19169. this.backFaceCulling = true;
  19170. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19171. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19172. this.disableDepthWrite = false;
  19173. this.fogEnabled = true;
  19174. this._wasPreviouslyReady = false;
  19175. this._fillMode = Material.TriangleFillMode;
  19176. this.pointSize = 1.0;
  19177. this.zOffset = 0;
  19178. this.id = name;
  19179. this._scene = scene;
  19180. if (!doNotAdd) {
  19181. scene.materials.push(this);
  19182. }
  19183. }
  19184. Object.defineProperty(Material, "TriangleFillMode", {
  19185. get: function () {
  19186. return Material._TriangleFillMode;
  19187. },
  19188. enumerable: true,
  19189. configurable: true
  19190. });
  19191. Object.defineProperty(Material, "WireFrameFillMode", {
  19192. get: function () {
  19193. return Material._WireFrameFillMode;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. Object.defineProperty(Material, "PointFillMode", {
  19199. get: function () {
  19200. return Material._PointFillMode;
  19201. },
  19202. enumerable: true,
  19203. configurable: true
  19204. });
  19205. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19206. get: function () {
  19207. return Material._ClockWiseSideOrientation;
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19213. get: function () {
  19214. return Material._CounterClockWiseSideOrientation;
  19215. },
  19216. enumerable: true,
  19217. configurable: true
  19218. });
  19219. Object.defineProperty(Material.prototype, "wireframe", {
  19220. get: function () {
  19221. return this._fillMode === Material.WireFrameFillMode;
  19222. },
  19223. set: function (value) {
  19224. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(Material.prototype, "pointsCloud", {
  19230. get: function () {
  19231. return this._fillMode === Material.PointFillMode;
  19232. },
  19233. set: function (value) {
  19234. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. Object.defineProperty(Material.prototype, "fillMode", {
  19240. get: function () {
  19241. return this._fillMode;
  19242. },
  19243. set: function (value) {
  19244. this._fillMode = value;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(Material.prototype, "isFrozen", {
  19250. get: function () {
  19251. return this.checkReadyOnlyOnce;
  19252. },
  19253. enumerable: true,
  19254. configurable: true
  19255. });
  19256. Material.prototype.freeze = function () {
  19257. this.checkReadyOnlyOnce = true;
  19258. };
  19259. Material.prototype.unfreeze = function () {
  19260. this.checkReadyOnlyOnce = false;
  19261. };
  19262. Material.prototype.isReady = function (mesh, useInstances) {
  19263. return true;
  19264. };
  19265. Material.prototype.getEffect = function () {
  19266. return this._effect;
  19267. };
  19268. Material.prototype.getScene = function () {
  19269. return this._scene;
  19270. };
  19271. Material.prototype.needAlphaBlending = function () {
  19272. return (this.alpha < 1.0);
  19273. };
  19274. Material.prototype.needAlphaTesting = function () {
  19275. return false;
  19276. };
  19277. Material.prototype.getAlphaTestTexture = function () {
  19278. return null;
  19279. };
  19280. Material.prototype.trackCreation = function (onCompiled, onError) {
  19281. };
  19282. Material.prototype.markDirty = function () {
  19283. this._wasPreviouslyReady = false;
  19284. };
  19285. Material.prototype._preBind = function () {
  19286. var engine = this._scene.getEngine();
  19287. engine.enableEffect(this._effect);
  19288. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19289. };
  19290. Material.prototype.bind = function (world, mesh) {
  19291. this._scene._cachedMaterial = this;
  19292. if (this.onBind) {
  19293. this.onBind(this, mesh);
  19294. }
  19295. if (this.disableDepthWrite) {
  19296. var engine = this._scene.getEngine();
  19297. this._cachedDepthWriteState = engine.getDepthWrite();
  19298. engine.setDepthWrite(false);
  19299. }
  19300. };
  19301. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19302. };
  19303. Material.prototype.unbind = function () {
  19304. if (this.disableDepthWrite) {
  19305. var engine = this._scene.getEngine();
  19306. engine.setDepthWrite(this._cachedDepthWriteState);
  19307. }
  19308. };
  19309. Material.prototype.clone = function (name) {
  19310. return null;
  19311. };
  19312. Material.prototype.getBindedMeshes = function () {
  19313. var result = new Array();
  19314. for (var index = 0; index < this._scene.meshes.length; index++) {
  19315. var mesh = this._scene.meshes[index];
  19316. if (mesh.material === this) {
  19317. result.push(mesh);
  19318. }
  19319. }
  19320. return result;
  19321. };
  19322. Material.prototype.dispose = function (forceDisposeEffect) {
  19323. // Animations
  19324. this.getScene().stopAnimation(this);
  19325. // Remove from scene
  19326. var index = this._scene.materials.indexOf(this);
  19327. if (index >= 0) {
  19328. this._scene.materials.splice(index, 1);
  19329. }
  19330. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19331. if (forceDisposeEffect && this._effect) {
  19332. this._scene.getEngine()._releaseEffect(this._effect);
  19333. this._effect = null;
  19334. }
  19335. // Remove from meshes
  19336. for (index = 0; index < this._scene.meshes.length; index++) {
  19337. var mesh = this._scene.meshes[index];
  19338. if (mesh.material === this) {
  19339. mesh.material = null;
  19340. }
  19341. }
  19342. // Callback
  19343. if (this.onDispose) {
  19344. this.onDispose();
  19345. }
  19346. };
  19347. Material.prototype.copyTo = function (other) {
  19348. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19349. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19350. other.alpha = this.alpha;
  19351. other.fillMode = this.fillMode;
  19352. other.backFaceCulling = this.backFaceCulling;
  19353. other.fogEnabled = this.fogEnabled;
  19354. other.wireframe = this.wireframe;
  19355. other.zOffset = this.zOffset;
  19356. other.alphaMode = this.alphaMode;
  19357. other.sideOrientation = this.sideOrientation;
  19358. other.disableDepthWrite = this.disableDepthWrite;
  19359. other.pointSize = this.pointSize;
  19360. other.pointsCloud = this.pointsCloud;
  19361. };
  19362. Material.prototype.serialize = function () {
  19363. var serializationObject = {};
  19364. serializationObject.name = this.name;
  19365. serializationObject.alpha = this.alpha;
  19366. serializationObject.id = this.id;
  19367. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19368. serializationObject.backFaceCulling = this.backFaceCulling;
  19369. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19370. serializationObject.disableDepthWrite = this.disableDepthWrite;
  19371. return serializationObject;
  19372. };
  19373. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19374. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19375. multiMaterial.id = parsedMultiMaterial.id;
  19376. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19377. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19378. var subMatId = parsedMultiMaterial.materials[matIndex];
  19379. if (subMatId) {
  19380. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19381. }
  19382. else {
  19383. multiMaterial.subMaterials.push(null);
  19384. }
  19385. }
  19386. return multiMaterial;
  19387. };
  19388. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19389. if (!parsedMaterial.customType) {
  19390. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19391. }
  19392. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19393. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19394. ;
  19395. };
  19396. Material._TriangleFillMode = 0;
  19397. Material._WireFrameFillMode = 1;
  19398. Material._PointFillMode = 2;
  19399. Material._ClockWiseSideOrientation = 0;
  19400. Material._CounterClockWiseSideOrientation = 1;
  19401. return Material;
  19402. })();
  19403. BABYLON.Material = Material;
  19404. })(BABYLON || (BABYLON = {}));
  19405. var BABYLON;
  19406. (function (BABYLON) {
  19407. var maxSimultaneousLights = 4;
  19408. var FresnelParameters = (function () {
  19409. function FresnelParameters() {
  19410. this.isEnabled = true;
  19411. this.leftColor = BABYLON.Color3.White();
  19412. this.rightColor = BABYLON.Color3.Black();
  19413. this.bias = 0;
  19414. this.power = 1;
  19415. }
  19416. FresnelParameters.prototype.clone = function () {
  19417. var newFresnelParameters = new FresnelParameters();
  19418. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19419. return new FresnelParameters;
  19420. };
  19421. FresnelParameters.prototype.serialize = function () {
  19422. var serializationObject = {};
  19423. serializationObject.isEnabled = this.isEnabled;
  19424. serializationObject.leftColor = this.leftColor;
  19425. serializationObject.rightColor = this.rightColor;
  19426. serializationObject.bias = this.bias;
  19427. serializationObject.power = this.power;
  19428. return serializationObject;
  19429. };
  19430. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19431. var fresnelParameters = new FresnelParameters();
  19432. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19433. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19434. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19435. fresnelParameters.bias = parsedFresnelParameters.bias;
  19436. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19437. return fresnelParameters;
  19438. };
  19439. return FresnelParameters;
  19440. })();
  19441. BABYLON.FresnelParameters = FresnelParameters;
  19442. var StandardMaterialDefines = (function (_super) {
  19443. __extends(StandardMaterialDefines, _super);
  19444. function StandardMaterialDefines() {
  19445. _super.call(this);
  19446. this.DIFFUSE = false;
  19447. this.AMBIENT = false;
  19448. this.OPACITY = false;
  19449. this.OPACITYRGB = false;
  19450. this.REFLECTION = false;
  19451. this.EMISSIVE = false;
  19452. this.SPECULAR = false;
  19453. this.BUMP = false;
  19454. this.SPECULAROVERALPHA = false;
  19455. this.CLIPPLANE = false;
  19456. this.ALPHATEST = false;
  19457. this.ALPHAFROMDIFFUSE = false;
  19458. this.POINTSIZE = false;
  19459. this.FOG = false;
  19460. this.LIGHT0 = false;
  19461. this.LIGHT1 = false;
  19462. this.LIGHT2 = false;
  19463. this.LIGHT3 = false;
  19464. this.SPOTLIGHT0 = false;
  19465. this.SPOTLIGHT1 = false;
  19466. this.SPOTLIGHT2 = false;
  19467. this.SPOTLIGHT3 = false;
  19468. this.HEMILIGHT0 = false;
  19469. this.HEMILIGHT1 = false;
  19470. this.HEMILIGHT2 = false;
  19471. this.HEMILIGHT3 = false;
  19472. this.POINTLIGHT0 = false;
  19473. this.POINTLIGHT1 = false;
  19474. this.POINTLIGHT2 = false;
  19475. this.POINTLIGHT3 = false;
  19476. this.DIRLIGHT0 = false;
  19477. this.DIRLIGHT1 = false;
  19478. this.DIRLIGHT2 = false;
  19479. this.DIRLIGHT3 = false;
  19480. this.SPECULARTERM = false;
  19481. this.SHADOW0 = false;
  19482. this.SHADOW1 = false;
  19483. this.SHADOW2 = false;
  19484. this.SHADOW3 = false;
  19485. this.SHADOWS = false;
  19486. this.SHADOWVSM0 = false;
  19487. this.SHADOWVSM1 = false;
  19488. this.SHADOWVSM2 = false;
  19489. this.SHADOWVSM3 = false;
  19490. this.SHADOWPCF0 = false;
  19491. this.SHADOWPCF1 = false;
  19492. this.SHADOWPCF2 = false;
  19493. this.SHADOWPCF3 = false;
  19494. this.DIFFUSEFRESNEL = false;
  19495. this.OPACITYFRESNEL = false;
  19496. this.REFLECTIONFRESNEL = false;
  19497. this.REFRACTIONFRESNEL = false;
  19498. this.EMISSIVEFRESNEL = false;
  19499. this.FRESNEL = false;
  19500. this.NORMAL = false;
  19501. this.UV1 = false;
  19502. this.UV2 = false;
  19503. this.VERTEXCOLOR = false;
  19504. this.VERTEXALPHA = false;
  19505. this.NUM_BONE_INFLUENCERS = 0;
  19506. this.BonesPerMesh = 0;
  19507. this.INSTANCES = false;
  19508. this.GLOSSINESS = false;
  19509. this.ROUGHNESS = false;
  19510. this.EMISSIVEASILLUMINATION = false;
  19511. this.LINKEMISSIVEWITHDIFFUSE = false;
  19512. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19513. this.LIGHTMAP = false;
  19514. this.USELIGHTMAPASSHADOWMAP = false;
  19515. this.REFLECTIONMAP_3D = false;
  19516. this.REFLECTIONMAP_SPHERICAL = false;
  19517. this.REFLECTIONMAP_PLANAR = false;
  19518. this.REFLECTIONMAP_CUBIC = false;
  19519. this.REFLECTIONMAP_PROJECTION = false;
  19520. this.REFLECTIONMAP_SKYBOX = false;
  19521. this.REFLECTIONMAP_EXPLICIT = false;
  19522. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19523. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19524. this.INVERTCUBICMAP = false;
  19525. this.LOGARITHMICDEPTH = false;
  19526. this.REFRACTION = false;
  19527. this.REFRACTIONMAP_3D = false;
  19528. this._keys = Object.keys(this);
  19529. }
  19530. return StandardMaterialDefines;
  19531. })(BABYLON.MaterialDefines);
  19532. var StandardMaterial = (function (_super) {
  19533. __extends(StandardMaterial, _super);
  19534. function StandardMaterial(name, scene) {
  19535. var _this = this;
  19536. _super.call(this, name, scene);
  19537. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19538. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19539. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19540. this.specularPower = 64;
  19541. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19542. this.useAlphaFromDiffuseTexture = false;
  19543. this.useEmissiveAsIllumination = false;
  19544. this.linkEmissiveWithDiffuse = false;
  19545. this.useReflectionFresnelFromSpecular = false;
  19546. this.useSpecularOverAlpha = false;
  19547. this.disableLighting = false;
  19548. this.roughness = 0;
  19549. this.indexOfRefraction = 0.98;
  19550. this.invertRefractionY = true;
  19551. this.useLightmapAsShadowmap = false;
  19552. this.useGlossinessFromSpecularMapAlpha = false;
  19553. this._renderTargets = new BABYLON.SmartArray(16);
  19554. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19555. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19556. this._defines = new StandardMaterialDefines();
  19557. this._cachedDefines = new StandardMaterialDefines();
  19558. this._cachedDefines.BonesPerMesh = -1;
  19559. this.getRenderTargetTextures = function () {
  19560. _this._renderTargets.reset();
  19561. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19562. _this._renderTargets.push(_this.reflectionTexture);
  19563. }
  19564. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  19565. _this._renderTargets.push(_this.refractionTexture);
  19566. }
  19567. return _this._renderTargets;
  19568. };
  19569. }
  19570. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19571. get: function () {
  19572. return this._useLogarithmicDepth;
  19573. },
  19574. set: function (value) {
  19575. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. StandardMaterial.prototype.needAlphaBlending = function () {
  19581. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19582. };
  19583. StandardMaterial.prototype.needAlphaTesting = function () {
  19584. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19585. };
  19586. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19587. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19588. };
  19589. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19590. return this.diffuseTexture;
  19591. };
  19592. // Methods
  19593. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19594. if (!mesh) {
  19595. return true;
  19596. }
  19597. if (this._defines.INSTANCES !== useInstances) {
  19598. return false;
  19599. }
  19600. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19601. return true;
  19602. }
  19603. return false;
  19604. };
  19605. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19606. var lightIndex = 0;
  19607. var needNormals = false;
  19608. for (var index = 0; index < scene.lights.length; index++) {
  19609. var light = scene.lights[index];
  19610. if (!light.isEnabled()) {
  19611. continue;
  19612. }
  19613. // Excluded check
  19614. if (light._excludedMeshesIds.length > 0) {
  19615. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19616. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19617. if (excludedMesh) {
  19618. light.excludedMeshes.push(excludedMesh);
  19619. }
  19620. }
  19621. light._excludedMeshesIds = [];
  19622. }
  19623. // Included check
  19624. if (light._includedOnlyMeshesIds.length > 0) {
  19625. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19626. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19627. if (includedOnlyMesh) {
  19628. light.includedOnlyMeshes.push(includedOnlyMesh);
  19629. }
  19630. }
  19631. light._includedOnlyMeshesIds = [];
  19632. }
  19633. if (!light.canAffectMesh(mesh)) {
  19634. continue;
  19635. }
  19636. needNormals = true;
  19637. defines["LIGHT" + lightIndex] = true;
  19638. var type;
  19639. if (light instanceof BABYLON.SpotLight) {
  19640. type = "SPOTLIGHT" + lightIndex;
  19641. }
  19642. else if (light instanceof BABYLON.HemisphericLight) {
  19643. type = "HEMILIGHT" + lightIndex;
  19644. }
  19645. else if (light instanceof BABYLON.PointLight) {
  19646. type = "POINTLIGHT" + lightIndex;
  19647. }
  19648. else {
  19649. type = "DIRLIGHT" + lightIndex;
  19650. }
  19651. defines[type] = true;
  19652. // Specular
  19653. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19654. defines["SPECULARTERM"] = true;
  19655. }
  19656. // Shadows
  19657. if (scene.shadowsEnabled) {
  19658. var shadowGenerator = light.getShadowGenerator();
  19659. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19660. defines["SHADOW" + lightIndex] = true;
  19661. defines["SHADOWS"] = true;
  19662. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19663. defines["SHADOWVSM" + lightIndex] = true;
  19664. }
  19665. if (shadowGenerator.usePoissonSampling) {
  19666. defines["SHADOWPCF" + lightIndex] = true;
  19667. }
  19668. }
  19669. }
  19670. lightIndex++;
  19671. if (lightIndex === maxSimultaneousLights)
  19672. break;
  19673. }
  19674. return needNormals;
  19675. };
  19676. StandardMaterial.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19677. var shadowGenerator = light.getShadowGenerator();
  19678. if (mesh.receiveShadows && shadowGenerator) {
  19679. if (!light.needCube()) {
  19680. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19681. }
  19682. else {
  19683. if (!depthValuesAlreadySet) {
  19684. depthValuesAlreadySet = true;
  19685. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19686. }
  19687. }
  19688. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19689. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19690. }
  19691. return depthValuesAlreadySet;
  19692. };
  19693. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19694. var lightIndex = 0;
  19695. var depthValuesAlreadySet = false;
  19696. for (var index = 0; index < scene.lights.length; index++) {
  19697. var light = scene.lights[index];
  19698. if (!light.isEnabled()) {
  19699. continue;
  19700. }
  19701. if (!light.canAffectMesh(mesh)) {
  19702. continue;
  19703. }
  19704. if (light instanceof BABYLON.PointLight) {
  19705. // Point Light
  19706. light.transferToEffect(effect, "vLightData" + lightIndex);
  19707. }
  19708. else if (light instanceof BABYLON.DirectionalLight) {
  19709. // Directional Light
  19710. light.transferToEffect(effect, "vLightData" + lightIndex);
  19711. }
  19712. else if (light instanceof BABYLON.SpotLight) {
  19713. // Spot Light
  19714. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19715. }
  19716. else if (light instanceof BABYLON.HemisphericLight) {
  19717. // Hemispheric Light
  19718. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19719. }
  19720. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19721. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19722. if (defines["SPECULARTERM"]) {
  19723. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19724. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19725. }
  19726. // Shadows
  19727. if (scene.shadowsEnabled) {
  19728. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19729. }
  19730. lightIndex++;
  19731. if (lightIndex === maxSimultaneousLights)
  19732. break;
  19733. }
  19734. };
  19735. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19736. if (this.isFrozen) {
  19737. if (this._wasPreviouslyReady) {
  19738. return true;
  19739. }
  19740. }
  19741. var scene = this.getScene();
  19742. if (!this.checkReadyOnEveryCall) {
  19743. if (this._renderId === scene.getRenderId()) {
  19744. if (this._checkCache(scene, mesh, useInstances)) {
  19745. return true;
  19746. }
  19747. }
  19748. }
  19749. var engine = scene.getEngine();
  19750. var needNormals = false;
  19751. var needUVs = false;
  19752. this._defines.reset();
  19753. // Textures
  19754. if (scene.texturesEnabled) {
  19755. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19756. if (!this.diffuseTexture.isReady()) {
  19757. return false;
  19758. }
  19759. else {
  19760. needUVs = true;
  19761. this._defines.DIFFUSE = true;
  19762. }
  19763. }
  19764. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19765. if (!this.ambientTexture.isReady()) {
  19766. return false;
  19767. }
  19768. else {
  19769. needUVs = true;
  19770. this._defines.AMBIENT = true;
  19771. }
  19772. }
  19773. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19774. if (!this.opacityTexture.isReady()) {
  19775. return false;
  19776. }
  19777. else {
  19778. needUVs = true;
  19779. this._defines.OPACITY = true;
  19780. if (this.opacityTexture.getAlphaFromRGB) {
  19781. this._defines.OPACITYRGB = true;
  19782. }
  19783. }
  19784. }
  19785. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19786. if (!this.reflectionTexture.isReady()) {
  19787. return false;
  19788. }
  19789. else {
  19790. needNormals = true;
  19791. this._defines.REFLECTION = true;
  19792. if (this.roughness > 0) {
  19793. this._defines.ROUGHNESS = true;
  19794. }
  19795. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19796. this._defines.INVERTCUBICMAP = true;
  19797. }
  19798. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19799. switch (this.reflectionTexture.coordinatesMode) {
  19800. case BABYLON.Texture.CUBIC_MODE:
  19801. case BABYLON.Texture.INVCUBIC_MODE:
  19802. this._defines.REFLECTIONMAP_CUBIC = true;
  19803. break;
  19804. case BABYLON.Texture.EXPLICIT_MODE:
  19805. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19806. break;
  19807. case BABYLON.Texture.PLANAR_MODE:
  19808. this._defines.REFLECTIONMAP_PLANAR = true;
  19809. break;
  19810. case BABYLON.Texture.PROJECTION_MODE:
  19811. this._defines.REFLECTIONMAP_PROJECTION = true;
  19812. break;
  19813. case BABYLON.Texture.SKYBOX_MODE:
  19814. this._defines.REFLECTIONMAP_SKYBOX = true;
  19815. break;
  19816. case BABYLON.Texture.SPHERICAL_MODE:
  19817. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19818. break;
  19819. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19820. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19821. break;
  19822. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19823. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19824. break;
  19825. }
  19826. }
  19827. }
  19828. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19829. if (!this.emissiveTexture.isReady()) {
  19830. return false;
  19831. }
  19832. else {
  19833. needUVs = true;
  19834. this._defines.EMISSIVE = true;
  19835. }
  19836. }
  19837. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  19838. if (!this.lightmapTexture.isReady()) {
  19839. return false;
  19840. }
  19841. else {
  19842. needUVs = true;
  19843. this._defines.LIGHTMAP = true;
  19844. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19845. }
  19846. }
  19847. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19848. if (!this.specularTexture.isReady()) {
  19849. return false;
  19850. }
  19851. else {
  19852. needUVs = true;
  19853. this._defines.SPECULAR = true;
  19854. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19855. }
  19856. }
  19857. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19858. if (!this.bumpTexture.isReady()) {
  19859. return false;
  19860. }
  19861. else {
  19862. needUVs = true;
  19863. this._defines.BUMP = true;
  19864. }
  19865. }
  19866. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  19867. if (!this.refractionTexture.isReady()) {
  19868. return false;
  19869. }
  19870. else {
  19871. needUVs = true;
  19872. this._defines.REFRACTION = true;
  19873. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  19874. }
  19875. }
  19876. }
  19877. // Effect
  19878. if (scene.clipPlane) {
  19879. this._defines.CLIPPLANE = true;
  19880. }
  19881. if (engine.getAlphaTesting()) {
  19882. this._defines.ALPHATEST = true;
  19883. }
  19884. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19885. this._defines.ALPHAFROMDIFFUSE = true;
  19886. }
  19887. if (this.useEmissiveAsIllumination) {
  19888. this._defines.EMISSIVEASILLUMINATION = true;
  19889. }
  19890. if (this.linkEmissiveWithDiffuse) {
  19891. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19892. }
  19893. if (this.useReflectionFresnelFromSpecular) {
  19894. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19895. }
  19896. if (this.useLogarithmicDepth) {
  19897. this._defines.LOGARITHMICDEPTH = true;
  19898. }
  19899. // Point size
  19900. if (this.pointsCloud || scene.forcePointsCloud) {
  19901. this._defines.POINTSIZE = true;
  19902. }
  19903. // Fog
  19904. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19905. this._defines.FOG = true;
  19906. }
  19907. if (scene.lightsEnabled && !this.disableLighting) {
  19908. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19909. }
  19910. if (StandardMaterial.FresnelEnabled) {
  19911. // Fresnel
  19912. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19913. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19914. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19915. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  19916. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19917. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19918. this._defines.DIFFUSEFRESNEL = true;
  19919. }
  19920. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19921. this._defines.OPACITYFRESNEL = true;
  19922. }
  19923. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19924. this._defines.REFLECTIONFRESNEL = true;
  19925. }
  19926. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  19927. this._defines.REFRACTIONFRESNEL = true;
  19928. }
  19929. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19930. this._defines.EMISSIVEFRESNEL = true;
  19931. }
  19932. needNormals = true;
  19933. this._defines.FRESNEL = true;
  19934. }
  19935. }
  19936. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19937. this._defines.SPECULAROVERALPHA = true;
  19938. }
  19939. // Attribs
  19940. if (mesh) {
  19941. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19942. this._defines.NORMAL = true;
  19943. }
  19944. if (needUVs) {
  19945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19946. this._defines.UV1 = true;
  19947. }
  19948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19949. this._defines.UV2 = true;
  19950. }
  19951. }
  19952. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19953. this._defines.VERTEXCOLOR = true;
  19954. if (mesh.hasVertexAlpha) {
  19955. this._defines.VERTEXALPHA = true;
  19956. }
  19957. }
  19958. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19959. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19960. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19961. }
  19962. // Instances
  19963. if (useInstances) {
  19964. this._defines.INSTANCES = true;
  19965. }
  19966. }
  19967. // Get correct effect
  19968. if (!this._defines.isEqual(this._cachedDefines)) {
  19969. this._defines.cloneTo(this._cachedDefines);
  19970. scene.resetCachedMaterial();
  19971. // Fallbacks
  19972. var fallbacks = new BABYLON.EffectFallbacks();
  19973. if (this._defines.REFLECTION) {
  19974. fallbacks.addFallback(0, "REFLECTION");
  19975. }
  19976. if (this._defines.SPECULAR) {
  19977. fallbacks.addFallback(0, "SPECULAR");
  19978. }
  19979. if (this._defines.BUMP) {
  19980. fallbacks.addFallback(0, "BUMP");
  19981. }
  19982. if (this._defines.SPECULAROVERALPHA) {
  19983. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19984. }
  19985. if (this._defines.FOG) {
  19986. fallbacks.addFallback(1, "FOG");
  19987. }
  19988. if (this._defines.POINTSIZE) {
  19989. fallbacks.addFallback(0, "POINTSIZE");
  19990. }
  19991. if (this._defines.LOGARITHMICDEPTH) {
  19992. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19993. }
  19994. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19995. if (!this._defines["LIGHT" + lightIndex]) {
  19996. continue;
  19997. }
  19998. if (lightIndex > 0) {
  19999. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  20000. }
  20001. if (this._defines["SHADOW" + lightIndex]) {
  20002. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  20003. }
  20004. if (this._defines["SHADOWPCF" + lightIndex]) {
  20005. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  20006. }
  20007. if (this._defines["SHADOWVSM" + lightIndex]) {
  20008. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  20009. }
  20010. }
  20011. if (this._defines.SPECULARTERM) {
  20012. fallbacks.addFallback(0, "SPECULARTERM");
  20013. }
  20014. if (this._defines.DIFFUSEFRESNEL) {
  20015. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20016. }
  20017. if (this._defines.OPACITYFRESNEL) {
  20018. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20019. }
  20020. if (this._defines.REFLECTIONFRESNEL) {
  20021. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20022. }
  20023. if (this._defines.EMISSIVEFRESNEL) {
  20024. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20025. }
  20026. if (this._defines.FRESNEL) {
  20027. fallbacks.addFallback(4, "FRESNEL");
  20028. }
  20029. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  20030. fallbacks.addCPUSkinningFallback(0, mesh);
  20031. }
  20032. //Attributes
  20033. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20034. if (this._defines.NORMAL) {
  20035. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20036. }
  20037. if (this._defines.UV1) {
  20038. attribs.push(BABYLON.VertexBuffer.UVKind);
  20039. }
  20040. if (this._defines.UV2) {
  20041. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20042. }
  20043. if (this._defines.VERTEXCOLOR) {
  20044. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20045. }
  20046. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  20047. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20048. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20049. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  20050. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  20051. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  20052. }
  20053. }
  20054. if (this._defines.INSTANCES) {
  20055. attribs.push("world0");
  20056. attribs.push("world1");
  20057. attribs.push("world2");
  20058. attribs.push("world3");
  20059. }
  20060. // Legacy browser patch
  20061. var shaderName = "default";
  20062. if (!scene.getEngine().getCaps().standardDerivatives) {
  20063. shaderName = "legacydefault";
  20064. }
  20065. var join = this._defines.toString();
  20066. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20067. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20068. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20069. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20070. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20071. "vFogInfos", "vFogColor", "pointSize",
  20072. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20073. "mBones",
  20074. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20075. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20076. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20077. "logarithmicDepthConstant"
  20078. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20079. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20080. ], join, fallbacks, this.onCompiled, this.onError);
  20081. }
  20082. if (!this._effect.isReady()) {
  20083. return false;
  20084. }
  20085. this._renderId = scene.getRenderId();
  20086. this._wasPreviouslyReady = true;
  20087. if (mesh) {
  20088. if (!mesh._materialDefines) {
  20089. mesh._materialDefines = new StandardMaterialDefines();
  20090. }
  20091. this._defines.cloneTo(mesh._materialDefines);
  20092. }
  20093. return true;
  20094. };
  20095. StandardMaterial.prototype.unbind = function () {
  20096. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20097. this._effect.setTexture("reflection2DSampler", null);
  20098. }
  20099. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20100. this._effect.setTexture("refraction2DSampler", null);
  20101. }
  20102. _super.prototype.unbind.call(this);
  20103. };
  20104. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20105. this._effect.setMatrix("world", world);
  20106. };
  20107. StandardMaterial.prototype.bind = function (world, mesh) {
  20108. var scene = this.getScene();
  20109. // Matrices
  20110. this.bindOnlyWorldMatrix(world);
  20111. // Bones
  20112. StandardMaterial.ApplyBonesParameters(mesh, this._effect);
  20113. if (scene.getCachedMaterial() !== this) {
  20114. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20115. if (StandardMaterial.FresnelEnabled) {
  20116. // Fresnel
  20117. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20118. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20119. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20120. }
  20121. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20122. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20123. }
  20124. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20125. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20126. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20127. }
  20128. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20129. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20130. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20131. }
  20132. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20133. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20134. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20135. }
  20136. }
  20137. // Textures
  20138. if (scene.texturesEnabled) {
  20139. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20140. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20141. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20142. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20143. }
  20144. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20145. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20146. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20147. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20148. }
  20149. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20150. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20151. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20152. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20153. }
  20154. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20155. if (this.reflectionTexture.isCube) {
  20156. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20157. }
  20158. else {
  20159. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20160. }
  20161. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20162. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20163. }
  20164. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20165. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20166. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20167. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20168. }
  20169. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20170. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20171. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20172. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20173. }
  20174. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20175. this._effect.setTexture("specularSampler", this.specularTexture);
  20176. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20177. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20178. }
  20179. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20180. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20181. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20182. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20183. }
  20184. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20185. var depth = 1.0;
  20186. if (this.refractionTexture.isCube) {
  20187. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20188. }
  20189. else {
  20190. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20191. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20192. if (this.refractionTexture.depth) {
  20193. depth = this.refractionTexture.depth;
  20194. }
  20195. }
  20196. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20197. }
  20198. }
  20199. // Clip plane
  20200. if (scene.clipPlane) {
  20201. var clipPlane = scene.clipPlane;
  20202. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20203. }
  20204. // Point size
  20205. if (this.pointsCloud) {
  20206. this._effect.setFloat("pointSize", this.pointSize);
  20207. }
  20208. // Colors
  20209. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20210. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20211. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20212. if (this._defines.SPECULARTERM) {
  20213. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20214. }
  20215. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20216. }
  20217. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20218. // Diffuse
  20219. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20220. // Lights
  20221. if (scene.lightsEnabled && !this.disableLighting) {
  20222. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  20223. }
  20224. // View
  20225. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20226. this._effect.setMatrix("view", scene.getViewMatrix());
  20227. }
  20228. // Fog
  20229. StandardMaterial.ApplyFogParameters(scene, mesh, this._effect);
  20230. // Log. depth
  20231. if (this._defines.LOGARITHMICDEPTH) {
  20232. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20233. }
  20234. }
  20235. _super.prototype.bind.call(this, world, mesh);
  20236. };
  20237. StandardMaterial.ApplyFogParameters = function (scene, mesh, effect) {
  20238. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20239. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20240. effect.setColor3("vFogColor", scene.fogColor);
  20241. }
  20242. };
  20243. StandardMaterial.ApplyBonesParameters = function (mesh, effect) {
  20244. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20245. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20246. }
  20247. };
  20248. StandardMaterial.prototype.getAnimatables = function () {
  20249. var results = [];
  20250. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20251. results.push(this.diffuseTexture);
  20252. }
  20253. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20254. results.push(this.ambientTexture);
  20255. }
  20256. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20257. results.push(this.opacityTexture);
  20258. }
  20259. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20260. results.push(this.reflectionTexture);
  20261. }
  20262. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20263. results.push(this.emissiveTexture);
  20264. }
  20265. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20266. results.push(this.specularTexture);
  20267. }
  20268. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20269. results.push(this.bumpTexture);
  20270. }
  20271. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20272. results.push(this.lightmapTexture);
  20273. }
  20274. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20275. results.push(this.refractionTexture);
  20276. }
  20277. return results;
  20278. };
  20279. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20280. if (this.diffuseTexture) {
  20281. this.diffuseTexture.dispose();
  20282. }
  20283. if (this.ambientTexture) {
  20284. this.ambientTexture.dispose();
  20285. }
  20286. if (this.opacityTexture) {
  20287. this.opacityTexture.dispose();
  20288. }
  20289. if (this.reflectionTexture) {
  20290. this.reflectionTexture.dispose();
  20291. }
  20292. if (this.emissiveTexture) {
  20293. this.emissiveTexture.dispose();
  20294. }
  20295. if (this.specularTexture) {
  20296. this.specularTexture.dispose();
  20297. }
  20298. if (this.bumpTexture) {
  20299. this.bumpTexture.dispose();
  20300. }
  20301. if (this.lightmapTexture) {
  20302. this.lightmapTexture.dispose();
  20303. }
  20304. if (this.refractionTexture) {
  20305. this.refractionTexture.dispose();
  20306. }
  20307. _super.prototype.dispose.call(this, forceDisposeEffect);
  20308. };
  20309. StandardMaterial.prototype.clone = function (name) {
  20310. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  20311. // Base material
  20312. this.copyTo(newStandardMaterial);
  20313. // Standard material
  20314. if (this.diffuseTexture && this.diffuseTexture.clone) {
  20315. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  20316. }
  20317. if (this.ambientTexture && this.ambientTexture.clone) {
  20318. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  20319. }
  20320. if (this.opacityTexture && this.opacityTexture.clone) {
  20321. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  20322. }
  20323. if (this.reflectionTexture && this.reflectionTexture.clone) {
  20324. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  20325. }
  20326. if (this.emissiveTexture && this.emissiveTexture.clone) {
  20327. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  20328. }
  20329. if (this.specularTexture && this.specularTexture.clone) {
  20330. newStandardMaterial.specularTexture = this.specularTexture.clone();
  20331. }
  20332. if (this.bumpTexture && this.bumpTexture.clone) {
  20333. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  20334. }
  20335. if (this.lightmapTexture && this.lightmapTexture.clone) {
  20336. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  20337. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20338. }
  20339. if (this.refractionTexture && this.refractionTexture.clone) {
  20340. newStandardMaterial.refractionTexture = this.refractionTexture.clone();
  20341. }
  20342. newStandardMaterial.ambientColor = this.ambientColor.clone();
  20343. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  20344. newStandardMaterial.specularColor = this.specularColor.clone();
  20345. newStandardMaterial.specularPower = this.specularPower;
  20346. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  20347. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  20348. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20349. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  20350. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20351. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  20352. newStandardMaterial.roughness = this.roughness;
  20353. newStandardMaterial.indexOfRefraction = this.indexOfRefraction;
  20354. newStandardMaterial.invertRefractionY = this.invertRefractionY;
  20355. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  20356. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  20357. }
  20358. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  20359. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  20360. }
  20361. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  20362. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  20363. }
  20364. if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
  20365. newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
  20366. }
  20367. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  20368. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  20369. }
  20370. return newStandardMaterial;
  20371. };
  20372. StandardMaterial.prototype.serialize = function () {
  20373. var serializationObject = _super.prototype.serialize.call(this);
  20374. serializationObject.ambient = this.ambientColor.asArray();
  20375. serializationObject.diffuse = this.diffuseColor.asArray();
  20376. serializationObject.specular = this.specularColor.asArray();
  20377. serializationObject.specularPower = this.specularPower;
  20378. serializationObject.emissive = this.emissiveColor.asArray();
  20379. serializationObject.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20380. serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20381. serializationObject.indexOfRefraction = this.indexOfRefraction;
  20382. serializationObject.invertRefractionY = this.invertRefractionY;
  20383. if (this.diffuseTexture) {
  20384. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  20385. }
  20386. if (this.diffuseFresnelParameters) {
  20387. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  20388. }
  20389. if (this.ambientTexture) {
  20390. serializationObject.ambientTexture = this.ambientTexture.serialize();
  20391. }
  20392. if (this.opacityTexture) {
  20393. serializationObject.opacityTexture = this.opacityTexture.serialize();
  20394. }
  20395. if (this.opacityFresnelParameters) {
  20396. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  20397. }
  20398. if (this.reflectionTexture) {
  20399. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  20400. }
  20401. if (this.reflectionFresnelParameters) {
  20402. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  20403. }
  20404. if (this.refractionFresnelParameters) {
  20405. serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
  20406. }
  20407. if (this.emissiveTexture) {
  20408. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  20409. }
  20410. if (this.lightmapTexture) {
  20411. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  20412. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20413. }
  20414. if (this.emissiveFresnelParameters) {
  20415. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  20416. }
  20417. if (this.specularTexture) {
  20418. serializationObject.specularTexture = this.specularTexture.serialize();
  20419. }
  20420. if (this.bumpTexture) {
  20421. serializationObject.bumpTexture = this.bumpTexture.serialize();
  20422. }
  20423. if (this.refractionTexture) {
  20424. serializationObject.refractionTexture = this.refractionTexture.serialize();
  20425. }
  20426. return serializationObject;
  20427. };
  20428. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20429. var material = new StandardMaterial(source.name, scene);
  20430. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  20431. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  20432. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  20433. material.specularPower = source.specularPower;
  20434. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  20435. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  20436. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  20437. material.indexOfRefraction = source.indexOfRefraction;
  20438. material.invertRefractionY = source.invertRefractionY;
  20439. material.alpha = source.alpha;
  20440. material.id = source.id;
  20441. if (source.disableDepthWrite) {
  20442. material.disableDepthWrite = source.disableDepthWrite;
  20443. }
  20444. BABYLON.Tags.AddTagsTo(material, source.tags);
  20445. material.backFaceCulling = source.backFaceCulling;
  20446. material.wireframe = source.wireframe;
  20447. if (source.diffuseTexture) {
  20448. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  20449. }
  20450. if (source.diffuseFresnelParameters) {
  20451. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  20452. }
  20453. if (source.ambientTexture) {
  20454. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  20455. }
  20456. if (source.opacityTexture) {
  20457. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  20458. }
  20459. if (source.opacityFresnelParameters) {
  20460. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  20461. }
  20462. if (source.reflectionTexture) {
  20463. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  20464. }
  20465. if (source.reflectionFresnelParameters) {
  20466. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  20467. }
  20468. if (source.refractionFresnelParameters) {
  20469. material.refractionFresnelParameters = FresnelParameters.Parse(source.refractionFresnelParameters);
  20470. }
  20471. if (source.emissiveTexture) {
  20472. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20473. }
  20474. if (source.lightmapTexture) {
  20475. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20476. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20477. }
  20478. if (source.emissiveFresnelParameters) {
  20479. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  20480. }
  20481. if (source.specularTexture) {
  20482. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20483. }
  20484. if (source.bumpTexture) {
  20485. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20486. }
  20487. if (source.refractionTexture) {
  20488. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  20489. }
  20490. if (source.checkReadyOnlyOnce) {
  20491. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20492. }
  20493. return material;
  20494. };
  20495. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  20496. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  20497. // Statics
  20498. // Flags used to enable or disable a type of texture for all Standard Materials
  20499. StandardMaterial.DiffuseTextureEnabled = true;
  20500. StandardMaterial.AmbientTextureEnabled = true;
  20501. StandardMaterial.OpacityTextureEnabled = true;
  20502. StandardMaterial.ReflectionTextureEnabled = true;
  20503. StandardMaterial.EmissiveTextureEnabled = true;
  20504. StandardMaterial.SpecularTextureEnabled = true;
  20505. StandardMaterial.BumpTextureEnabled = true;
  20506. StandardMaterial.FresnelEnabled = true;
  20507. StandardMaterial.LightmapTextureEnabled = true;
  20508. StandardMaterial.RefractionTextureEnabled = true;
  20509. return StandardMaterial;
  20510. })(BABYLON.Material);
  20511. BABYLON.StandardMaterial = StandardMaterial;
  20512. })(BABYLON || (BABYLON = {}));
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. var MultiMaterial = (function (_super) {
  20516. __extends(MultiMaterial, _super);
  20517. function MultiMaterial(name, scene) {
  20518. _super.call(this, name, scene, true);
  20519. this.subMaterials = new Array();
  20520. scene.multiMaterials.push(this);
  20521. }
  20522. // Properties
  20523. MultiMaterial.prototype.getSubMaterial = function (index) {
  20524. if (index < 0 || index >= this.subMaterials.length) {
  20525. return this.getScene().defaultMaterial;
  20526. }
  20527. return this.subMaterials[index];
  20528. };
  20529. // Methods
  20530. MultiMaterial.prototype.isReady = function (mesh) {
  20531. for (var index = 0; index < this.subMaterials.length; index++) {
  20532. var subMaterial = this.subMaterials[index];
  20533. if (subMaterial) {
  20534. if (!this.subMaterials[index].isReady(mesh)) {
  20535. return false;
  20536. }
  20537. }
  20538. }
  20539. return true;
  20540. };
  20541. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20542. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20543. for (var index = 0; index < this.subMaterials.length; index++) {
  20544. var subMaterial = null;
  20545. if (cloneChildren) {
  20546. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20547. }
  20548. else {
  20549. subMaterial = this.subMaterials[index];
  20550. }
  20551. newMultiMaterial.subMaterials.push(subMaterial);
  20552. }
  20553. return newMultiMaterial;
  20554. };
  20555. MultiMaterial.prototype.serialize = function () {
  20556. var serializationObject = {};
  20557. serializationObject.name = this.name;
  20558. serializationObject.id = this.id;
  20559. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20560. serializationObject.materials = [];
  20561. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20562. var subMat = this.subMaterials[matIndex];
  20563. if (subMat) {
  20564. serializationObject.materials.push(subMat.id);
  20565. }
  20566. else {
  20567. serializationObject.materials.push(null);
  20568. }
  20569. }
  20570. return serializationObject;
  20571. };
  20572. return MultiMaterial;
  20573. })(BABYLON.Material);
  20574. BABYLON.MultiMaterial = MultiMaterial;
  20575. })(BABYLON || (BABYLON = {}));
  20576. var BABYLON;
  20577. (function (BABYLON) {
  20578. var SceneLoader = (function () {
  20579. function SceneLoader() {
  20580. }
  20581. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20582. get: function () {
  20583. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20584. },
  20585. set: function (value) {
  20586. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20587. },
  20588. enumerable: true,
  20589. configurable: true
  20590. });
  20591. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20592. get: function () {
  20593. return SceneLoader._ShowLoadingScreen;
  20594. },
  20595. set: function (value) {
  20596. SceneLoader._ShowLoadingScreen = value;
  20597. },
  20598. enumerable: true,
  20599. configurable: true
  20600. });
  20601. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20602. var dotPosition = sceneFilename.lastIndexOf(".");
  20603. var queryStringPosition = sceneFilename.indexOf("?");
  20604. if (queryStringPosition === -1) {
  20605. queryStringPosition = sceneFilename.length;
  20606. }
  20607. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20608. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20609. var plugin = this._registeredPlugins[index];
  20610. if (plugin.extensions.indexOf(extension) !== -1) {
  20611. return plugin;
  20612. }
  20613. }
  20614. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20615. };
  20616. // Public functions
  20617. SceneLoader.GetPluginForExtension = function (extension) {
  20618. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20619. var plugin = this._registeredPlugins[index];
  20620. if (plugin.extensions.indexOf(extension) !== -1) {
  20621. return plugin;
  20622. }
  20623. }
  20624. return null;
  20625. };
  20626. SceneLoader.RegisterPlugin = function (plugin) {
  20627. plugin.extensions = plugin.extensions.toLowerCase();
  20628. SceneLoader._registeredPlugins.push(plugin);
  20629. };
  20630. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20631. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20632. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20633. return;
  20634. }
  20635. var loadingToken = {};
  20636. scene._addPendingData(loadingToken);
  20637. var manifestChecked = function (success) {
  20638. scene.database = database;
  20639. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20640. var importMeshFromData = function (data) {
  20641. var meshes = [];
  20642. var particleSystems = [];
  20643. var skeletons = [];
  20644. try {
  20645. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20646. if (onerror) {
  20647. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20648. }
  20649. scene._removePendingData(loadingToken);
  20650. return;
  20651. }
  20652. }
  20653. catch (e) {
  20654. if (onerror) {
  20655. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20656. }
  20657. scene._removePendingData(loadingToken);
  20658. return;
  20659. }
  20660. if (onsuccess) {
  20661. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20662. onsuccess(meshes, particleSystems, skeletons);
  20663. scene._removePendingData(loadingToken);
  20664. }
  20665. };
  20666. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20667. // Direct load
  20668. importMeshFromData(sceneFilename.substr(5));
  20669. return;
  20670. }
  20671. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20672. importMeshFromData(data);
  20673. }, progressCallBack, database);
  20674. };
  20675. if (scene.getEngine().enableOfflineSupport) {
  20676. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20677. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20678. }
  20679. else {
  20680. manifestChecked(true);
  20681. }
  20682. };
  20683. /**
  20684. * Load a scene
  20685. * @param rootUrl a string that defines the root url for scene and resources
  20686. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20687. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20688. */
  20689. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20690. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20691. };
  20692. /**
  20693. * Append a scene
  20694. * @param rootUrl a string that defines the root url for scene and resources
  20695. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20696. * @param scene is the instance of BABYLON.Scene to append to
  20697. */
  20698. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20699. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20700. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20701. return;
  20702. }
  20703. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20704. var database;
  20705. var loadingToken = {};
  20706. scene._addPendingData(loadingToken);
  20707. if (SceneLoader.ShowLoadingScreen) {
  20708. scene.getEngine().displayLoadingUI();
  20709. }
  20710. var loadSceneFromData = function (data) {
  20711. scene.database = database;
  20712. if (!plugin.load(scene, data, rootUrl)) {
  20713. if (onerror) {
  20714. onerror(scene);
  20715. }
  20716. scene._removePendingData(loadingToken);
  20717. scene.getEngine().hideLoadingUI();
  20718. return;
  20719. }
  20720. if (onsuccess) {
  20721. onsuccess(scene);
  20722. }
  20723. scene._removePendingData(loadingToken);
  20724. if (SceneLoader.ShowLoadingScreen) {
  20725. scene.executeWhenReady(function () {
  20726. scene.getEngine().hideLoadingUI();
  20727. });
  20728. }
  20729. };
  20730. var manifestChecked = function (success) {
  20731. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20732. };
  20733. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20734. // Direct load
  20735. loadSceneFromData(sceneFilename.substr(5));
  20736. return;
  20737. }
  20738. if (rootUrl.indexOf("file:") === -1) {
  20739. if (scene.getEngine().enableOfflineSupport) {
  20740. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20741. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20742. }
  20743. else {
  20744. manifestChecked(true);
  20745. }
  20746. }
  20747. else {
  20748. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20749. }
  20750. };
  20751. // Flags
  20752. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20753. SceneLoader._ShowLoadingScreen = true;
  20754. // Members
  20755. SceneLoader._registeredPlugins = new Array();
  20756. return SceneLoader;
  20757. })();
  20758. BABYLON.SceneLoader = SceneLoader;
  20759. ;
  20760. })(BABYLON || (BABYLON = {}));
  20761. var BABYLON;
  20762. (function (BABYLON) {
  20763. var Internals;
  20764. (function (Internals) {
  20765. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20766. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20767. var parsedMaterial = parsedData.materials[index];
  20768. if (parsedMaterial.id === id) {
  20769. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20770. }
  20771. }
  20772. return null;
  20773. };
  20774. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20775. names = (names instanceof Array) ? names : [names];
  20776. for (var i in names) {
  20777. if (mesh.name === names[i]) {
  20778. hierarchyIds.push(mesh.id);
  20779. return true;
  20780. }
  20781. }
  20782. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20783. hierarchyIds.push(mesh.id);
  20784. return true;
  20785. }
  20786. return false;
  20787. };
  20788. BABYLON.SceneLoader.RegisterPlugin({
  20789. extensions: ".babylon",
  20790. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20791. var parsedData = JSON.parse(data);
  20792. var loadedSkeletonsIds = [];
  20793. var loadedMaterialsIds = [];
  20794. var hierarchyIds = [];
  20795. var index;
  20796. var cache;
  20797. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20798. var parsedMesh = parsedData.meshes[index];
  20799. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20800. if (meshesNames instanceof Array) {
  20801. // Remove found mesh name from list.
  20802. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20803. }
  20804. //Geometry?
  20805. if (parsedMesh.geometryId) {
  20806. //does the file contain geometries?
  20807. if (parsedData.geometries) {
  20808. //find the correct geometry and add it to the scene
  20809. var found = false;
  20810. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20811. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20812. return;
  20813. }
  20814. else {
  20815. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20816. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20817. switch (geometryType) {
  20818. case "boxes":
  20819. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20820. break;
  20821. case "spheres":
  20822. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20823. break;
  20824. case "cylinders":
  20825. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20826. break;
  20827. case "toruses":
  20828. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20829. break;
  20830. case "grounds":
  20831. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20832. break;
  20833. case "planes":
  20834. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20835. break;
  20836. case "torusKnots":
  20837. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20838. break;
  20839. case "vertexData":
  20840. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20841. break;
  20842. }
  20843. found = true;
  20844. }
  20845. });
  20846. }
  20847. });
  20848. if (!found) {
  20849. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20850. }
  20851. }
  20852. }
  20853. // Material ?
  20854. if (parsedMesh.materialId) {
  20855. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20856. if (!materialFound && parsedData.multiMaterials) {
  20857. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20858. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20859. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20860. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20861. var subMatId = parsedMultiMaterial.materials[matIndex];
  20862. loadedMaterialsIds.push(subMatId);
  20863. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20864. }
  20865. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20866. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20867. materialFound = true;
  20868. break;
  20869. }
  20870. }
  20871. }
  20872. if (!materialFound) {
  20873. loadedMaterialsIds.push(parsedMesh.materialId);
  20874. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20875. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20876. }
  20877. }
  20878. }
  20879. // Skeleton ?
  20880. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20881. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20882. if (!skeletonAlreadyLoaded) {
  20883. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20884. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20885. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20886. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20887. loadedSkeletonsIds.push(parsedSkeleton.id);
  20888. }
  20889. }
  20890. }
  20891. }
  20892. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20893. meshes.push(mesh);
  20894. }
  20895. }
  20896. // Connecting parents
  20897. var currentMesh;
  20898. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20899. currentMesh = scene.meshes[index];
  20900. if (currentMesh._waitingParentId) {
  20901. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20902. currentMesh._waitingParentId = undefined;
  20903. }
  20904. }
  20905. // freeze and compute world matrix application
  20906. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20907. currentMesh = scene.meshes[index];
  20908. if (currentMesh._waitingFreezeWorldMatrix) {
  20909. currentMesh.freezeWorldMatrix();
  20910. currentMesh._waitingFreezeWorldMatrix = undefined;
  20911. }
  20912. else {
  20913. currentMesh.computeWorldMatrix(true);
  20914. }
  20915. }
  20916. // Particles
  20917. if (parsedData.particleSystems) {
  20918. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20919. var parsedParticleSystem = parsedData.particleSystems[index];
  20920. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20921. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20922. }
  20923. }
  20924. }
  20925. return true;
  20926. },
  20927. load: function (scene, data, rootUrl) {
  20928. var parsedData = JSON.parse(data);
  20929. // Scene
  20930. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20931. scene.autoClear = parsedData.autoClear;
  20932. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20933. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20934. if (parsedData.gravity) {
  20935. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20936. }
  20937. // Fog
  20938. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20939. scene.fogMode = parsedData.fogMode;
  20940. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20941. scene.fogStart = parsedData.fogStart;
  20942. scene.fogEnd = parsedData.fogEnd;
  20943. scene.fogDensity = parsedData.fogDensity;
  20944. }
  20945. //Physics
  20946. if (parsedData.physicsEnabled) {
  20947. var physicsPlugin;
  20948. if (parsedData.physicsEngine === "cannon") {
  20949. physicsPlugin = new BABYLON.CannonJSPlugin();
  20950. }
  20951. else if (parsedData.physicsEngine === "oimo") {
  20952. physicsPlugin = new BABYLON.OimoJSPlugin();
  20953. }
  20954. //else - default engine, which is currently oimo
  20955. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20956. scene.enablePhysics(physicsGravity, physicsPlugin);
  20957. }
  20958. //collisions, if defined. otherwise, default is true
  20959. if (parsedData.collisionsEnabled != undefined) {
  20960. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20961. }
  20962. scene.workerCollisions = !!parsedData.workerCollisions;
  20963. var index;
  20964. var cache;
  20965. // Lights
  20966. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20967. var parsedLight = parsedData.lights[index];
  20968. BABYLON.Light.Parse(parsedLight, scene);
  20969. }
  20970. // Animations
  20971. if (parsedData.animations) {
  20972. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  20973. var parsedAnimation = parsedData.animations[index];
  20974. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20975. }
  20976. }
  20977. // Materials
  20978. if (parsedData.materials) {
  20979. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20980. var parsedMaterial = parsedData.materials[index];
  20981. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20982. }
  20983. }
  20984. if (parsedData.multiMaterials) {
  20985. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20986. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20987. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20988. }
  20989. }
  20990. // Skeletons
  20991. if (parsedData.skeletons) {
  20992. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20993. var parsedSkeleton = parsedData.skeletons[index];
  20994. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20995. }
  20996. }
  20997. // Geometries
  20998. var geometries = parsedData.geometries;
  20999. if (geometries) {
  21000. // Boxes
  21001. var boxes = geometries.boxes;
  21002. if (boxes) {
  21003. for (index = 0, cache = boxes.length; index < cache; index++) {
  21004. var parsedBox = boxes[index];
  21005. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21006. }
  21007. }
  21008. // Spheres
  21009. var spheres = geometries.spheres;
  21010. if (spheres) {
  21011. for (index = 0, cache = spheres.length; index < cache; index++) {
  21012. var parsedSphere = spheres[index];
  21013. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21014. }
  21015. }
  21016. // Cylinders
  21017. var cylinders = geometries.cylinders;
  21018. if (cylinders) {
  21019. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21020. var parsedCylinder = cylinders[index];
  21021. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21022. }
  21023. }
  21024. // Toruses
  21025. var toruses = geometries.toruses;
  21026. if (toruses) {
  21027. for (index = 0, cache = toruses.length; index < cache; index++) {
  21028. var parsedTorus = toruses[index];
  21029. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21030. }
  21031. }
  21032. // Grounds
  21033. var grounds = geometries.grounds;
  21034. if (grounds) {
  21035. for (index = 0, cache = grounds.length; index < cache; index++) {
  21036. var parsedGround = grounds[index];
  21037. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21038. }
  21039. }
  21040. // Planes
  21041. var planes = geometries.planes;
  21042. if (planes) {
  21043. for (index = 0, cache = planes.length; index < cache; index++) {
  21044. var parsedPlane = planes[index];
  21045. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21046. }
  21047. }
  21048. // TorusKnots
  21049. var torusKnots = geometries.torusKnots;
  21050. if (torusKnots) {
  21051. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21052. var parsedTorusKnot = torusKnots[index];
  21053. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21054. }
  21055. }
  21056. // VertexData
  21057. var vertexData = geometries.vertexData;
  21058. if (vertexData) {
  21059. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21060. var parsedVertexData = vertexData[index];
  21061. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21062. }
  21063. }
  21064. }
  21065. // Meshes
  21066. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21067. var parsedMesh = parsedData.meshes[index];
  21068. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21069. }
  21070. // Cameras
  21071. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21072. var parsedCamera = parsedData.cameras[index];
  21073. BABYLON.Camera.Parse(parsedCamera, scene);
  21074. }
  21075. if (parsedData.activeCameraID) {
  21076. scene.setActiveCameraByID(parsedData.activeCameraID);
  21077. }
  21078. // Browsing all the graph to connect the dots
  21079. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21080. var camera = scene.cameras[index];
  21081. if (camera._waitingParentId) {
  21082. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21083. camera._waitingParentId = undefined;
  21084. }
  21085. }
  21086. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21087. var light = scene.lights[index];
  21088. if (light._waitingParentId) {
  21089. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21090. light._waitingParentId = undefined;
  21091. }
  21092. }
  21093. // Sounds
  21094. var loadedSounds = [];
  21095. var loadedSound;
  21096. if (BABYLON.AudioEngine && parsedData.sounds) {
  21097. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21098. var parsedSound = parsedData.sounds[index];
  21099. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21100. if (!parsedSound.url)
  21101. parsedSound.url = parsedSound.name;
  21102. if (!loadedSounds[parsedSound.url]) {
  21103. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21104. loadedSounds[parsedSound.url] = loadedSound;
  21105. }
  21106. else {
  21107. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21108. }
  21109. }
  21110. else {
  21111. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21112. }
  21113. }
  21114. }
  21115. loadedSounds = [];
  21116. // Connect parents & children and parse actions
  21117. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21118. var mesh = scene.meshes[index];
  21119. if (mesh._waitingParentId) {
  21120. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21121. mesh._waitingParentId = undefined;
  21122. }
  21123. if (mesh._waitingActions) {
  21124. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21125. mesh._waitingActions = undefined;
  21126. }
  21127. }
  21128. // freeze world matrix application
  21129. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21130. var currentMesh = scene.meshes[index];
  21131. if (currentMesh._waitingFreezeWorldMatrix) {
  21132. currentMesh.freezeWorldMatrix();
  21133. currentMesh._waitingFreezeWorldMatrix = undefined;
  21134. }
  21135. else {
  21136. currentMesh.computeWorldMatrix(true);
  21137. }
  21138. }
  21139. // Particles Systems
  21140. if (parsedData.particleSystems) {
  21141. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21142. var parsedParticleSystem = parsedData.particleSystems[index];
  21143. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21144. }
  21145. }
  21146. // Lens flares
  21147. if (parsedData.lensFlareSystems) {
  21148. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21149. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21150. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21151. }
  21152. }
  21153. // Shadows
  21154. if (parsedData.shadowGenerators) {
  21155. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21156. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21157. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21158. }
  21159. }
  21160. // Actions (scene)
  21161. if (parsedData.actions) {
  21162. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21163. }
  21164. // Finish
  21165. return true;
  21166. }
  21167. });
  21168. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21169. })(BABYLON || (BABYLON = {}));
  21170. var BABYLON;
  21171. (function (BABYLON) {
  21172. var SpriteManager = (function () {
  21173. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21175. this.name = name;
  21176. this.cellSize = cellSize;
  21177. this.sprites = new Array();
  21178. this.renderingGroupId = 0;
  21179. this.layerMask = 0x0FFFFFFF;
  21180. this.fogEnabled = true;
  21181. this.isPickable = false;
  21182. this._vertexDeclaration = [4, 4, 4, 4];
  21183. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21184. this._capacity = capacity;
  21185. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21186. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21187. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21188. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21189. this._scene = scene;
  21190. this._scene.spriteManagers.push(this);
  21191. // VBO
  21192. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21193. var indices = [];
  21194. var index = 0;
  21195. for (var count = 0; count < capacity; count++) {
  21196. indices.push(index);
  21197. indices.push(index + 1);
  21198. indices.push(index + 2);
  21199. indices.push(index);
  21200. indices.push(index + 2);
  21201. indices.push(index + 3);
  21202. index += 4;
  21203. }
  21204. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21205. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21206. // Effects
  21207. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21208. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21209. }
  21210. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21211. var arrayOffset = index * 16;
  21212. if (offsetX === 0)
  21213. offsetX = this._epsilon;
  21214. else if (offsetX === 1)
  21215. offsetX = 1 - this._epsilon;
  21216. if (offsetY === 0)
  21217. offsetY = this._epsilon;
  21218. else if (offsetY === 1)
  21219. offsetY = 1 - this._epsilon;
  21220. this._vertices[arrayOffset] = sprite.position.x;
  21221. this._vertices[arrayOffset + 1] = sprite.position.y;
  21222. this._vertices[arrayOffset + 2] = sprite.position.z;
  21223. this._vertices[arrayOffset + 3] = sprite.angle;
  21224. this._vertices[arrayOffset + 4] = sprite.width;
  21225. this._vertices[arrayOffset + 5] = sprite.height;
  21226. this._vertices[arrayOffset + 6] = offsetX;
  21227. this._vertices[arrayOffset + 7] = offsetY;
  21228. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21229. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21230. var offset = (sprite.cellIndex / rowSize) >> 0;
  21231. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21232. this._vertices[arrayOffset + 11] = offset;
  21233. // Color
  21234. this._vertices[arrayOffset + 12] = sprite.color.r;
  21235. this._vertices[arrayOffset + 13] = sprite.color.g;
  21236. this._vertices[arrayOffset + 14] = sprite.color.b;
  21237. this._vertices[arrayOffset + 15] = sprite.color.a;
  21238. };
  21239. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21240. var count = Math.min(this._capacity, this.sprites.length);
  21241. var min = BABYLON.Vector3.Zero();
  21242. var max = BABYLON.Vector3.Zero();
  21243. var distance = Number.MAX_VALUE;
  21244. var currentSprite;
  21245. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21246. var cameraView = camera.getViewMatrix();
  21247. for (var index = 0; index < count; index++) {
  21248. var sprite = this.sprites[index];
  21249. if (!sprite) {
  21250. continue;
  21251. }
  21252. if (predicate) {
  21253. if (!predicate(sprite)) {
  21254. continue;
  21255. }
  21256. }
  21257. else if (!sprite.isPickable) {
  21258. continue;
  21259. }
  21260. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21261. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21262. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21263. if (ray.intersectsBoxMinMax(min, max)) {
  21264. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21265. if (distance > currentDistance) {
  21266. distance = currentDistance;
  21267. currentSprite = sprite;
  21268. if (fastCheck) {
  21269. break;
  21270. }
  21271. }
  21272. }
  21273. }
  21274. if (currentSprite) {
  21275. var result = new BABYLON.PickingInfo();
  21276. result.hit = true;
  21277. result.pickedSprite = currentSprite;
  21278. result.distance = distance;
  21279. return result;
  21280. }
  21281. return null;
  21282. };
  21283. SpriteManager.prototype.render = function () {
  21284. // Check
  21285. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21286. return;
  21287. var engine = this._scene.getEngine();
  21288. var baseSize = this._spriteTexture.getBaseSize();
  21289. // Sprites
  21290. var deltaTime = engine.getDeltaTime();
  21291. var max = Math.min(this._capacity, this.sprites.length);
  21292. var rowSize = baseSize.width / this.cellSize;
  21293. var offset = 0;
  21294. for (var index = 0; index < max; index++) {
  21295. var sprite = this.sprites[index];
  21296. if (!sprite) {
  21297. continue;
  21298. }
  21299. sprite._animate(deltaTime);
  21300. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21301. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21302. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21303. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21304. }
  21305. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21306. // Render
  21307. var effect = this._effectBase;
  21308. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21309. effect = this._effectFog;
  21310. }
  21311. engine.enableEffect(effect);
  21312. var viewMatrix = this._scene.getViewMatrix();
  21313. effect.setTexture("diffuseSampler", this._spriteTexture);
  21314. effect.setMatrix("view", viewMatrix);
  21315. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21316. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21317. // Fog
  21318. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21319. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21320. effect.setColor3("vFogColor", this._scene.fogColor);
  21321. }
  21322. // VBOs
  21323. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21324. // Draw order
  21325. engine.setDepthFunctionToLessOrEqual();
  21326. effect.setBool("alphaTest", true);
  21327. engine.setColorWrite(false);
  21328. engine.draw(true, 0, max * 6);
  21329. engine.setColorWrite(true);
  21330. effect.setBool("alphaTest", false);
  21331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21332. engine.draw(true, 0, max * 6);
  21333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21334. };
  21335. SpriteManager.prototype.dispose = function () {
  21336. if (this._vertexBuffer) {
  21337. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21338. this._vertexBuffer = null;
  21339. }
  21340. if (this._indexBuffer) {
  21341. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21342. this._indexBuffer = null;
  21343. }
  21344. if (this._spriteTexture) {
  21345. this._spriteTexture.dispose();
  21346. this._spriteTexture = null;
  21347. }
  21348. // Remove from scene
  21349. var index = this._scene.spriteManagers.indexOf(this);
  21350. this._scene.spriteManagers.splice(index, 1);
  21351. // Callback
  21352. if (this.onDispose) {
  21353. this.onDispose();
  21354. }
  21355. };
  21356. return SpriteManager;
  21357. })();
  21358. BABYLON.SpriteManager = SpriteManager;
  21359. })(BABYLON || (BABYLON = {}));
  21360. var BABYLON;
  21361. (function (BABYLON) {
  21362. var Sprite = (function () {
  21363. function Sprite(name, manager) {
  21364. this.name = name;
  21365. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21366. this.width = 1.0;
  21367. this.height = 1.0;
  21368. this.angle = 0;
  21369. this.cellIndex = 0;
  21370. this.invertU = 0;
  21371. this.invertV = 0;
  21372. this.animations = new Array();
  21373. this.isPickable = false;
  21374. this._animationStarted = false;
  21375. this._loopAnimation = false;
  21376. this._fromIndex = 0;
  21377. this._toIndex = 0;
  21378. this._delay = 0;
  21379. this._direction = 1;
  21380. this._frameCount = 0;
  21381. this._time = 0;
  21382. this._manager = manager;
  21383. this._manager.sprites.push(this);
  21384. this.position = BABYLON.Vector3.Zero();
  21385. }
  21386. Object.defineProperty(Sprite.prototype, "size", {
  21387. get: function () {
  21388. return this.width;
  21389. },
  21390. set: function (value) {
  21391. this.width = value;
  21392. this.height = value;
  21393. },
  21394. enumerable: true,
  21395. configurable: true
  21396. });
  21397. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21398. this._fromIndex = from;
  21399. this._toIndex = to;
  21400. this._loopAnimation = loop;
  21401. this._delay = delay;
  21402. this._animationStarted = true;
  21403. this._direction = from < to ? 1 : -1;
  21404. this.cellIndex = from;
  21405. this._time = 0;
  21406. };
  21407. Sprite.prototype.stopAnimation = function () {
  21408. this._animationStarted = false;
  21409. };
  21410. Sprite.prototype._animate = function (deltaTime) {
  21411. if (!this._animationStarted)
  21412. return;
  21413. this._time += deltaTime;
  21414. if (this._time > this._delay) {
  21415. this._time = this._time % this._delay;
  21416. this.cellIndex += this._direction;
  21417. if (this.cellIndex == this._toIndex) {
  21418. if (this._loopAnimation) {
  21419. this.cellIndex = this._fromIndex;
  21420. }
  21421. else {
  21422. this._animationStarted = false;
  21423. if (this.disposeWhenFinishedAnimating) {
  21424. this.dispose();
  21425. }
  21426. }
  21427. }
  21428. }
  21429. };
  21430. Sprite.prototype.dispose = function () {
  21431. for (var i = 0; i < this._manager.sprites.length; i++) {
  21432. if (this._manager.sprites[i] == this) {
  21433. this._manager.sprites.splice(i, 1);
  21434. }
  21435. }
  21436. };
  21437. return Sprite;
  21438. })();
  21439. BABYLON.Sprite = Sprite;
  21440. })(BABYLON || (BABYLON = {}));
  21441. var BABYLON;
  21442. (function (BABYLON) {
  21443. var Layer = (function () {
  21444. function Layer(name, imgUrl, scene, isBackground, color) {
  21445. this.name = name;
  21446. this.scale = new BABYLON.Vector2(1, 1);
  21447. this.offset = new BABYLON.Vector2(0, 0);
  21448. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21449. this._vertexDeclaration = [2];
  21450. this._vertexStrideSize = 2 * 4;
  21451. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21452. this.isBackground = isBackground === undefined ? true : isBackground;
  21453. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21454. this._scene = scene;
  21455. this._scene.layers.push(this);
  21456. // VBO
  21457. var vertices = [];
  21458. vertices.push(1, 1);
  21459. vertices.push(-1, 1);
  21460. vertices.push(-1, -1);
  21461. vertices.push(1, -1);
  21462. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21463. // Indices
  21464. var indices = [];
  21465. indices.push(0);
  21466. indices.push(1);
  21467. indices.push(2);
  21468. indices.push(0);
  21469. indices.push(2);
  21470. indices.push(3);
  21471. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21472. // Effects
  21473. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21474. }
  21475. Layer.prototype.render = function () {
  21476. // Check
  21477. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21478. return;
  21479. var engine = this._scene.getEngine();
  21480. // Render
  21481. engine.enableEffect(this._effect);
  21482. engine.setState(false);
  21483. // Texture
  21484. this._effect.setTexture("textureSampler", this.texture);
  21485. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21486. // Color
  21487. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21488. // Scale / offset
  21489. this._effect.setVector2("offset", this.offset);
  21490. this._effect.setVector2("scale", this.scale);
  21491. // VBOs
  21492. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21493. // Draw order
  21494. engine.setAlphaMode(this.alphaBlendingMode);
  21495. engine.draw(true, 0, 6);
  21496. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21497. };
  21498. Layer.prototype.dispose = function () {
  21499. if (this._vertexBuffer) {
  21500. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21501. this._vertexBuffer = null;
  21502. }
  21503. if (this._indexBuffer) {
  21504. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21505. this._indexBuffer = null;
  21506. }
  21507. if (this.texture) {
  21508. this.texture.dispose();
  21509. this.texture = null;
  21510. }
  21511. // Remove from scene
  21512. var index = this._scene.layers.indexOf(this);
  21513. this._scene.layers.splice(index, 1);
  21514. // Callback
  21515. if (this.onDispose) {
  21516. this.onDispose();
  21517. }
  21518. };
  21519. return Layer;
  21520. })();
  21521. BABYLON.Layer = Layer;
  21522. })(BABYLON || (BABYLON = {}));
  21523. var BABYLON;
  21524. (function (BABYLON) {
  21525. var Particle = (function () {
  21526. function Particle() {
  21527. this.position = BABYLON.Vector3.Zero();
  21528. this.direction = BABYLON.Vector3.Zero();
  21529. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21530. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21531. this.lifeTime = 1.0;
  21532. this.age = 0;
  21533. this.size = 0;
  21534. this.angle = 0;
  21535. this.angularSpeed = 0;
  21536. }
  21537. Particle.prototype.copyTo = function (other) {
  21538. other.position.copyFrom(this.position);
  21539. other.direction.copyFrom(this.direction);
  21540. other.color.copyFrom(this.color);
  21541. other.colorStep.copyFrom(this.colorStep);
  21542. other.lifeTime = this.lifeTime;
  21543. other.age = this.age;
  21544. other.size = this.size;
  21545. other.angle = this.angle;
  21546. other.angularSpeed = this.angularSpeed;
  21547. };
  21548. return Particle;
  21549. })();
  21550. BABYLON.Particle = Particle;
  21551. })(BABYLON || (BABYLON = {}));
  21552. var BABYLON;
  21553. (function (BABYLON) {
  21554. var randomNumber = function (min, max) {
  21555. if (min === max) {
  21556. return (min);
  21557. }
  21558. var random = Math.random();
  21559. return ((random * (max - min)) + min);
  21560. };
  21561. var ParticleSystem = (function () {
  21562. function ParticleSystem(name, capacity, scene, customEffect) {
  21563. var _this = this;
  21564. this.name = name;
  21565. // Members
  21566. this.animations = [];
  21567. this.renderingGroupId = 0;
  21568. this.emitter = null;
  21569. this.emitRate = 10;
  21570. this.manualEmitCount = -1;
  21571. this.updateSpeed = 0.01;
  21572. this.targetStopDuration = 0;
  21573. this.disposeOnStop = false;
  21574. this.minEmitPower = 1;
  21575. this.maxEmitPower = 1;
  21576. this.minLifeTime = 1;
  21577. this.maxLifeTime = 1;
  21578. this.minSize = 1;
  21579. this.maxSize = 1;
  21580. this.minAngularSpeed = 0;
  21581. this.maxAngularSpeed = 0;
  21582. this.layerMask = 0x0FFFFFFF;
  21583. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21584. this.forceDepthWrite = false;
  21585. this.gravity = BABYLON.Vector3.Zero();
  21586. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21587. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21588. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21589. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21590. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21591. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21592. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21593. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21594. this.particles = new Array();
  21595. this._vertexDeclaration = [3, 4, 4];
  21596. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21597. this._stockParticles = new Array();
  21598. this._newPartsExcess = 0;
  21599. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21600. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21601. this._scaledDirection = BABYLON.Vector3.Zero();
  21602. this._scaledGravity = BABYLON.Vector3.Zero();
  21603. this._currentRenderId = -1;
  21604. this._started = false;
  21605. this._stopped = false;
  21606. this._actualFrame = 0;
  21607. this.id = name;
  21608. this._capacity = capacity;
  21609. this._scene = scene;
  21610. this._customEffect = customEffect;
  21611. scene.particleSystems.push(this);
  21612. // VBO
  21613. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21614. var indices = [];
  21615. var index = 0;
  21616. for (var count = 0; count < capacity; count++) {
  21617. indices.push(index);
  21618. indices.push(index + 1);
  21619. indices.push(index + 2);
  21620. indices.push(index);
  21621. indices.push(index + 2);
  21622. indices.push(index + 3);
  21623. index += 4;
  21624. }
  21625. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21626. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21627. // Default behaviors
  21628. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21629. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21630. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21631. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21632. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21633. };
  21634. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21635. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21636. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21637. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21638. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21639. };
  21640. this.updateFunction = function (particles) {
  21641. for (var index = 0; index < particles.length; index++) {
  21642. var particle = particles[index];
  21643. particle.age += _this._scaledUpdateSpeed;
  21644. if (particle.age >= particle.lifeTime) {
  21645. _this.recycleParticle(particle);
  21646. index--;
  21647. continue;
  21648. }
  21649. else {
  21650. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21651. particle.color.addInPlace(_this._scaledColorStep);
  21652. if (particle.color.a < 0)
  21653. particle.color.a = 0;
  21654. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21655. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21656. particle.position.addInPlace(_this._scaledDirection);
  21657. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21658. particle.direction.addInPlace(_this._scaledGravity);
  21659. }
  21660. }
  21661. };
  21662. }
  21663. ParticleSystem.prototype.recycleParticle = function (particle) {
  21664. var lastParticle = this.particles.pop();
  21665. if (lastParticle !== particle) {
  21666. lastParticle.copyTo(particle);
  21667. this._stockParticles.push(lastParticle);
  21668. }
  21669. };
  21670. ParticleSystem.prototype.getCapacity = function () {
  21671. return this._capacity;
  21672. };
  21673. ParticleSystem.prototype.isAlive = function () {
  21674. return this._alive;
  21675. };
  21676. ParticleSystem.prototype.isStarted = function () {
  21677. return this._started;
  21678. };
  21679. ParticleSystem.prototype.start = function () {
  21680. this._started = true;
  21681. this._stopped = false;
  21682. this._actualFrame = 0;
  21683. };
  21684. ParticleSystem.prototype.stop = function () {
  21685. this._stopped = true;
  21686. };
  21687. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21688. var offset = index * 11;
  21689. this._vertices[offset] = particle.position.x;
  21690. this._vertices[offset + 1] = particle.position.y;
  21691. this._vertices[offset + 2] = particle.position.z;
  21692. this._vertices[offset + 3] = particle.color.r;
  21693. this._vertices[offset + 4] = particle.color.g;
  21694. this._vertices[offset + 5] = particle.color.b;
  21695. this._vertices[offset + 6] = particle.color.a;
  21696. this._vertices[offset + 7] = particle.angle;
  21697. this._vertices[offset + 8] = particle.size;
  21698. this._vertices[offset + 9] = offsetX;
  21699. this._vertices[offset + 10] = offsetY;
  21700. };
  21701. ParticleSystem.prototype._update = function (newParticles) {
  21702. // Update current
  21703. this._alive = this.particles.length > 0;
  21704. this.updateFunction(this.particles);
  21705. // Add new ones
  21706. var worldMatrix;
  21707. if (this.emitter.position) {
  21708. worldMatrix = this.emitter.getWorldMatrix();
  21709. }
  21710. else {
  21711. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21712. }
  21713. var particle;
  21714. for (var index = 0; index < newParticles; index++) {
  21715. if (this.particles.length === this._capacity) {
  21716. break;
  21717. }
  21718. if (this._stockParticles.length !== 0) {
  21719. particle = this._stockParticles.pop();
  21720. particle.age = 0;
  21721. }
  21722. else {
  21723. particle = new BABYLON.Particle();
  21724. }
  21725. this.particles.push(particle);
  21726. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21727. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21728. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21729. particle.size = randomNumber(this.minSize, this.maxSize);
  21730. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21731. this.startPositionFunction(worldMatrix, particle.position, particle);
  21732. var step = randomNumber(0, 1.0);
  21733. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21734. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21735. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21736. }
  21737. };
  21738. ParticleSystem.prototype._getEffect = function () {
  21739. if (this._customEffect) {
  21740. return this._customEffect;
  21741. }
  21742. ;
  21743. var defines = [];
  21744. if (this._scene.clipPlane) {
  21745. defines.push("#define CLIPPLANE");
  21746. }
  21747. // Effect
  21748. var join = defines.join("\n");
  21749. if (this._cachedDefines !== join) {
  21750. this._cachedDefines = join;
  21751. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21752. }
  21753. return this._effect;
  21754. };
  21755. ParticleSystem.prototype.animate = function () {
  21756. if (!this._started)
  21757. return;
  21758. var effect = this._getEffect();
  21759. // Check
  21760. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21761. return;
  21762. if (this._currentRenderId === this._scene.getRenderId()) {
  21763. return;
  21764. }
  21765. this._currentRenderId = this._scene.getRenderId();
  21766. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21767. // determine the number of particles we need to create
  21768. var newParticles;
  21769. if (this.manualEmitCount > -1) {
  21770. newParticles = this.manualEmitCount;
  21771. this._newPartsExcess = 0;
  21772. this.manualEmitCount = 0;
  21773. }
  21774. else {
  21775. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21776. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21777. }
  21778. if (this._newPartsExcess > 1.0) {
  21779. newParticles += this._newPartsExcess >> 0;
  21780. this._newPartsExcess -= this._newPartsExcess >> 0;
  21781. }
  21782. this._alive = false;
  21783. if (!this._stopped) {
  21784. this._actualFrame += this._scaledUpdateSpeed;
  21785. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21786. this.stop();
  21787. }
  21788. else {
  21789. newParticles = 0;
  21790. }
  21791. this._update(newParticles);
  21792. // Stopped?
  21793. if (this._stopped) {
  21794. if (!this._alive) {
  21795. this._started = false;
  21796. if (this.disposeOnStop) {
  21797. this._scene._toBeDisposed.push(this);
  21798. }
  21799. }
  21800. }
  21801. // Update VBO
  21802. var offset = 0;
  21803. for (var index = 0; index < this.particles.length; index++) {
  21804. var particle = this.particles[index];
  21805. this._appendParticleVertex(offset++, particle, 0, 0);
  21806. this._appendParticleVertex(offset++, particle, 1, 0);
  21807. this._appendParticleVertex(offset++, particle, 1, 1);
  21808. this._appendParticleVertex(offset++, particle, 0, 1);
  21809. }
  21810. var engine = this._scene.getEngine();
  21811. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21812. };
  21813. ParticleSystem.prototype.render = function () {
  21814. var effect = this._getEffect();
  21815. // Check
  21816. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21817. return 0;
  21818. var engine = this._scene.getEngine();
  21819. // Render
  21820. engine.enableEffect(effect);
  21821. engine.setState(false);
  21822. var viewMatrix = this._scene.getViewMatrix();
  21823. effect.setTexture("diffuseSampler", this.particleTexture);
  21824. effect.setMatrix("view", viewMatrix);
  21825. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21826. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21827. if (this._scene.clipPlane) {
  21828. var clipPlane = this._scene.clipPlane;
  21829. var invView = viewMatrix.clone();
  21830. invView.invert();
  21831. effect.setMatrix("invView", invView);
  21832. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21833. }
  21834. // VBOs
  21835. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21836. // Draw order
  21837. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21838. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21839. }
  21840. else {
  21841. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21842. }
  21843. if (this.forceDepthWrite) {
  21844. engine.setDepthWrite(true);
  21845. }
  21846. engine.draw(true, 0, this.particles.length * 6);
  21847. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21848. return this.particles.length;
  21849. };
  21850. ParticleSystem.prototype.dispose = function () {
  21851. if (this._vertexBuffer) {
  21852. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21853. this._vertexBuffer = null;
  21854. }
  21855. if (this._indexBuffer) {
  21856. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21857. this._indexBuffer = null;
  21858. }
  21859. if (this.particleTexture) {
  21860. this.particleTexture.dispose();
  21861. this.particleTexture = null;
  21862. }
  21863. // Remove from scene
  21864. var index = this._scene.particleSystems.indexOf(this);
  21865. this._scene.particleSystems.splice(index, 1);
  21866. // Callback
  21867. if (this.onDispose) {
  21868. this.onDispose();
  21869. }
  21870. };
  21871. // Clone
  21872. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21873. var result = new ParticleSystem(name, this._capacity, this._scene);
  21874. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21875. if (newEmitter === undefined) {
  21876. newEmitter = this.emitter;
  21877. }
  21878. result.emitter = newEmitter;
  21879. if (this.particleTexture) {
  21880. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21881. }
  21882. result.start();
  21883. return result;
  21884. };
  21885. ParticleSystem.prototype.serialize = function () {
  21886. var serializationObject = {};
  21887. serializationObject.name = this.name;
  21888. // Emitter
  21889. if (this.emitter.position) {
  21890. serializationObject.emitterId = this.emitter.id;
  21891. }
  21892. else {
  21893. serializationObject.emitter = this.emitter.asArray();
  21894. ;
  21895. }
  21896. serializationObject.capacity = this.getCapacity();
  21897. if (this.particleTexture) {
  21898. serializationObject.textureName = this.particleTexture.name;
  21899. }
  21900. // Animations
  21901. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21902. // Particle system
  21903. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21904. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21905. serializationObject.minSize = this.minSize;
  21906. serializationObject.maxSize = this.maxSize;
  21907. serializationObject.minEmitPower = this.minEmitPower;
  21908. serializationObject.maxEmitPower = this.maxEmitPower;
  21909. serializationObject.minLifeTime = this.minLifeTime;
  21910. serializationObject.maxLifeTime = this.maxLifeTime;
  21911. serializationObject.emitRate = this.emitRate;
  21912. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21913. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21914. serializationObject.gravity = this.gravity.asArray();
  21915. serializationObject.direction1 = this.direction1.asArray();
  21916. serializationObject.direction2 = this.direction2.asArray();
  21917. serializationObject.color1 = this.color1.asArray();
  21918. serializationObject.color2 = this.color2.asArray();
  21919. serializationObject.colorDead = this.colorDead.asArray();
  21920. serializationObject.updateSpeed = this.updateSpeed;
  21921. serializationObject.targetStopDuration = this.targetStopDuration;
  21922. serializationObject.textureMask = this.textureMask.asArray();
  21923. serializationObject.blendMode = this.blendMode;
  21924. return serializationObject;
  21925. };
  21926. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21927. var name = parsedParticleSystem.name;
  21928. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21929. // Texture
  21930. if (parsedParticleSystem.textureName) {
  21931. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21932. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21933. }
  21934. // Emitter
  21935. if (parsedParticleSystem.emitterId) {
  21936. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21937. }
  21938. else {
  21939. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21940. }
  21941. // Animations
  21942. if (parsedParticleSystem.animations) {
  21943. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  21944. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  21945. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21946. }
  21947. }
  21948. // Particle system
  21949. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21950. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21951. particleSystem.minSize = parsedParticleSystem.minSize;
  21952. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21953. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21954. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21955. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21956. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21957. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21958. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21959. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21960. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21961. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21962. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21963. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21964. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21965. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21966. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21967. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21968. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21969. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21970. particleSystem.start();
  21971. return particleSystem;
  21972. };
  21973. // Statics
  21974. ParticleSystem.BLENDMODE_ONEONE = 0;
  21975. ParticleSystem.BLENDMODE_STANDARD = 1;
  21976. return ParticleSystem;
  21977. })();
  21978. BABYLON.ParticleSystem = ParticleSystem;
  21979. })(BABYLON || (BABYLON = {}));
  21980. var BABYLON;
  21981. (function (BABYLON) {
  21982. var AnimationRange = (function () {
  21983. function AnimationRange(name, from, to) {
  21984. this.name = name;
  21985. this.from = from;
  21986. this.to = to;
  21987. }
  21988. return AnimationRange;
  21989. })();
  21990. BABYLON.AnimationRange = AnimationRange;
  21991. /**
  21992. * Composed of a frame, and an action function
  21993. */
  21994. var AnimationEvent = (function () {
  21995. function AnimationEvent(frame, action, onlyOnce) {
  21996. this.frame = frame;
  21997. this.action = action;
  21998. this.onlyOnce = onlyOnce;
  21999. this.isDone = false;
  22000. }
  22001. return AnimationEvent;
  22002. })();
  22003. BABYLON.AnimationEvent = AnimationEvent;
  22004. var Animation = (function () {
  22005. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22006. this.name = name;
  22007. this.targetProperty = targetProperty;
  22008. this.framePerSecond = framePerSecond;
  22009. this.dataType = dataType;
  22010. this.loopMode = loopMode;
  22011. this._offsetsCache = {};
  22012. this._highLimitsCache = {};
  22013. this._stopped = false;
  22014. // The set of event that will be linked to this animation
  22015. this._events = new Array();
  22016. this.allowMatricesInterpolation = false;
  22017. this._ranges = {};
  22018. this.targetPropertyPath = targetProperty.split(".");
  22019. this.dataType = dataType;
  22020. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22021. }
  22022. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22023. var dataType = undefined;
  22024. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22025. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22026. }
  22027. else if (from instanceof BABYLON.Quaternion) {
  22028. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22029. }
  22030. else if (from instanceof BABYLON.Vector3) {
  22031. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22032. }
  22033. else if (from instanceof BABYLON.Vector2) {
  22034. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22035. }
  22036. else if (from instanceof BABYLON.Color3) {
  22037. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22038. }
  22039. if (dataType == undefined) {
  22040. return null;
  22041. }
  22042. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22043. var keys = [];
  22044. keys.push({ frame: 0, value: from });
  22045. keys.push({ frame: totalFrame, value: to });
  22046. animation.setKeys(keys);
  22047. if (easingFunction !== undefined) {
  22048. animation.setEasingFunction(easingFunction);
  22049. }
  22050. return animation;
  22051. };
  22052. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22053. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22054. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22055. };
  22056. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22057. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22058. node.animations.push(animation);
  22059. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22060. };
  22061. // Methods
  22062. /**
  22063. * Add an event to this animation.
  22064. */
  22065. Animation.prototype.addEvent = function (event) {
  22066. this._events.push(event);
  22067. };
  22068. /**
  22069. * Remove all events found at the given frame
  22070. * @param frame
  22071. */
  22072. Animation.prototype.removeEvents = function (frame) {
  22073. for (var index = 0; index < this._events.length; index++) {
  22074. if (this._events[index].frame === frame) {
  22075. this._events.splice(index, 1);
  22076. index--;
  22077. }
  22078. }
  22079. };
  22080. Animation.prototype.createRange = function (name, from, to) {
  22081. // check name not already in use; could happen for bones after serialized
  22082. if (!this._ranges[name]) {
  22083. this._ranges[name] = new AnimationRange(name, from, to);
  22084. }
  22085. };
  22086. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22087. if (deleteFrames === void 0) { deleteFrames = true; }
  22088. if (this._ranges[name]) {
  22089. if (deleteFrames) {
  22090. var from = this._ranges[name].from;
  22091. var to = this._ranges[name].to;
  22092. // this loop MUST go high to low for multiple splices to work
  22093. for (var key = this._keys.length - 1; key >= 0; key--) {
  22094. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22095. this._keys.splice(key, 1);
  22096. }
  22097. }
  22098. }
  22099. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22100. }
  22101. };
  22102. Animation.prototype.getRange = function (name) {
  22103. return this._ranges[name];
  22104. };
  22105. Animation.prototype.reset = function () {
  22106. this._offsetsCache = {};
  22107. this._highLimitsCache = {};
  22108. this.currentFrame = 0;
  22109. };
  22110. Animation.prototype.isStopped = function () {
  22111. return this._stopped;
  22112. };
  22113. Animation.prototype.getKeys = function () {
  22114. return this._keys;
  22115. };
  22116. Animation.prototype.getHighestFrame = function () {
  22117. var ret = 0;
  22118. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22119. if (ret < this._keys[key].frame) {
  22120. ret = this._keys[key].frame;
  22121. }
  22122. }
  22123. return ret;
  22124. };
  22125. Animation.prototype.getEasingFunction = function () {
  22126. return this._easingFunction;
  22127. };
  22128. Animation.prototype.setEasingFunction = function (easingFunction) {
  22129. this._easingFunction = easingFunction;
  22130. };
  22131. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22132. return startValue + (endValue - startValue) * gradient;
  22133. };
  22134. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22135. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22136. };
  22137. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22138. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22139. };
  22140. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22141. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22142. };
  22143. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22144. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22145. };
  22146. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22147. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22148. };
  22149. Animation.prototype.clone = function () {
  22150. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22151. if (this._keys) {
  22152. clone.setKeys(this._keys);
  22153. }
  22154. return clone;
  22155. };
  22156. Animation.prototype.setKeys = function (values) {
  22157. this._keys = values.slice(0);
  22158. this._offsetsCache = {};
  22159. this._highLimitsCache = {};
  22160. };
  22161. Animation.prototype._getKeyValue = function (value) {
  22162. if (typeof value === "function") {
  22163. return value();
  22164. }
  22165. return value;
  22166. };
  22167. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22168. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22169. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22170. }
  22171. this.currentFrame = currentFrame;
  22172. // Try to get a hash to find the right key
  22173. 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));
  22174. if (this._keys[startKey].frame >= currentFrame) {
  22175. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22176. startKey--;
  22177. }
  22178. }
  22179. for (var key = startKey; key < this._keys.length; key++) {
  22180. if (this._keys[key + 1].frame >= currentFrame) {
  22181. var startValue = this._getKeyValue(this._keys[key].value);
  22182. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22183. // gradient : percent of currentFrame between the frame inf and the frame sup
  22184. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22185. // check for easingFunction and correction of gradient
  22186. if (this._easingFunction != null) {
  22187. gradient = this._easingFunction.ease(gradient);
  22188. }
  22189. switch (this.dataType) {
  22190. // Float
  22191. case Animation.ANIMATIONTYPE_FLOAT:
  22192. switch (loopMode) {
  22193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22195. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22196. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22197. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22198. }
  22199. break;
  22200. // Quaternion
  22201. case Animation.ANIMATIONTYPE_QUATERNION:
  22202. var quaternion = null;
  22203. switch (loopMode) {
  22204. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22205. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22206. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22207. break;
  22208. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22209. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22210. break;
  22211. }
  22212. return quaternion;
  22213. // Vector3
  22214. case Animation.ANIMATIONTYPE_VECTOR3:
  22215. switch (loopMode) {
  22216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22218. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22219. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22220. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22221. }
  22222. // Vector2
  22223. case Animation.ANIMATIONTYPE_VECTOR2:
  22224. switch (loopMode) {
  22225. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22226. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22227. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22228. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22229. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22230. }
  22231. // Color3
  22232. case Animation.ANIMATIONTYPE_COLOR3:
  22233. switch (loopMode) {
  22234. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22235. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22236. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22237. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22238. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22239. }
  22240. // Matrix
  22241. case Animation.ANIMATIONTYPE_MATRIX:
  22242. switch (loopMode) {
  22243. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22244. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22245. if (this.allowMatricesInterpolation) {
  22246. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22247. }
  22248. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22249. return startValue;
  22250. }
  22251. default:
  22252. break;
  22253. }
  22254. break;
  22255. }
  22256. }
  22257. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22258. };
  22259. Animation.prototype.setValue = function (currentValue) {
  22260. // Set value
  22261. if (this.targetPropertyPath.length > 1) {
  22262. var property = this._target[this.targetPropertyPath[0]];
  22263. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22264. property = property[this.targetPropertyPath[index]];
  22265. }
  22266. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22267. }
  22268. else {
  22269. this._target[this.targetPropertyPath[0]] = currentValue;
  22270. }
  22271. if (this._target.markAsDirty) {
  22272. this._target.markAsDirty(this.targetProperty);
  22273. }
  22274. };
  22275. Animation.prototype.goToFrame = function (frame) {
  22276. if (frame < this._keys[0].frame) {
  22277. frame = this._keys[0].frame;
  22278. }
  22279. else if (frame > this._keys[this._keys.length - 1].frame) {
  22280. frame = this._keys[this._keys.length - 1].frame;
  22281. }
  22282. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22283. this.setValue(currentValue);
  22284. };
  22285. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22286. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22287. this._stopped = true;
  22288. return false;
  22289. }
  22290. var returnValue = true;
  22291. // Adding a start key at frame 0 if missing
  22292. if (this._keys[0].frame !== 0) {
  22293. var newKey = { frame: 0, value: this._keys[0].value };
  22294. this._keys.splice(0, 0, newKey);
  22295. }
  22296. // Check limits
  22297. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22298. from = this._keys[0].frame;
  22299. }
  22300. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22301. to = this._keys[this._keys.length - 1].frame;
  22302. }
  22303. // Compute ratio
  22304. var range = to - from;
  22305. var offsetValue;
  22306. // ratio represents the frame delta between from and to
  22307. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22308. var highLimitValue = 0;
  22309. if (ratio > range && !loop) {
  22310. returnValue = false;
  22311. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22312. }
  22313. else {
  22314. // Get max value if required
  22315. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22316. var keyOffset = to.toString() + from.toString();
  22317. if (!this._offsetsCache[keyOffset]) {
  22318. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22319. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22320. switch (this.dataType) {
  22321. // Float
  22322. case Animation.ANIMATIONTYPE_FLOAT:
  22323. this._offsetsCache[keyOffset] = toValue - fromValue;
  22324. break;
  22325. // Quaternion
  22326. case Animation.ANIMATIONTYPE_QUATERNION:
  22327. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22328. break;
  22329. // Vector3
  22330. case Animation.ANIMATIONTYPE_VECTOR3:
  22331. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22332. // Vector2
  22333. case Animation.ANIMATIONTYPE_VECTOR2:
  22334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22335. // Color3
  22336. case Animation.ANIMATIONTYPE_COLOR3:
  22337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22338. default:
  22339. break;
  22340. }
  22341. this._highLimitsCache[keyOffset] = toValue;
  22342. }
  22343. highLimitValue = this._highLimitsCache[keyOffset];
  22344. offsetValue = this._offsetsCache[keyOffset];
  22345. }
  22346. }
  22347. if (offsetValue === undefined) {
  22348. switch (this.dataType) {
  22349. // Float
  22350. case Animation.ANIMATIONTYPE_FLOAT:
  22351. offsetValue = 0;
  22352. break;
  22353. // Quaternion
  22354. case Animation.ANIMATIONTYPE_QUATERNION:
  22355. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22356. break;
  22357. // Vector3
  22358. case Animation.ANIMATIONTYPE_VECTOR3:
  22359. offsetValue = BABYLON.Vector3.Zero();
  22360. break;
  22361. // Vector2
  22362. case Animation.ANIMATIONTYPE_VECTOR2:
  22363. offsetValue = BABYLON.Vector2.Zero();
  22364. break;
  22365. // Color3
  22366. case Animation.ANIMATIONTYPE_COLOR3:
  22367. offsetValue = BABYLON.Color3.Black();
  22368. }
  22369. }
  22370. // Compute value
  22371. var repeatCount = (ratio / range) >> 0;
  22372. var currentFrame = returnValue ? from + ratio % range : to;
  22373. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22374. // Set value
  22375. this.setValue(currentValue);
  22376. // Check events
  22377. for (var index = 0; index < this._events.length; index++) {
  22378. if (currentFrame >= this._events[index].frame) {
  22379. var event = this._events[index];
  22380. if (!event.isDone) {
  22381. // If event should be done only once, remove it.
  22382. if (event.onlyOnce) {
  22383. this._events.splice(index, 1);
  22384. index--;
  22385. }
  22386. event.isDone = true;
  22387. event.action();
  22388. } // Don't do anything if the event has already be done.
  22389. }
  22390. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22391. // reset event, the animation is looping
  22392. this._events[index].isDone = false;
  22393. }
  22394. }
  22395. if (!returnValue) {
  22396. this._stopped = true;
  22397. }
  22398. return returnValue;
  22399. };
  22400. Animation.prototype.serialize = function () {
  22401. var serializationObject = {};
  22402. serializationObject.name = this.name;
  22403. serializationObject.property = this.targetProperty;
  22404. serializationObject.framePerSecond = this.framePerSecond;
  22405. serializationObject.dataType = this.dataType;
  22406. serializationObject.loopBehavior = this.loopMode;
  22407. var dataType = this.dataType;
  22408. serializationObject.keys = [];
  22409. var keys = this.getKeys();
  22410. for (var index = 0; index < keys.length; index++) {
  22411. var animationKey = keys[index];
  22412. var key = {};
  22413. key.frame = animationKey.frame;
  22414. switch (dataType) {
  22415. case Animation.ANIMATIONTYPE_FLOAT:
  22416. key.values = [animationKey.value];
  22417. break;
  22418. case Animation.ANIMATIONTYPE_QUATERNION:
  22419. case Animation.ANIMATIONTYPE_MATRIX:
  22420. case Animation.ANIMATIONTYPE_VECTOR3:
  22421. case Animation.ANIMATIONTYPE_COLOR3:
  22422. key.values = animationKey.value.asArray();
  22423. break;
  22424. }
  22425. serializationObject.keys.push(key);
  22426. }
  22427. serializationObject.ranges = [];
  22428. for (var name in this._ranges) {
  22429. var range = {};
  22430. range.name = name;
  22431. range.from = this._ranges[name].from;
  22432. range.to = this._ranges[name].to;
  22433. serializationObject.ranges.push(range);
  22434. }
  22435. return serializationObject;
  22436. };
  22437. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22438. get: function () {
  22439. return Animation._ANIMATIONTYPE_FLOAT;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22445. get: function () {
  22446. return Animation._ANIMATIONTYPE_VECTOR3;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22452. get: function () {
  22453. return Animation._ANIMATIONTYPE_VECTOR2;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22459. get: function () {
  22460. return Animation._ANIMATIONTYPE_QUATERNION;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22466. get: function () {
  22467. return Animation._ANIMATIONTYPE_MATRIX;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22473. get: function () {
  22474. return Animation._ANIMATIONTYPE_COLOR3;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22480. get: function () {
  22481. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22487. get: function () {
  22488. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22494. get: function () {
  22495. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. Animation.Parse = function (parsedAnimation) {
  22501. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22502. var dataType = parsedAnimation.dataType;
  22503. var keys = [];
  22504. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22505. var key = parsedAnimation.keys[index];
  22506. var data;
  22507. switch (dataType) {
  22508. case Animation.ANIMATIONTYPE_FLOAT:
  22509. data = key.values[0];
  22510. break;
  22511. case Animation.ANIMATIONTYPE_QUATERNION:
  22512. data = BABYLON.Quaternion.FromArray(key.values);
  22513. break;
  22514. case Animation.ANIMATIONTYPE_MATRIX:
  22515. data = BABYLON.Matrix.FromArray(key.values);
  22516. break;
  22517. case Animation.ANIMATIONTYPE_COLOR3:
  22518. data = BABYLON.Color3.FromArray(key.values);
  22519. break;
  22520. case Animation.ANIMATIONTYPE_VECTOR3:
  22521. default:
  22522. data = BABYLON.Vector3.FromArray(key.values);
  22523. break;
  22524. }
  22525. keys.push({
  22526. frame: key.frame,
  22527. value: data
  22528. });
  22529. }
  22530. animation.setKeys(keys);
  22531. if (parsedAnimation.ranges) {
  22532. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22533. data = parsedAnimation.ranges[index];
  22534. animation.createRange(data.name, data.from, data.to);
  22535. }
  22536. }
  22537. return animation;
  22538. };
  22539. Animation.AppendSerializedAnimations = function (source, destination) {
  22540. if (source.animations) {
  22541. destination.animations = [];
  22542. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22543. var animation = source.animations[animationIndex];
  22544. destination.animations.push(animation.serialize());
  22545. }
  22546. }
  22547. };
  22548. // Statics
  22549. Animation._ANIMATIONTYPE_FLOAT = 0;
  22550. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22551. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22552. Animation._ANIMATIONTYPE_MATRIX = 3;
  22553. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22554. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22555. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22556. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22557. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22558. return Animation;
  22559. })();
  22560. BABYLON.Animation = Animation;
  22561. })(BABYLON || (BABYLON = {}));
  22562. var BABYLON;
  22563. (function (BABYLON) {
  22564. var Animatable = (function () {
  22565. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22566. if (fromFrame === void 0) { fromFrame = 0; }
  22567. if (toFrame === void 0) { toFrame = 100; }
  22568. if (loopAnimation === void 0) { loopAnimation = false; }
  22569. if (speedRatio === void 0) { speedRatio = 1.0; }
  22570. this.target = target;
  22571. this.fromFrame = fromFrame;
  22572. this.toFrame = toFrame;
  22573. this.loopAnimation = loopAnimation;
  22574. this.speedRatio = speedRatio;
  22575. this.onAnimationEnd = onAnimationEnd;
  22576. this._animations = new Array();
  22577. this._paused = false;
  22578. this.animationStarted = false;
  22579. if (animations) {
  22580. this.appendAnimations(target, animations);
  22581. }
  22582. this._scene = scene;
  22583. scene._activeAnimatables.push(this);
  22584. }
  22585. // Methods
  22586. Animatable.prototype.getAnimations = function () {
  22587. return this._animations;
  22588. };
  22589. Animatable.prototype.appendAnimations = function (target, animations) {
  22590. for (var index = 0; index < animations.length; index++) {
  22591. var animation = animations[index];
  22592. animation._target = target;
  22593. this._animations.push(animation);
  22594. }
  22595. };
  22596. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22597. var animations = this._animations;
  22598. for (var index = 0; index < animations.length; index++) {
  22599. if (animations[index].targetProperty === property) {
  22600. return animations[index];
  22601. }
  22602. }
  22603. return null;
  22604. };
  22605. Animatable.prototype.reset = function () {
  22606. var animations = this._animations;
  22607. for (var index = 0; index < animations.length; index++) {
  22608. animations[index].reset();
  22609. }
  22610. this._localDelayOffset = null;
  22611. this._pausedDelay = null;
  22612. };
  22613. Animatable.prototype.goToFrame = function (frame) {
  22614. var animations = this._animations;
  22615. for (var index = 0; index < animations.length; index++) {
  22616. animations[index].goToFrame(frame);
  22617. }
  22618. };
  22619. Animatable.prototype.pause = function () {
  22620. if (this._paused) {
  22621. return;
  22622. }
  22623. this._paused = true;
  22624. };
  22625. Animatable.prototype.restart = function () {
  22626. this._paused = false;
  22627. };
  22628. Animatable.prototype.stop = function () {
  22629. var index = this._scene._activeAnimatables.indexOf(this);
  22630. if (index > -1) {
  22631. this._scene._activeAnimatables.splice(index, 1);
  22632. }
  22633. if (this.onAnimationEnd) {
  22634. this.onAnimationEnd();
  22635. }
  22636. };
  22637. Animatable.prototype._animate = function (delay) {
  22638. if (this._paused) {
  22639. this.animationStarted = false;
  22640. if (!this._pausedDelay) {
  22641. this._pausedDelay = delay;
  22642. }
  22643. return true;
  22644. }
  22645. if (!this._localDelayOffset) {
  22646. this._localDelayOffset = delay;
  22647. }
  22648. else if (this._pausedDelay) {
  22649. this._localDelayOffset += delay - this._pausedDelay;
  22650. this._pausedDelay = null;
  22651. }
  22652. // Animating
  22653. var running = false;
  22654. var animations = this._animations;
  22655. var index;
  22656. for (index = 0; index < animations.length; index++) {
  22657. var animation = animations[index];
  22658. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22659. running = running || isRunning;
  22660. }
  22661. this.animationStarted = running;
  22662. if (!running) {
  22663. // Remove from active animatables
  22664. index = this._scene._activeAnimatables.indexOf(this);
  22665. this._scene._activeAnimatables.splice(index, 1);
  22666. }
  22667. if (!running && this.onAnimationEnd) {
  22668. this.onAnimationEnd();
  22669. }
  22670. return running;
  22671. };
  22672. return Animatable;
  22673. })();
  22674. BABYLON.Animatable = Animatable;
  22675. })(BABYLON || (BABYLON = {}));
  22676. var BABYLON;
  22677. (function (BABYLON) {
  22678. var EasingFunction = (function () {
  22679. function EasingFunction() {
  22680. // Properties
  22681. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22682. }
  22683. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22684. get: function () {
  22685. return EasingFunction._EASINGMODE_EASEIN;
  22686. },
  22687. enumerable: true,
  22688. configurable: true
  22689. });
  22690. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22691. get: function () {
  22692. return EasingFunction._EASINGMODE_EASEOUT;
  22693. },
  22694. enumerable: true,
  22695. configurable: true
  22696. });
  22697. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22698. get: function () {
  22699. return EasingFunction._EASINGMODE_EASEINOUT;
  22700. },
  22701. enumerable: true,
  22702. configurable: true
  22703. });
  22704. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22705. var n = Math.min(Math.max(easingMode, 0), 2);
  22706. this._easingMode = n;
  22707. };
  22708. EasingFunction.prototype.getEasingMode = function () {
  22709. return this._easingMode;
  22710. };
  22711. EasingFunction.prototype.easeInCore = function (gradient) {
  22712. throw new Error('You must implement this method');
  22713. };
  22714. EasingFunction.prototype.ease = function (gradient) {
  22715. switch (this._easingMode) {
  22716. case EasingFunction.EASINGMODE_EASEIN:
  22717. return this.easeInCore(gradient);
  22718. case EasingFunction.EASINGMODE_EASEOUT:
  22719. return (1 - this.easeInCore(1 - gradient));
  22720. }
  22721. if (gradient >= 0.5) {
  22722. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22723. }
  22724. return (this.easeInCore(gradient * 2) * 0.5);
  22725. };
  22726. //Statics
  22727. EasingFunction._EASINGMODE_EASEIN = 0;
  22728. EasingFunction._EASINGMODE_EASEOUT = 1;
  22729. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22730. return EasingFunction;
  22731. })();
  22732. BABYLON.EasingFunction = EasingFunction;
  22733. var CircleEase = (function (_super) {
  22734. __extends(CircleEase, _super);
  22735. function CircleEase() {
  22736. _super.apply(this, arguments);
  22737. }
  22738. CircleEase.prototype.easeInCore = function (gradient) {
  22739. gradient = Math.max(0, Math.min(1, gradient));
  22740. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22741. };
  22742. return CircleEase;
  22743. })(EasingFunction);
  22744. BABYLON.CircleEase = CircleEase;
  22745. var BackEase = (function (_super) {
  22746. __extends(BackEase, _super);
  22747. function BackEase(amplitude) {
  22748. if (amplitude === void 0) { amplitude = 1; }
  22749. _super.call(this);
  22750. this.amplitude = amplitude;
  22751. }
  22752. BackEase.prototype.easeInCore = function (gradient) {
  22753. var num = Math.max(0, this.amplitude);
  22754. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22755. };
  22756. return BackEase;
  22757. })(EasingFunction);
  22758. BABYLON.BackEase = BackEase;
  22759. var BounceEase = (function (_super) {
  22760. __extends(BounceEase, _super);
  22761. function BounceEase(bounces, bounciness) {
  22762. if (bounces === void 0) { bounces = 3; }
  22763. if (bounciness === void 0) { bounciness = 2; }
  22764. _super.call(this);
  22765. this.bounces = bounces;
  22766. this.bounciness = bounciness;
  22767. }
  22768. BounceEase.prototype.easeInCore = function (gradient) {
  22769. var y = Math.max(0.0, this.bounces);
  22770. var bounciness = this.bounciness;
  22771. if (bounciness <= 1.0) {
  22772. bounciness = 1.001;
  22773. }
  22774. var num9 = Math.pow(bounciness, y);
  22775. var num5 = 1.0 - bounciness;
  22776. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22777. var num15 = gradient * num4;
  22778. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22779. var num3 = Math.floor(num65);
  22780. var num13 = num3 + 1.0;
  22781. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22782. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22783. var num7 = (num8 + num12) * 0.5;
  22784. var num6 = gradient - num7;
  22785. var num2 = num7 - num8;
  22786. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22787. };
  22788. return BounceEase;
  22789. })(EasingFunction);
  22790. BABYLON.BounceEase = BounceEase;
  22791. var CubicEase = (function (_super) {
  22792. __extends(CubicEase, _super);
  22793. function CubicEase() {
  22794. _super.apply(this, arguments);
  22795. }
  22796. CubicEase.prototype.easeInCore = function (gradient) {
  22797. return (gradient * gradient * gradient);
  22798. };
  22799. return CubicEase;
  22800. })(EasingFunction);
  22801. BABYLON.CubicEase = CubicEase;
  22802. var ElasticEase = (function (_super) {
  22803. __extends(ElasticEase, _super);
  22804. function ElasticEase(oscillations, springiness) {
  22805. if (oscillations === void 0) { oscillations = 3; }
  22806. if (springiness === void 0) { springiness = 3; }
  22807. _super.call(this);
  22808. this.oscillations = oscillations;
  22809. this.springiness = springiness;
  22810. }
  22811. ElasticEase.prototype.easeInCore = function (gradient) {
  22812. var num2;
  22813. var num3 = Math.max(0.0, this.oscillations);
  22814. var num = Math.max(0.0, this.springiness);
  22815. if (num == 0) {
  22816. num2 = gradient;
  22817. }
  22818. else {
  22819. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22820. }
  22821. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22822. };
  22823. return ElasticEase;
  22824. })(EasingFunction);
  22825. BABYLON.ElasticEase = ElasticEase;
  22826. var ExponentialEase = (function (_super) {
  22827. __extends(ExponentialEase, _super);
  22828. function ExponentialEase(exponent) {
  22829. if (exponent === void 0) { exponent = 2; }
  22830. _super.call(this);
  22831. this.exponent = exponent;
  22832. }
  22833. ExponentialEase.prototype.easeInCore = function (gradient) {
  22834. if (this.exponent <= 0) {
  22835. return gradient;
  22836. }
  22837. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22838. };
  22839. return ExponentialEase;
  22840. })(EasingFunction);
  22841. BABYLON.ExponentialEase = ExponentialEase;
  22842. var PowerEase = (function (_super) {
  22843. __extends(PowerEase, _super);
  22844. function PowerEase(power) {
  22845. if (power === void 0) { power = 2; }
  22846. _super.call(this);
  22847. this.power = power;
  22848. }
  22849. PowerEase.prototype.easeInCore = function (gradient) {
  22850. var y = Math.max(0.0, this.power);
  22851. return Math.pow(gradient, y);
  22852. };
  22853. return PowerEase;
  22854. })(EasingFunction);
  22855. BABYLON.PowerEase = PowerEase;
  22856. var QuadraticEase = (function (_super) {
  22857. __extends(QuadraticEase, _super);
  22858. function QuadraticEase() {
  22859. _super.apply(this, arguments);
  22860. }
  22861. QuadraticEase.prototype.easeInCore = function (gradient) {
  22862. return (gradient * gradient);
  22863. };
  22864. return QuadraticEase;
  22865. })(EasingFunction);
  22866. BABYLON.QuadraticEase = QuadraticEase;
  22867. var QuarticEase = (function (_super) {
  22868. __extends(QuarticEase, _super);
  22869. function QuarticEase() {
  22870. _super.apply(this, arguments);
  22871. }
  22872. QuarticEase.prototype.easeInCore = function (gradient) {
  22873. return (gradient * gradient * gradient * gradient);
  22874. };
  22875. return QuarticEase;
  22876. })(EasingFunction);
  22877. BABYLON.QuarticEase = QuarticEase;
  22878. var QuinticEase = (function (_super) {
  22879. __extends(QuinticEase, _super);
  22880. function QuinticEase() {
  22881. _super.apply(this, arguments);
  22882. }
  22883. QuinticEase.prototype.easeInCore = function (gradient) {
  22884. return (gradient * gradient * gradient * gradient * gradient);
  22885. };
  22886. return QuinticEase;
  22887. })(EasingFunction);
  22888. BABYLON.QuinticEase = QuinticEase;
  22889. var SineEase = (function (_super) {
  22890. __extends(SineEase, _super);
  22891. function SineEase() {
  22892. _super.apply(this, arguments);
  22893. }
  22894. SineEase.prototype.easeInCore = function (gradient) {
  22895. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22896. };
  22897. return SineEase;
  22898. })(EasingFunction);
  22899. BABYLON.SineEase = SineEase;
  22900. var BezierCurveEase = (function (_super) {
  22901. __extends(BezierCurveEase, _super);
  22902. function BezierCurveEase(x1, y1, x2, y2) {
  22903. if (x1 === void 0) { x1 = 0; }
  22904. if (y1 === void 0) { y1 = 0; }
  22905. if (x2 === void 0) { x2 = 1; }
  22906. if (y2 === void 0) { y2 = 1; }
  22907. _super.call(this);
  22908. this.x1 = x1;
  22909. this.y1 = y1;
  22910. this.x2 = x2;
  22911. this.y2 = y2;
  22912. }
  22913. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22914. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22915. };
  22916. return BezierCurveEase;
  22917. })(EasingFunction);
  22918. BABYLON.BezierCurveEase = BezierCurveEase;
  22919. })(BABYLON || (BABYLON = {}));
  22920. var BABYLON;
  22921. (function (BABYLON) {
  22922. var Bone = (function (_super) {
  22923. __extends(Bone, _super);
  22924. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22925. _super.call(this, name, skeleton.getScene());
  22926. this.name = name;
  22927. this.children = new Array();
  22928. this.animations = new Array();
  22929. this._worldTransform = new BABYLON.Matrix();
  22930. this._absoluteTransform = new BABYLON.Matrix();
  22931. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22932. this._skeleton = skeleton;
  22933. this._matrix = matrix;
  22934. this._baseMatrix = matrix;
  22935. this._restPose = restPose ? restPose : matrix.clone();
  22936. skeleton.bones.push(this);
  22937. if (parentBone) {
  22938. this._parent = parentBone;
  22939. parentBone.children.push(this);
  22940. }
  22941. else {
  22942. this._parent = null;
  22943. }
  22944. this._updateDifferenceMatrix();
  22945. }
  22946. // Members
  22947. Bone.prototype.getParent = function () {
  22948. return this._parent;
  22949. };
  22950. Bone.prototype.getLocalMatrix = function () {
  22951. return this._matrix;
  22952. };
  22953. Bone.prototype.getBaseMatrix = function () {
  22954. return this._baseMatrix;
  22955. };
  22956. Bone.prototype.getRestPose = function () {
  22957. return this._restPose;
  22958. };
  22959. Bone.prototype.returnToRest = function () {
  22960. this.updateMatrix(this._restPose.clone());
  22961. };
  22962. Bone.prototype.getWorldMatrix = function () {
  22963. return this._worldTransform;
  22964. };
  22965. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22966. return this._invertedAbsoluteTransform;
  22967. };
  22968. Bone.prototype.getAbsoluteTransform = function () {
  22969. return this._absoluteTransform;
  22970. };
  22971. // Methods
  22972. Bone.prototype.updateMatrix = function (matrix) {
  22973. this._baseMatrix = matrix.clone();
  22974. this._matrix = matrix.clone();
  22975. this._skeleton._markAsDirty();
  22976. this._updateDifferenceMatrix();
  22977. };
  22978. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  22979. if (!rootMatrix) {
  22980. rootMatrix = this._baseMatrix;
  22981. }
  22982. if (this._parent) {
  22983. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22984. }
  22985. else {
  22986. this._absoluteTransform.copyFrom(rootMatrix);
  22987. }
  22988. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22989. for (var index = 0; index < this.children.length; index++) {
  22990. this.children[index]._updateDifferenceMatrix();
  22991. }
  22992. };
  22993. Bone.prototype.markAsDirty = function () {
  22994. this._currentRenderId++;
  22995. this._skeleton._markAsDirty();
  22996. };
  22997. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22998. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22999. // all animation may be coming from a library skeleton, so may need to create animation
  23000. if (this.animations.length === 0) {
  23001. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23002. }
  23003. // get animation info / verify there is such a range from the source bone
  23004. var sourceRange = source.animations[0].getRange(rangeName);
  23005. if (!sourceRange) {
  23006. return false;
  23007. }
  23008. var from = sourceRange.from;
  23009. var to = sourceRange.to;
  23010. var sourceKeys = source.animations[0].getKeys();
  23011. // rescaling prep
  23012. var sourceBoneLength = source.length;
  23013. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23014. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23015. var destKeys = this.animations[0].getKeys();
  23016. // loop vars declaration / initialization
  23017. var orig;
  23018. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23019. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23020. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23021. var mat;
  23022. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23023. orig = sourceKeys[key];
  23024. if (orig.frame >= from && orig.frame <= to) {
  23025. if (scalingReqd) {
  23026. orig.value.decompose(origScale, origRotation, origTranslation);
  23027. origTranslation.scaleInPlace(ratio);
  23028. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23029. }
  23030. else {
  23031. mat = orig.value;
  23032. }
  23033. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23034. }
  23035. }
  23036. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23037. return true;
  23038. };
  23039. return Bone;
  23040. })(BABYLON.Node);
  23041. BABYLON.Bone = Bone;
  23042. })(BABYLON || (BABYLON = {}));
  23043. var BABYLON;
  23044. (function (BABYLON) {
  23045. var Skeleton = (function () {
  23046. function Skeleton(name, id, scene) {
  23047. this.name = name;
  23048. this.id = id;
  23049. this.bones = new Array();
  23050. this.needInitialSkinMatrix = false;
  23051. this._isDirty = true;
  23052. this._meshesWithPoseMatrix = new Array();
  23053. this._identity = BABYLON.Matrix.Identity();
  23054. this._ranges = {};
  23055. this.bones = [];
  23056. this._scene = scene;
  23057. scene.skeletons.push(this);
  23058. this.prepare();
  23059. //make sure it will recalculate the matrix next time prepare is called.
  23060. this._isDirty = true;
  23061. }
  23062. // Members
  23063. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23064. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23065. return mesh._bonesTransformMatrices;
  23066. }
  23067. return this._transformMatrices;
  23068. };
  23069. Skeleton.prototype.getScene = function () {
  23070. return this._scene;
  23071. };
  23072. // Methods
  23073. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23074. // check name not already in use
  23075. if (!this._ranges[name]) {
  23076. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23077. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23078. if (this.bones[i].animations[0]) {
  23079. this.bones[i].animations[0].createRange(name, from, to);
  23080. }
  23081. }
  23082. }
  23083. };
  23084. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23085. if (deleteFrames === void 0) { deleteFrames = true; }
  23086. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23087. if (this.bones[i].animations[0]) {
  23088. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23089. }
  23090. }
  23091. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23092. };
  23093. Skeleton.prototype.getAnimationRange = function (name) {
  23094. return this._ranges[name];
  23095. };
  23096. /**
  23097. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23098. */
  23099. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23100. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23101. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23102. return false;
  23103. }
  23104. var ret = true;
  23105. var frameOffset = this._getHighestAnimationFrame() + 1;
  23106. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23107. var boneDict = {};
  23108. var sourceBones = source.bones;
  23109. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23110. boneDict[sourceBones[i].name] = sourceBones[i];
  23111. }
  23112. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23113. var boneName = this.bones[i].name;
  23114. var sourceBone = boneDict[boneName];
  23115. if (sourceBone) {
  23116. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23117. }
  23118. else {
  23119. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23120. ret = false;
  23121. }
  23122. }
  23123. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23124. var range = source.getAnimationRange(name);
  23125. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23126. return ret;
  23127. };
  23128. Skeleton.prototype.returnToRest = function () {
  23129. for (var index = 0; index < this.bones.length; index++) {
  23130. this.bones[index].returnToRest();
  23131. }
  23132. };
  23133. Skeleton.prototype._getHighestAnimationFrame = function () {
  23134. var ret = 0;
  23135. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23136. if (this.bones[i].animations[0]) {
  23137. var highest = this.bones[i].animations[0].getHighestFrame();
  23138. if (ret < highest) {
  23139. ret = highest;
  23140. }
  23141. }
  23142. }
  23143. return ret;
  23144. };
  23145. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23146. var range = this.getAnimationRange(name);
  23147. if (!range) {
  23148. return null;
  23149. }
  23150. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23151. };
  23152. Skeleton.prototype._markAsDirty = function () {
  23153. this._isDirty = true;
  23154. };
  23155. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23156. this._meshesWithPoseMatrix.push(mesh);
  23157. };
  23158. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23159. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23160. if (index > -1) {
  23161. this._meshesWithPoseMatrix.splice(index, 1);
  23162. }
  23163. };
  23164. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23165. for (var index = 0; index < this.bones.length; index++) {
  23166. var bone = this.bones[index];
  23167. var parentBone = bone.getParent();
  23168. if (parentBone) {
  23169. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23170. }
  23171. else {
  23172. if (initialSkinMatrix) {
  23173. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23174. }
  23175. else {
  23176. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23177. }
  23178. }
  23179. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23180. }
  23181. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23182. };
  23183. Skeleton.prototype.prepare = function () {
  23184. if (!this._isDirty) {
  23185. return;
  23186. }
  23187. if (this.needInitialSkinMatrix) {
  23188. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23189. var mesh = this._meshesWithPoseMatrix[index];
  23190. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23191. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23192. }
  23193. var poseMatrix = mesh.getPoseMatrix();
  23194. // Prepare bones
  23195. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23196. var bone = this.bones[boneIndex];
  23197. if (!bone.getParent()) {
  23198. var matrix = bone.getBaseMatrix();
  23199. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23200. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23201. }
  23202. }
  23203. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23204. }
  23205. }
  23206. else {
  23207. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23208. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23209. }
  23210. this._computeTransformMatrices(this._transformMatrices, null);
  23211. }
  23212. this._isDirty = false;
  23213. this._scene._activeBones += this.bones.length;
  23214. };
  23215. Skeleton.prototype.getAnimatables = function () {
  23216. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23217. this._animatables = [];
  23218. for (var index = 0; index < this.bones.length; index++) {
  23219. this._animatables.push(this.bones[index]);
  23220. }
  23221. }
  23222. return this._animatables;
  23223. };
  23224. Skeleton.prototype.clone = function (name, id) {
  23225. var result = new Skeleton(name, id || name, this._scene);
  23226. for (var index = 0; index < this.bones.length; index++) {
  23227. var source = this.bones[index];
  23228. var parentBone = null;
  23229. if (source.getParent()) {
  23230. var parentIndex = this.bones.indexOf(source.getParent());
  23231. parentBone = result.bones[parentIndex];
  23232. }
  23233. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23234. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23235. }
  23236. return result;
  23237. };
  23238. Skeleton.prototype.dispose = function () {
  23239. this._meshesWithPoseMatrix = [];
  23240. // Animations
  23241. this.getScene().stopAnimation(this);
  23242. // Remove from scene
  23243. this.getScene().removeSkeleton(this);
  23244. };
  23245. Skeleton.prototype.serialize = function () {
  23246. var serializationObject = {};
  23247. serializationObject.name = this.name;
  23248. serializationObject.id = this.id;
  23249. serializationObject.bones = [];
  23250. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23251. for (var index = 0; index < this.bones.length; index++) {
  23252. var bone = this.bones[index];
  23253. var serializedBone = {
  23254. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23255. name: bone.name,
  23256. matrix: bone.getLocalMatrix().toArray(),
  23257. rest: bone.getRestPose().toArray()
  23258. };
  23259. serializationObject.bones.push(serializedBone);
  23260. if (bone.length) {
  23261. serializedBone.length = bone.length;
  23262. }
  23263. if (bone.animations && bone.animations.length > 0) {
  23264. serializedBone.animation = bone.animations[0].serialize();
  23265. }
  23266. serializationObject.ranges = [];
  23267. for (var name in this._ranges) {
  23268. var range = {};
  23269. range.name = name;
  23270. range.from = this._ranges[name].from;
  23271. range.to = this._ranges[name].to;
  23272. serializationObject.ranges.push(range);
  23273. }
  23274. }
  23275. return serializationObject;
  23276. };
  23277. Skeleton.Parse = function (parsedSkeleton, scene) {
  23278. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23279. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23280. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23281. var parsedBone = parsedSkeleton.bones[index];
  23282. var parentBone = null;
  23283. if (parsedBone.parentBoneIndex > -1) {
  23284. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23285. }
  23286. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23287. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23288. if (parsedBone.length) {
  23289. bone.length = parsedBone.length;
  23290. }
  23291. if (parsedBone.animation) {
  23292. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23293. }
  23294. }
  23295. // placed after bones, so createAnimationRange can cascade down
  23296. if (parsedSkeleton.ranges) {
  23297. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23298. var data = parsedSkeleton.ranges[index];
  23299. skeleton.createAnimationRange(data.name, data.from, data.to);
  23300. }
  23301. }
  23302. return skeleton;
  23303. };
  23304. return Skeleton;
  23305. })();
  23306. BABYLON.Skeleton = Skeleton;
  23307. })(BABYLON || (BABYLON = {}));
  23308. var BABYLON;
  23309. (function (BABYLON) {
  23310. var PostProcess = (function () {
  23311. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23313. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23314. this.name = name;
  23315. this.width = -1;
  23316. this.height = -1;
  23317. this._reusable = false;
  23318. this._textures = new BABYLON.SmartArray(2);
  23319. this._currentRenderTextureInd = 0;
  23320. if (camera != null) {
  23321. this._camera = camera;
  23322. this._scene = camera.getScene();
  23323. camera.attachPostProcess(this);
  23324. this._engine = this._scene.getEngine();
  23325. }
  23326. else {
  23327. this._engine = engine;
  23328. }
  23329. this._renderRatio = ratio;
  23330. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23331. this._reusable = reusable || false;
  23332. this._textureType = textureType;
  23333. this._samplers = samplers || [];
  23334. this._samplers.push("textureSampler");
  23335. this._fragmentUrl = fragmentUrl;
  23336. this._parameters = parameters || [];
  23337. this.updateEffect(defines);
  23338. }
  23339. PostProcess.prototype.updateEffect = function (defines) {
  23340. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23341. };
  23342. PostProcess.prototype.isReusable = function () {
  23343. return this._reusable;
  23344. };
  23345. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23346. camera = camera || this._camera;
  23347. var scene = camera.getScene();
  23348. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23349. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23350. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23351. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23352. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23353. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23354. if (this._textures.length > 0) {
  23355. for (var i = 0; i < this._textures.length; i++) {
  23356. this._engine._releaseTexture(this._textures.data[i]);
  23357. }
  23358. this._textures.reset();
  23359. }
  23360. this.width = desiredWidth;
  23361. this.height = desiredHeight;
  23362. 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 }));
  23363. if (this._reusable) {
  23364. 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 }));
  23365. }
  23366. if (this.onSizeChanged) {
  23367. this.onSizeChanged();
  23368. }
  23369. }
  23370. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23371. if (this.onActivate) {
  23372. this.onActivate(camera);
  23373. }
  23374. // Clear
  23375. if (this.clearColor) {
  23376. this._engine.clear(this.clearColor, true, true);
  23377. }
  23378. else {
  23379. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23380. }
  23381. if (this._reusable) {
  23382. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23383. }
  23384. };
  23385. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23386. get: function () {
  23387. return this._effect.isSupported;
  23388. },
  23389. enumerable: true,
  23390. configurable: true
  23391. });
  23392. PostProcess.prototype.apply = function () {
  23393. // Check
  23394. if (!this._effect.isReady())
  23395. return null;
  23396. // States
  23397. this._engine.enableEffect(this._effect);
  23398. this._engine.setState(false);
  23399. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23400. this._engine.setDepthBuffer(false);
  23401. this._engine.setDepthWrite(false);
  23402. // Texture
  23403. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23404. // Parameters
  23405. if (this.onApply) {
  23406. this.onApply(this._effect);
  23407. }
  23408. return this._effect;
  23409. };
  23410. PostProcess.prototype.dispose = function (camera) {
  23411. camera = camera || this._camera;
  23412. if (this._textures.length > 0) {
  23413. for (var i = 0; i < this._textures.length; i++) {
  23414. this._engine._releaseTexture(this._textures.data[i]);
  23415. }
  23416. this._textures.reset();
  23417. }
  23418. if (!camera) {
  23419. return;
  23420. }
  23421. camera.detachPostProcess(this);
  23422. var index = camera._postProcesses.indexOf(this);
  23423. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23424. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23425. }
  23426. };
  23427. return PostProcess;
  23428. })();
  23429. BABYLON.PostProcess = PostProcess;
  23430. })(BABYLON || (BABYLON = {}));
  23431. var BABYLON;
  23432. (function (BABYLON) {
  23433. var PostProcessManager = (function () {
  23434. function PostProcessManager(scene) {
  23435. this._vertexDeclaration = [2];
  23436. this._vertexStrideSize = 2 * 4;
  23437. this._scene = scene;
  23438. }
  23439. PostProcessManager.prototype._prepareBuffers = function () {
  23440. if (this._vertexBuffer) {
  23441. return;
  23442. }
  23443. // VBO
  23444. var vertices = [];
  23445. vertices.push(1, 1);
  23446. vertices.push(-1, 1);
  23447. vertices.push(-1, -1);
  23448. vertices.push(1, -1);
  23449. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23450. // Indices
  23451. var indices = [];
  23452. indices.push(0);
  23453. indices.push(1);
  23454. indices.push(2);
  23455. indices.push(0);
  23456. indices.push(2);
  23457. indices.push(3);
  23458. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23459. };
  23460. // Methods
  23461. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23462. var postProcesses = this._scene.activeCamera._postProcesses;
  23463. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23464. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23465. return false;
  23466. }
  23467. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23468. return true;
  23469. };
  23470. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23471. var engine = this._scene.getEngine();
  23472. for (var index = 0; index < postProcesses.length; index++) {
  23473. if (index < postProcesses.length - 1) {
  23474. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23475. }
  23476. else {
  23477. if (targetTexture) {
  23478. engine.bindFramebuffer(targetTexture);
  23479. }
  23480. else {
  23481. engine.restoreDefaultFramebuffer();
  23482. }
  23483. }
  23484. var pp = postProcesses[index];
  23485. var effect = pp.apply();
  23486. if (effect) {
  23487. if (pp.onBeforeRender) {
  23488. pp.onBeforeRender(effect);
  23489. }
  23490. // VBOs
  23491. this._prepareBuffers();
  23492. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23493. // Draw order
  23494. engine.draw(true, 0, 6);
  23495. if (pp.onAfterRender) {
  23496. pp.onAfterRender(effect);
  23497. }
  23498. }
  23499. }
  23500. // Restore depth buffer
  23501. engine.setDepthBuffer(true);
  23502. engine.setDepthWrite(true);
  23503. };
  23504. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23505. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23506. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23507. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23508. return;
  23509. }
  23510. var engine = this._scene.getEngine();
  23511. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23512. if (index < postProcessesTakenIndices.length - 1) {
  23513. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23514. }
  23515. else {
  23516. if (targetTexture) {
  23517. engine.bindFramebuffer(targetTexture, faceIndex);
  23518. }
  23519. else {
  23520. engine.restoreDefaultFramebuffer();
  23521. }
  23522. }
  23523. if (doNotPresent) {
  23524. break;
  23525. }
  23526. var pp = postProcesses[postProcessesTakenIndices[index]];
  23527. var effect = pp.apply();
  23528. if (effect) {
  23529. if (pp.onBeforeRender) {
  23530. pp.onBeforeRender(effect);
  23531. }
  23532. // VBOs
  23533. this._prepareBuffers();
  23534. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23535. // Draw order
  23536. engine.draw(true, 0, 6);
  23537. if (pp.onAfterRender) {
  23538. pp.onAfterRender(effect);
  23539. }
  23540. }
  23541. }
  23542. // Restore depth buffer
  23543. engine.setDepthBuffer(true);
  23544. engine.setDepthWrite(true);
  23545. };
  23546. PostProcessManager.prototype.dispose = function () {
  23547. if (this._vertexBuffer) {
  23548. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23549. this._vertexBuffer = null;
  23550. }
  23551. if (this._indexBuffer) {
  23552. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23553. this._indexBuffer = null;
  23554. }
  23555. };
  23556. return PostProcessManager;
  23557. })();
  23558. BABYLON.PostProcessManager = PostProcessManager;
  23559. })(BABYLON || (BABYLON = {}));
  23560. var BABYLON;
  23561. (function (BABYLON) {
  23562. var PassPostProcess = (function (_super) {
  23563. __extends(PassPostProcess, _super);
  23564. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23565. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23566. }
  23567. return PassPostProcess;
  23568. })(BABYLON.PostProcess);
  23569. BABYLON.PassPostProcess = PassPostProcess;
  23570. })(BABYLON || (BABYLON = {}));
  23571. var BABYLON;
  23572. (function (BABYLON) {
  23573. var PhysicsEngine = (function () {
  23574. function PhysicsEngine(plugin) {
  23575. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23576. }
  23577. PhysicsEngine.prototype._initialize = function (gravity) {
  23578. this._currentPlugin.initialize();
  23579. this._setGravity(gravity);
  23580. };
  23581. PhysicsEngine.prototype._runOneStep = function (delta) {
  23582. if (delta > 0.1) {
  23583. delta = 0.1;
  23584. }
  23585. else if (delta <= 0) {
  23586. delta = 1.0 / 60.0;
  23587. }
  23588. this._currentPlugin.runOneStep(delta);
  23589. };
  23590. PhysicsEngine.prototype._setGravity = function (gravity) {
  23591. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23592. this._currentPlugin.setGravity(this.gravity);
  23593. };
  23594. PhysicsEngine.prototype._getGravity = function () {
  23595. return this._currentPlugin.getGravity();
  23596. };
  23597. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23598. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23599. };
  23600. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23601. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23602. };
  23603. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23604. this._currentPlugin.unregisterMesh(mesh);
  23605. };
  23606. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23607. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23608. };
  23609. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23610. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23611. };
  23612. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23613. this._currentPlugin.updateBodyPosition(mesh);
  23614. };
  23615. PhysicsEngine.prototype.dispose = function () {
  23616. this._currentPlugin.dispose();
  23617. };
  23618. PhysicsEngine.prototype.isSupported = function () {
  23619. return this._currentPlugin.isSupported();
  23620. };
  23621. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23622. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23623. };
  23624. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23625. return this._currentPlugin.name;
  23626. };
  23627. PhysicsEngine.prototype.getWorldObject = function () {
  23628. return this._currentPlugin.getWorldObject();
  23629. };
  23630. // Statics
  23631. PhysicsEngine.NoImpostor = 0;
  23632. PhysicsEngine.SphereImpostor = 1;
  23633. PhysicsEngine.BoxImpostor = 2;
  23634. PhysicsEngine.PlaneImpostor = 3;
  23635. PhysicsEngine.MeshImpostor = 4;
  23636. PhysicsEngine.CapsuleImpostor = 5;
  23637. PhysicsEngine.ConeImpostor = 6;
  23638. PhysicsEngine.CylinderImpostor = 7;
  23639. PhysicsEngine.ConvexHullImpostor = 8;
  23640. PhysicsEngine.HeightmapImpostor = 9;
  23641. PhysicsEngine.Epsilon = 0.001;
  23642. return PhysicsEngine;
  23643. })();
  23644. BABYLON.PhysicsEngine = PhysicsEngine;
  23645. })(BABYLON || (BABYLON = {}));
  23646. var BABYLON;
  23647. (function (BABYLON) {
  23648. var VertexData = (function () {
  23649. function VertexData() {
  23650. }
  23651. VertexData.prototype.set = function (data, kind) {
  23652. switch (kind) {
  23653. case BABYLON.VertexBuffer.PositionKind:
  23654. this.positions = data;
  23655. break;
  23656. case BABYLON.VertexBuffer.NormalKind:
  23657. this.normals = data;
  23658. break;
  23659. case BABYLON.VertexBuffer.UVKind:
  23660. this.uvs = data;
  23661. break;
  23662. case BABYLON.VertexBuffer.UV2Kind:
  23663. this.uvs2 = data;
  23664. break;
  23665. case BABYLON.VertexBuffer.UV3Kind:
  23666. this.uvs3 = data;
  23667. break;
  23668. case BABYLON.VertexBuffer.UV4Kind:
  23669. this.uvs4 = data;
  23670. break;
  23671. case BABYLON.VertexBuffer.UV5Kind:
  23672. this.uvs5 = data;
  23673. break;
  23674. case BABYLON.VertexBuffer.UV6Kind:
  23675. this.uvs6 = data;
  23676. break;
  23677. case BABYLON.VertexBuffer.ColorKind:
  23678. this.colors = data;
  23679. break;
  23680. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23681. this.matricesIndices = data;
  23682. break;
  23683. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23684. this.matricesWeights = data;
  23685. break;
  23686. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23687. this.matricesIndicesExtra = data;
  23688. break;
  23689. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23690. this.matricesWeightsExtra = data;
  23691. break;
  23692. }
  23693. };
  23694. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23695. this._applyTo(mesh, updatable);
  23696. };
  23697. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23698. this._applyTo(geometry, updatable);
  23699. };
  23700. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23701. this._update(mesh);
  23702. };
  23703. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23704. this._update(geometry);
  23705. };
  23706. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23707. if (this.positions) {
  23708. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23709. }
  23710. if (this.normals) {
  23711. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23712. }
  23713. if (this.uvs) {
  23714. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23715. }
  23716. if (this.uvs2) {
  23717. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23718. }
  23719. if (this.uvs3) {
  23720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23721. }
  23722. if (this.uvs4) {
  23723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23724. }
  23725. if (this.uvs5) {
  23726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23727. }
  23728. if (this.uvs6) {
  23729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23730. }
  23731. if (this.colors) {
  23732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23733. }
  23734. if (this.matricesIndices) {
  23735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23736. }
  23737. if (this.matricesWeights) {
  23738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23739. }
  23740. if (this.matricesIndicesExtra) {
  23741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23742. }
  23743. if (this.matricesWeightsExtra) {
  23744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23745. }
  23746. if (this.indices) {
  23747. meshOrGeometry.setIndices(this.indices);
  23748. }
  23749. };
  23750. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23751. if (this.positions) {
  23752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23753. }
  23754. if (this.normals) {
  23755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23756. }
  23757. if (this.uvs) {
  23758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23759. }
  23760. if (this.uvs2) {
  23761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23762. }
  23763. if (this.uvs3) {
  23764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23765. }
  23766. if (this.uvs4) {
  23767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23768. }
  23769. if (this.uvs5) {
  23770. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23771. }
  23772. if (this.uvs6) {
  23773. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23774. }
  23775. if (this.colors) {
  23776. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23777. }
  23778. if (this.matricesIndices) {
  23779. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23780. }
  23781. if (this.matricesWeights) {
  23782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23783. }
  23784. if (this.matricesIndicesExtra) {
  23785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23786. }
  23787. if (this.matricesWeightsExtra) {
  23788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23789. }
  23790. if (this.indices) {
  23791. meshOrGeometry.setIndices(this.indices);
  23792. }
  23793. };
  23794. VertexData.prototype.transform = function (matrix) {
  23795. var transformed = BABYLON.Vector3.Zero();
  23796. var index;
  23797. if (this.positions) {
  23798. var position = BABYLON.Vector3.Zero();
  23799. for (index = 0; index < this.positions.length; index += 3) {
  23800. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23801. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23802. this.positions[index] = transformed.x;
  23803. this.positions[index + 1] = transformed.y;
  23804. this.positions[index + 2] = transformed.z;
  23805. }
  23806. }
  23807. if (this.normals) {
  23808. var normal = BABYLON.Vector3.Zero();
  23809. for (index = 0; index < this.normals.length; index += 3) {
  23810. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23811. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23812. this.normals[index] = transformed.x;
  23813. this.normals[index + 1] = transformed.y;
  23814. this.normals[index + 2] = transformed.z;
  23815. }
  23816. }
  23817. };
  23818. VertexData.prototype.merge = function (other) {
  23819. if (other.indices) {
  23820. if (!this.indices) {
  23821. this.indices = [];
  23822. }
  23823. var offset = this.positions ? this.positions.length / 3 : 0;
  23824. for (var index = 0; index < other.indices.length; index++) {
  23825. //TODO check type - if Int32Array!
  23826. this.indices.push(other.indices[index] + offset);
  23827. }
  23828. }
  23829. this.positions = this._mergeElement(this.positions, other.positions);
  23830. this.normals = this._mergeElement(this.normals, other.normals);
  23831. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23832. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23833. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23834. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23835. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23836. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23837. this.colors = this._mergeElement(this.colors, other.colors);
  23838. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23839. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23840. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23841. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23842. };
  23843. VertexData.prototype._mergeElement = function (source, other) {
  23844. if (!other)
  23845. return source;
  23846. if (!source)
  23847. return other;
  23848. var len = other.length + source.length;
  23849. var isSrcTypedArray = source instanceof Float32Array;
  23850. var isOthTypedArray = other instanceof Float32Array;
  23851. // use non-loop method when the source is Float32Array
  23852. if (isSrcTypedArray) {
  23853. var ret32 = new Float32Array(len);
  23854. ret32.set(source);
  23855. ret32.set(other, source.length);
  23856. return ret32;
  23857. }
  23858. else if (!isOthTypedArray) {
  23859. return source.concat(other);
  23860. }
  23861. else {
  23862. var ret = source.slice(0); // copy source to a separate array
  23863. for (var i = 0, len = other.length; i < len; i++) {
  23864. ret.push(other[i]);
  23865. }
  23866. return ret;
  23867. }
  23868. };
  23869. VertexData.prototype.serialize = function () {
  23870. var serializationObject = this.serialize();
  23871. if (this.positions) {
  23872. serializationObject.positions = this.positions;
  23873. }
  23874. if (this.normals) {
  23875. serializationObject.normals = this.normals;
  23876. }
  23877. if (this.uvs) {
  23878. serializationObject.uvs = this.uvs;
  23879. }
  23880. if (this.uvs2) {
  23881. serializationObject.uvs2 = this.uvs2;
  23882. }
  23883. if (this.uvs3) {
  23884. serializationObject.uvs3 = this.uvs3;
  23885. }
  23886. if (this.uvs4) {
  23887. serializationObject.uvs4 = this.uvs4;
  23888. }
  23889. if (this.uvs5) {
  23890. serializationObject.uvs5 = this.uvs5;
  23891. }
  23892. if (this.uvs6) {
  23893. serializationObject.uvs6 = this.uvs6;
  23894. }
  23895. if (this.colors) {
  23896. serializationObject.colors = this.colors;
  23897. }
  23898. if (this.matricesIndices) {
  23899. serializationObject.matricesIndices = this.matricesIndices;
  23900. serializationObject.matricesIndices._isExpanded = true;
  23901. }
  23902. if (this.matricesWeights) {
  23903. serializationObject.matricesWeights = this.matricesWeights;
  23904. }
  23905. if (this.matricesIndicesExtra) {
  23906. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23907. serializationObject.matricesIndicesExtra._isExpanded = true;
  23908. }
  23909. if (this.matricesWeightsExtra) {
  23910. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23911. }
  23912. serializationObject.indices = this.indices;
  23913. return serializationObject;
  23914. };
  23915. // Statics
  23916. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23917. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23918. };
  23919. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23920. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23921. };
  23922. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23923. var result = new VertexData();
  23924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23925. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23926. }
  23927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23928. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23929. }
  23930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23931. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23932. }
  23933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23934. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23935. }
  23936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23937. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23938. }
  23939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23940. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23941. }
  23942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23943. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23944. }
  23945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23946. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23947. }
  23948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23949. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23950. }
  23951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23952. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23953. }
  23954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23955. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23956. }
  23957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23958. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23959. }
  23960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23961. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23962. }
  23963. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23964. return result;
  23965. };
  23966. VertexData.CreateRibbon = function (options) {
  23967. var pathArray = options.pathArray;
  23968. var closeArray = options.closeArray || false;
  23969. var closePath = options.closePath || false;
  23970. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23971. var offset = options.offset || defaultOffset;
  23972. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23973. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23974. var positions = [];
  23975. var indices = [];
  23976. var normals = [];
  23977. var uvs = [];
  23978. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23979. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23980. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23981. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23982. var minlg; // minimal length among all paths from pathArray
  23983. var lg = []; // array of path lengths : nb of vertex per path
  23984. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23985. var p; // path iterator
  23986. var i; // point iterator
  23987. var j; // point iterator
  23988. // if single path in pathArray
  23989. if (pathArray.length < 2) {
  23990. var ar1 = [];
  23991. var ar2 = [];
  23992. for (i = 0; i < pathArray[0].length - offset; i++) {
  23993. ar1.push(pathArray[0][i]);
  23994. ar2.push(pathArray[0][i + offset]);
  23995. }
  23996. pathArray = [ar1, ar2];
  23997. }
  23998. // positions and horizontal distances (u)
  23999. var idc = 0;
  24000. var closePathCorr = (closePath) ? 1 : 0;
  24001. var path;
  24002. var l;
  24003. minlg = pathArray[0].length;
  24004. var vectlg;
  24005. var dist;
  24006. for (p = 0; p < pathArray.length; p++) {
  24007. uTotalDistance[p] = 0;
  24008. us[p] = [0];
  24009. path = pathArray[p];
  24010. l = path.length;
  24011. minlg = (minlg < l) ? minlg : l;
  24012. j = 0;
  24013. while (j < l) {
  24014. positions.push(path[j].x, path[j].y, path[j].z);
  24015. if (j > 0) {
  24016. vectlg = path[j].subtract(path[j - 1]).length();
  24017. dist = vectlg + uTotalDistance[p];
  24018. us[p].push(dist);
  24019. uTotalDistance[p] = dist;
  24020. }
  24021. j++;
  24022. }
  24023. if (closePath) {
  24024. j--;
  24025. positions.push(path[0].x, path[0].y, path[0].z);
  24026. vectlg = path[j].subtract(path[0]).length();
  24027. dist = vectlg + uTotalDistance[p];
  24028. us[p].push(dist);
  24029. uTotalDistance[p] = dist;
  24030. }
  24031. lg[p] = l + closePathCorr;
  24032. idx[p] = idc;
  24033. idc += (l + closePathCorr);
  24034. }
  24035. // vertical distances (v)
  24036. var path1;
  24037. var path2;
  24038. var vertex1;
  24039. var vertex2;
  24040. for (i = 0; i < minlg + closePathCorr; i++) {
  24041. vTotalDistance[i] = 0;
  24042. vs[i] = [0];
  24043. for (p = 0; p < pathArray.length - 1; p++) {
  24044. path1 = pathArray[p];
  24045. path2 = pathArray[p + 1];
  24046. if (i === minlg) {
  24047. vertex1 = path1[0];
  24048. vertex2 = path2[0];
  24049. }
  24050. else {
  24051. vertex1 = path1[i];
  24052. vertex2 = path2[i];
  24053. }
  24054. vectlg = vertex2.subtract(vertex1).length();
  24055. dist = vectlg + vTotalDistance[i];
  24056. vs[i].push(dist);
  24057. vTotalDistance[i] = dist;
  24058. }
  24059. if (closeArray) {
  24060. path1 = pathArray[p];
  24061. path2 = pathArray[0];
  24062. if (i === minlg) {
  24063. vertex2 = path2[0];
  24064. }
  24065. vectlg = vertex2.subtract(vertex1).length();
  24066. dist = vectlg + vTotalDistance[i];
  24067. vTotalDistance[i] = dist;
  24068. }
  24069. }
  24070. // uvs
  24071. var u;
  24072. var v;
  24073. for (p = 0; p < pathArray.length; p++) {
  24074. for (i = 0; i < minlg + closePathCorr; i++) {
  24075. u = us[p][i] / uTotalDistance[p];
  24076. v = vs[i][p] / vTotalDistance[i];
  24077. uvs.push(u, v);
  24078. }
  24079. }
  24080. // indices
  24081. p = 0; // path index
  24082. var pi = 0; // positions array index
  24083. var l1 = lg[p] - 1; // path1 length
  24084. var l2 = lg[p + 1] - 1; // path2 length
  24085. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24086. var shft = idx[1] - idx[0]; // shift
  24087. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24088. while (pi <= min && p < path1nb) {
  24089. // 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
  24090. indices.push(pi, pi + shft, pi + 1);
  24091. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24092. pi += 1;
  24093. if (pi === min) {
  24094. p++;
  24095. if (p === lg.length - 1) {
  24096. shft = idx[0] - idx[p];
  24097. l1 = lg[p] - 1;
  24098. l2 = lg[0] - 1;
  24099. }
  24100. else {
  24101. shft = idx[p + 1] - idx[p];
  24102. l1 = lg[p] - 1;
  24103. l2 = lg[p + 1] - 1;
  24104. }
  24105. pi = idx[p];
  24106. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24107. }
  24108. }
  24109. // normals
  24110. VertexData.ComputeNormals(positions, indices, normals);
  24111. if (closePath) {
  24112. var indexFirst = 0;
  24113. var indexLast = 0;
  24114. for (p = 0; p < pathArray.length; p++) {
  24115. indexFirst = idx[p] * 3;
  24116. if (p + 1 < pathArray.length) {
  24117. indexLast = (idx[p + 1] - 1) * 3;
  24118. }
  24119. else {
  24120. indexLast = normals.length - 3;
  24121. }
  24122. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24123. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24124. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24125. normals[indexLast] = normals[indexFirst];
  24126. normals[indexLast + 1] = normals[indexFirst + 1];
  24127. normals[indexLast + 2] = normals[indexFirst + 2];
  24128. }
  24129. }
  24130. // sides
  24131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24132. // Result
  24133. var vertexData = new VertexData();
  24134. vertexData.indices = indices;
  24135. vertexData.positions = positions;
  24136. vertexData.normals = normals;
  24137. vertexData.uvs = uvs;
  24138. if (closePath) {
  24139. vertexData._idx = idx;
  24140. }
  24141. return vertexData;
  24142. };
  24143. VertexData.CreateBox = function (options) {
  24144. var normalsSource = [
  24145. new BABYLON.Vector3(0, 0, 1),
  24146. new BABYLON.Vector3(0, 0, -1),
  24147. new BABYLON.Vector3(1, 0, 0),
  24148. new BABYLON.Vector3(-1, 0, 0),
  24149. new BABYLON.Vector3(0, 1, 0),
  24150. new BABYLON.Vector3(0, -1, 0)
  24151. ];
  24152. var indices = [];
  24153. var positions = [];
  24154. var normals = [];
  24155. var uvs = [];
  24156. var width = options.width || options.size || 1;
  24157. var height = options.height || options.size || 1;
  24158. var depth = options.depth || options.size || 1;
  24159. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24160. var faceUV = options.faceUV || new Array(6);
  24161. var faceColors = options.faceColors;
  24162. var colors = [];
  24163. // default face colors and UV if undefined
  24164. for (var f = 0; f < 6; f++) {
  24165. if (faceUV[f] === undefined) {
  24166. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24167. }
  24168. if (faceColors && faceColors[f] === undefined) {
  24169. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24170. }
  24171. }
  24172. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24173. // Create each face in turn.
  24174. for (var index = 0; index < normalsSource.length; index++) {
  24175. var normal = normalsSource[index];
  24176. // Get two vectors perpendicular to the face normal and to each other.
  24177. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24178. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24179. // Six indices (two triangles) per face.
  24180. var verticesLength = positions.length / 3;
  24181. indices.push(verticesLength);
  24182. indices.push(verticesLength + 1);
  24183. indices.push(verticesLength + 2);
  24184. indices.push(verticesLength);
  24185. indices.push(verticesLength + 2);
  24186. indices.push(verticesLength + 3);
  24187. // Four vertices per face.
  24188. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24189. positions.push(vertex.x, vertex.y, vertex.z);
  24190. normals.push(normal.x, normal.y, normal.z);
  24191. uvs.push(faceUV[index].z, faceUV[index].w);
  24192. if (faceColors) {
  24193. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24194. }
  24195. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24196. positions.push(vertex.x, vertex.y, vertex.z);
  24197. normals.push(normal.x, normal.y, normal.z);
  24198. uvs.push(faceUV[index].x, faceUV[index].w);
  24199. if (faceColors) {
  24200. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24201. }
  24202. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24203. positions.push(vertex.x, vertex.y, vertex.z);
  24204. normals.push(normal.x, normal.y, normal.z);
  24205. uvs.push(faceUV[index].x, faceUV[index].y);
  24206. if (faceColors) {
  24207. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24208. }
  24209. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24210. positions.push(vertex.x, vertex.y, vertex.z);
  24211. normals.push(normal.x, normal.y, normal.z);
  24212. uvs.push(faceUV[index].z, faceUV[index].y);
  24213. if (faceColors) {
  24214. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24215. }
  24216. }
  24217. // sides
  24218. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24219. // Result
  24220. var vertexData = new VertexData();
  24221. vertexData.indices = indices;
  24222. vertexData.positions = positions;
  24223. vertexData.normals = normals;
  24224. vertexData.uvs = uvs;
  24225. if (faceColors) {
  24226. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24227. vertexData.colors = totalColors;
  24228. }
  24229. return vertexData;
  24230. };
  24231. VertexData.CreateSphere = function (options) {
  24232. var segments = options.segments || 32;
  24233. var diameterX = options.diameterX || options.diameter || 1;
  24234. var diameterY = options.diameterY || options.diameter || 1;
  24235. var diameterZ = options.diameterZ || options.diameter || 1;
  24236. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24237. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24238. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24239. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24240. var totalZRotationSteps = 2 + segments;
  24241. var totalYRotationSteps = 2 * totalZRotationSteps;
  24242. var indices = [];
  24243. var positions = [];
  24244. var normals = [];
  24245. var uvs = [];
  24246. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24247. var normalizedZ = zRotationStep / totalZRotationSteps;
  24248. var angleZ = normalizedZ * Math.PI * slice;
  24249. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24250. var normalizedY = yRotationStep / totalYRotationSteps;
  24251. var angleY = normalizedY * Math.PI * 2 * arc;
  24252. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24253. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24254. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24255. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24256. var vertex = complete.multiply(radius);
  24257. var normal = complete.divide(radius).normalize();
  24258. positions.push(vertex.x, vertex.y, vertex.z);
  24259. normals.push(normal.x, normal.y, normal.z);
  24260. uvs.push(normalizedY, normalizedZ);
  24261. }
  24262. if (zRotationStep > 0) {
  24263. var verticesCount = positions.length / 3;
  24264. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24265. indices.push((firstIndex));
  24266. indices.push((firstIndex + 1));
  24267. indices.push(firstIndex + totalYRotationSteps + 1);
  24268. indices.push((firstIndex + totalYRotationSteps + 1));
  24269. indices.push((firstIndex + 1));
  24270. indices.push((firstIndex + totalYRotationSteps + 2));
  24271. }
  24272. }
  24273. }
  24274. // Sides
  24275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24276. // Result
  24277. var vertexData = new VertexData();
  24278. vertexData.indices = indices;
  24279. vertexData.positions = positions;
  24280. vertexData.normals = normals;
  24281. vertexData.uvs = uvs;
  24282. return vertexData;
  24283. };
  24284. // Cylinder and cone
  24285. VertexData.CreateCylinder = function (options) {
  24286. var height = options.height || 2;
  24287. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24288. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24289. var tessellation = options.tessellation || 24;
  24290. var subdivisions = options.subdivisions || 1;
  24291. var hasRings = options.hasRings;
  24292. var enclose = options.enclose;
  24293. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24294. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24295. var faceUV = options.faceUV || new Array(3);
  24296. var faceColors = options.faceColors;
  24297. // default face colors and UV if undefined
  24298. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24299. var ringNb = (hasRings) ? subdivisions : 1;
  24300. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24301. var f;
  24302. for (f = 0; f < surfaceNb; f++) {
  24303. if (faceColors && faceColors[f] === undefined) {
  24304. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24305. }
  24306. }
  24307. for (f = 0; f < surfaceNb; f++) {
  24308. if (faceUV && faceUV[f] === undefined) {
  24309. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24310. }
  24311. }
  24312. var indices = [];
  24313. var positions = [];
  24314. var normals = [];
  24315. var uvs = [];
  24316. var colors = [];
  24317. var angle_step = Math.PI * 2 * arc / tessellation;
  24318. var angle;
  24319. var h;
  24320. var radius;
  24321. var tan = (diameterBottom - diameterTop) / 2 / height;
  24322. var ringVertex = BABYLON.Vector3.Zero();
  24323. var ringNormal = BABYLON.Vector3.Zero();
  24324. var ringFirstVertex = BABYLON.Vector3.Zero();
  24325. var ringFirstNormal = BABYLON.Vector3.Zero();
  24326. var quadNormal = BABYLON.Vector3.Zero();
  24327. var Y = BABYLON.Axis.Y;
  24328. // positions, normals, uvs
  24329. var i;
  24330. var j;
  24331. var r;
  24332. var ringIdx = 1;
  24333. var s = 1; // surface index
  24334. var cs = 0;
  24335. var v = 0;
  24336. for (i = 0; i <= subdivisions; i++) {
  24337. h = i / subdivisions;
  24338. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24339. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24340. for (r = 0; r < ringIdx; r++) {
  24341. if (hasRings) {
  24342. s += r;
  24343. }
  24344. if (enclose) {
  24345. s += 2 * r;
  24346. }
  24347. for (j = 0; j <= tessellation; j++) {
  24348. angle = j * angle_step;
  24349. // position
  24350. ringVertex.x = Math.cos(-angle) * radius;
  24351. ringVertex.y = -height / 2 + h * height;
  24352. ringVertex.z = Math.sin(-angle) * radius;
  24353. // normal
  24354. if (diameterTop === 0 && i === subdivisions) {
  24355. // if no top cap, reuse former normals
  24356. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24357. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24358. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24359. }
  24360. else {
  24361. ringNormal.x = ringVertex.x;
  24362. ringNormal.z = ringVertex.z;
  24363. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24364. ringNormal.normalize();
  24365. }
  24366. // keep first ring vertex values for enclose
  24367. if (j === 0) {
  24368. ringFirstVertex.copyFrom(ringVertex);
  24369. ringFirstNormal.copyFrom(ringNormal);
  24370. }
  24371. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24372. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24373. if (hasRings) {
  24374. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24375. }
  24376. else {
  24377. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24378. }
  24379. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24380. if (faceColors) {
  24381. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24382. }
  24383. }
  24384. // if enclose, add four vertices and their dedicated normals
  24385. if (arc !== 1 && enclose) {
  24386. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24387. positions.push(0, ringVertex.y, 0);
  24388. positions.push(0, ringVertex.y, 0);
  24389. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24390. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24391. quadNormal.normalize();
  24392. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24393. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24394. quadNormal.normalize();
  24395. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24396. if (hasRings) {
  24397. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24398. }
  24399. else {
  24400. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24401. }
  24402. uvs.push(faceUV[s + 1].x, v);
  24403. uvs.push(faceUV[s + 1].z, v);
  24404. if (hasRings) {
  24405. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24406. }
  24407. else {
  24408. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24409. }
  24410. uvs.push(faceUV[s + 2].x, v);
  24411. uvs.push(faceUV[s + 2].z, v);
  24412. if (faceColors) {
  24413. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24414. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24415. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24416. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24417. }
  24418. }
  24419. if (cs !== s) {
  24420. cs = s;
  24421. }
  24422. }
  24423. }
  24424. // indices
  24425. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24426. var s;
  24427. i = 0;
  24428. for (s = 0; s < subdivisions; s++) {
  24429. for (j = 0; j < tessellation; j++) {
  24430. var i0 = i * (e + 1) + j;
  24431. var i1 = (i + 1) * (e + 1) + j;
  24432. var i2 = i * (e + 1) + (j + 1);
  24433. var i3 = (i + 1) * (e + 1) + (j + 1);
  24434. indices.push(i0, i1, i2);
  24435. indices.push(i3, i2, i1);
  24436. }
  24437. if (arc !== 1 && enclose) {
  24438. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24439. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24440. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24441. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24442. }
  24443. i = (hasRings) ? (i + 2) : (i + 1);
  24444. }
  24445. // Caps
  24446. var createCylinderCap = function (isTop) {
  24447. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24448. if (radius === 0) {
  24449. return;
  24450. }
  24451. // Cap positions, normals & uvs
  24452. var angle;
  24453. var circleVector;
  24454. var i;
  24455. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24456. var c;
  24457. if (faceColors) {
  24458. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24459. }
  24460. // cap center
  24461. var vbase = positions.length / 3;
  24462. var offset = isTop ? height / 2 : -height / 2;
  24463. var center = new BABYLON.Vector3(0, offset, 0);
  24464. positions.push(center.x, center.y, center.z);
  24465. normals.push(0, isTop ? 1 : -1, 0);
  24466. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24467. if (faceColors) {
  24468. colors.push(c.r, c.g, c.b, c.a);
  24469. }
  24470. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24471. for (i = 0; i <= tessellation; i++) {
  24472. angle = Math.PI * 2 * i * arc / tessellation;
  24473. var cos = Math.cos(-angle);
  24474. var sin = Math.sin(-angle);
  24475. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24476. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24477. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24478. normals.push(0, isTop ? 1 : -1, 0);
  24479. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24480. if (faceColors) {
  24481. colors.push(c.r, c.g, c.b, c.a);
  24482. }
  24483. }
  24484. // Cap indices
  24485. for (i = 0; i < tessellation; i++) {
  24486. if (!isTop) {
  24487. indices.push(vbase);
  24488. indices.push(vbase + (i + 1));
  24489. indices.push(vbase + (i + 2));
  24490. }
  24491. else {
  24492. indices.push(vbase);
  24493. indices.push(vbase + (i + 2));
  24494. indices.push(vbase + (i + 1));
  24495. }
  24496. }
  24497. };
  24498. // add caps to geometry
  24499. createCylinderCap(false);
  24500. createCylinderCap(true);
  24501. // Sides
  24502. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24503. var vertexData = new VertexData();
  24504. vertexData.indices = indices;
  24505. vertexData.positions = positions;
  24506. vertexData.normals = normals;
  24507. vertexData.uvs = uvs;
  24508. if (faceColors) {
  24509. vertexData.colors = colors;
  24510. }
  24511. return vertexData;
  24512. };
  24513. VertexData.CreateTorus = function (options) {
  24514. var indices = [];
  24515. var positions = [];
  24516. var normals = [];
  24517. var uvs = [];
  24518. var diameter = options.diameter || 1;
  24519. var thickness = options.thickness || 0.5;
  24520. var tessellation = options.tessellation || 16;
  24521. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24522. var stride = tessellation + 1;
  24523. for (var i = 0; i <= tessellation; i++) {
  24524. var u = i / tessellation;
  24525. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24526. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24527. for (var j = 0; j <= tessellation; j++) {
  24528. var v = 1 - j / tessellation;
  24529. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24530. var dx = Math.cos(innerAngle);
  24531. var dy = Math.sin(innerAngle);
  24532. // Create a vertex.
  24533. var normal = new BABYLON.Vector3(dx, dy, 0);
  24534. var position = normal.scale(thickness / 2);
  24535. var textureCoordinate = new BABYLON.Vector2(u, v);
  24536. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24537. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24538. positions.push(position.x, position.y, position.z);
  24539. normals.push(normal.x, normal.y, normal.z);
  24540. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24541. // And create indices for two triangles.
  24542. var nextI = (i + 1) % stride;
  24543. var nextJ = (j + 1) % stride;
  24544. indices.push(i * stride + j);
  24545. indices.push(i * stride + nextJ);
  24546. indices.push(nextI * stride + j);
  24547. indices.push(i * stride + nextJ);
  24548. indices.push(nextI * stride + nextJ);
  24549. indices.push(nextI * stride + j);
  24550. }
  24551. }
  24552. // Sides
  24553. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24554. // Result
  24555. var vertexData = new VertexData();
  24556. vertexData.indices = indices;
  24557. vertexData.positions = positions;
  24558. vertexData.normals = normals;
  24559. vertexData.uvs = uvs;
  24560. return vertexData;
  24561. };
  24562. VertexData.CreateLines = function (options) {
  24563. var indices = [];
  24564. var positions = [];
  24565. var points = options.points;
  24566. for (var index = 0; index < points.length; index++) {
  24567. positions.push(points[index].x, points[index].y, points[index].z);
  24568. if (index > 0) {
  24569. indices.push(index - 1);
  24570. indices.push(index);
  24571. }
  24572. }
  24573. // Result
  24574. var vertexData = new VertexData();
  24575. vertexData.indices = indices;
  24576. vertexData.positions = positions;
  24577. return vertexData;
  24578. };
  24579. VertexData.CreateDashedLines = function (options) {
  24580. var dashSize = options.dashSize || 3;
  24581. var gapSize = options.gapSize || 1;
  24582. var dashNb = options.dashNb || 200;
  24583. var points = options.points;
  24584. var positions = new Array();
  24585. var indices = new Array();
  24586. var curvect = BABYLON.Vector3.Zero();
  24587. var lg = 0;
  24588. var nb = 0;
  24589. var shft = 0;
  24590. var dashshft = 0;
  24591. var curshft = 0;
  24592. var idx = 0;
  24593. var i = 0;
  24594. for (i = 0; i < points.length - 1; i++) {
  24595. points[i + 1].subtractToRef(points[i], curvect);
  24596. lg += curvect.length();
  24597. }
  24598. shft = lg / dashNb;
  24599. dashshft = dashSize * shft / (dashSize + gapSize);
  24600. for (i = 0; i < points.length - 1; i++) {
  24601. points[i + 1].subtractToRef(points[i], curvect);
  24602. nb = Math.floor(curvect.length() / shft);
  24603. curvect.normalize();
  24604. for (var j = 0; j < nb; j++) {
  24605. curshft = shft * j;
  24606. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24607. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24608. indices.push(idx, idx + 1);
  24609. idx += 2;
  24610. }
  24611. }
  24612. // Result
  24613. var vertexData = new VertexData();
  24614. vertexData.positions = positions;
  24615. vertexData.indices = indices;
  24616. return vertexData;
  24617. };
  24618. VertexData.CreateGround = function (options) {
  24619. var indices = [];
  24620. var positions = [];
  24621. var normals = [];
  24622. var uvs = [];
  24623. var row, col;
  24624. var width = options.width || 1;
  24625. var height = options.height || 1;
  24626. var subdivisions = options.subdivisions || 1;
  24627. for (row = 0; row <= subdivisions; row++) {
  24628. for (col = 0; col <= subdivisions; col++) {
  24629. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24630. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24631. positions.push(position.x, position.y, position.z);
  24632. normals.push(normal.x, normal.y, normal.z);
  24633. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24634. }
  24635. }
  24636. for (row = 0; row < subdivisions; row++) {
  24637. for (col = 0; col < subdivisions; col++) {
  24638. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24639. indices.push(col + 1 + row * (subdivisions + 1));
  24640. indices.push(col + row * (subdivisions + 1));
  24641. indices.push(col + (row + 1) * (subdivisions + 1));
  24642. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24643. indices.push(col + row * (subdivisions + 1));
  24644. }
  24645. }
  24646. // Result
  24647. var vertexData = new VertexData();
  24648. vertexData.indices = indices;
  24649. vertexData.positions = positions;
  24650. vertexData.normals = normals;
  24651. vertexData.uvs = uvs;
  24652. return vertexData;
  24653. };
  24654. VertexData.CreateTiledGround = function (options) {
  24655. var xmin = options.xmin;
  24656. var zmin = options.zmin;
  24657. var xmax = options.xmax;
  24658. var zmax = options.zmax;
  24659. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24660. var precision = options.precision || { w: 1, h: 1 };
  24661. var indices = [];
  24662. var positions = [];
  24663. var normals = [];
  24664. var uvs = [];
  24665. var row, col, tileRow, tileCol;
  24666. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24667. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24668. precision.w = (precision.w < 1) ? 1 : precision.w;
  24669. precision.h = (precision.h < 1) ? 1 : precision.h;
  24670. var tileSize = {
  24671. 'w': (xmax - xmin) / subdivisions.w,
  24672. 'h': (zmax - zmin) / subdivisions.h
  24673. };
  24674. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24675. // Indices
  24676. var base = positions.length / 3;
  24677. var rowLength = precision.w + 1;
  24678. for (row = 0; row < precision.h; row++) {
  24679. for (col = 0; col < precision.w; col++) {
  24680. var square = [
  24681. base + col + row * rowLength,
  24682. base + (col + 1) + row * rowLength,
  24683. base + (col + 1) + (row + 1) * rowLength,
  24684. base + col + (row + 1) * rowLength
  24685. ];
  24686. indices.push(square[1]);
  24687. indices.push(square[2]);
  24688. indices.push(square[3]);
  24689. indices.push(square[0]);
  24690. indices.push(square[1]);
  24691. indices.push(square[3]);
  24692. }
  24693. }
  24694. // Position, normals and uvs
  24695. var position = BABYLON.Vector3.Zero();
  24696. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24697. for (row = 0; row <= precision.h; row++) {
  24698. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24699. for (col = 0; col <= precision.w; col++) {
  24700. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24701. position.y = 0;
  24702. positions.push(position.x, position.y, position.z);
  24703. normals.push(normal.x, normal.y, normal.z);
  24704. uvs.push(col / precision.w, row / precision.h);
  24705. }
  24706. }
  24707. }
  24708. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24709. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24710. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24711. }
  24712. }
  24713. // Result
  24714. var vertexData = new VertexData();
  24715. vertexData.indices = indices;
  24716. vertexData.positions = positions;
  24717. vertexData.normals = normals;
  24718. vertexData.uvs = uvs;
  24719. return vertexData;
  24720. };
  24721. VertexData.CreateGroundFromHeightMap = function (options) {
  24722. var indices = [];
  24723. var positions = [];
  24724. var normals = [];
  24725. var uvs = [];
  24726. var row, col;
  24727. // Vertices
  24728. for (row = 0; row <= options.subdivisions; row++) {
  24729. for (col = 0; col <= options.subdivisions; col++) {
  24730. 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));
  24731. // Compute height
  24732. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24733. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24734. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24735. var r = options.buffer[pos] / 255.0;
  24736. var g = options.buffer[pos + 1] / 255.0;
  24737. var b = options.buffer[pos + 2] / 255.0;
  24738. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24739. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24740. // Add vertex
  24741. positions.push(position.x, position.y, position.z);
  24742. normals.push(0, 0, 0);
  24743. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24744. }
  24745. }
  24746. // Indices
  24747. for (row = 0; row < options.subdivisions; row++) {
  24748. for (col = 0; col < options.subdivisions; col++) {
  24749. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24750. indices.push(col + 1 + row * (options.subdivisions + 1));
  24751. indices.push(col + row * (options.subdivisions + 1));
  24752. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24753. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24754. indices.push(col + row * (options.subdivisions + 1));
  24755. }
  24756. }
  24757. // Normals
  24758. VertexData.ComputeNormals(positions, indices, normals);
  24759. // Result
  24760. var vertexData = new VertexData();
  24761. vertexData.indices = indices;
  24762. vertexData.positions = positions;
  24763. vertexData.normals = normals;
  24764. vertexData.uvs = uvs;
  24765. return vertexData;
  24766. };
  24767. VertexData.CreatePlane = function (options) {
  24768. var indices = [];
  24769. var positions = [];
  24770. var normals = [];
  24771. var uvs = [];
  24772. var width = options.width || options.size || 1;
  24773. var height = options.height || options.size || 1;
  24774. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24775. // Vertices
  24776. var halfWidth = width / 2.0;
  24777. var halfHeight = height / 2.0;
  24778. positions.push(-halfWidth, -halfHeight, 0);
  24779. normals.push(0, 0, -1.0);
  24780. uvs.push(0.0, 0.0);
  24781. positions.push(halfWidth, -halfHeight, 0);
  24782. normals.push(0, 0, -1.0);
  24783. uvs.push(1.0, 0.0);
  24784. positions.push(halfWidth, halfHeight, 0);
  24785. normals.push(0, 0, -1.0);
  24786. uvs.push(1.0, 1.0);
  24787. positions.push(-halfWidth, halfHeight, 0);
  24788. normals.push(0, 0, -1.0);
  24789. uvs.push(0.0, 1.0);
  24790. // Indices
  24791. indices.push(0);
  24792. indices.push(1);
  24793. indices.push(2);
  24794. indices.push(0);
  24795. indices.push(2);
  24796. indices.push(3);
  24797. // Sides
  24798. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24799. // Result
  24800. var vertexData = new VertexData();
  24801. vertexData.indices = indices;
  24802. vertexData.positions = positions;
  24803. vertexData.normals = normals;
  24804. vertexData.uvs = uvs;
  24805. return vertexData;
  24806. };
  24807. VertexData.CreateDisc = function (options) {
  24808. var positions = [];
  24809. var indices = [];
  24810. var normals = [];
  24811. var uvs = [];
  24812. var radius = options.radius || 0.5;
  24813. var tessellation = options.tessellation || 64;
  24814. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24815. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24816. // positions and uvs
  24817. positions.push(0, 0, 0); // disc center first
  24818. uvs.push(0.5, 0.5);
  24819. var theta = Math.PI * 2 * arc;
  24820. var step = theta / tessellation;
  24821. for (var a = 0; a < theta; a += step) {
  24822. var x = Math.cos(a);
  24823. var y = Math.sin(a);
  24824. var u = (x + 1) / 2;
  24825. var v = (1 - y) / 2;
  24826. positions.push(radius * x, radius * y, 0);
  24827. uvs.push(u, v);
  24828. }
  24829. if (arc === 1) {
  24830. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24831. uvs.push(uvs[2], uvs[3]);
  24832. }
  24833. //indices
  24834. var vertexNb = positions.length / 3;
  24835. for (var i = 1; i < vertexNb - 1; i++) {
  24836. indices.push(i + 1, 0, i);
  24837. }
  24838. // result
  24839. VertexData.ComputeNormals(positions, indices, normals);
  24840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24841. var vertexData = new VertexData();
  24842. vertexData.indices = indices;
  24843. vertexData.positions = positions;
  24844. vertexData.normals = normals;
  24845. vertexData.uvs = uvs;
  24846. return vertexData;
  24847. };
  24848. VertexData.CreateIcoSphere = function (options) {
  24849. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24850. var radius = options.radius || 1;
  24851. var flat = (options.flat === undefined) ? true : options.flat;
  24852. var subdivisions = options.subdivisions || 4;
  24853. var radiusX = options.radiusX || radius;
  24854. var radiusY = options.radiusY || radius;
  24855. var radiusZ = options.radiusZ || radius;
  24856. var t = (1 + Math.sqrt(5)) / 2;
  24857. // 12 vertex x,y,z
  24858. var ico_vertices = [
  24859. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24860. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24861. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24862. ];
  24863. // index of 3 vertex makes a face of icopshere
  24864. var ico_indices = [
  24865. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24866. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24867. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24868. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24869. ];
  24870. // vertex for uv have aliased position, not for UV
  24871. var vertices_unalias_id = [
  24872. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24873. // vertex alias
  24874. 0,
  24875. 2,
  24876. 3,
  24877. 3,
  24878. 3,
  24879. 4,
  24880. 7,
  24881. 8,
  24882. 9,
  24883. 9,
  24884. 10,
  24885. 11 // 23: B + 12
  24886. ];
  24887. // uv as integer step (not pixels !)
  24888. var ico_vertexuv = [
  24889. 5, 1, 3, 1, 6, 4, 0, 0,
  24890. 5, 3, 4, 2, 2, 2, 4, 0,
  24891. 2, 0, 1, 1, 6, 0, 6, 2,
  24892. // vertex alias (for same vertex on different faces)
  24893. 0, 4,
  24894. 3, 3,
  24895. 4, 4,
  24896. 3, 1,
  24897. 4, 2,
  24898. 4, 4,
  24899. 0, 2,
  24900. 1, 1,
  24901. 2, 2,
  24902. 3, 3,
  24903. 1, 3,
  24904. 2, 4 // 23: B + 12
  24905. ];
  24906. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24907. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24908. // First island of uv mapping
  24909. // v = 4h 3+ 2
  24910. // v = 3h 9+ 4
  24911. // v = 2h 9+ 5 B
  24912. // v = 1h 9 1 0
  24913. // v = 0h 3 8 7 A
  24914. // u = 0 1 2 3 4 5 6 *a
  24915. // Second island of uv mapping
  24916. // v = 4h 0+ B+ 4+
  24917. // v = 3h A+ 2+
  24918. // v = 2h 7+ 6 3+
  24919. // v = 1h 8+ 3+
  24920. // v = 0h
  24921. // u = 0 1 2 3 4 5 6 *a
  24922. // Face layout on texture UV mapping
  24923. // ============
  24924. // \ 4 /\ 16 / ======
  24925. // \ / \ / /\ 11 /
  24926. // \/ 7 \/ / \ /
  24927. // ======= / 10 \/
  24928. // /\ 17 /\ =======
  24929. // / \ / \ \ 15 /\
  24930. // / 8 \/ 12 \ \ / \
  24931. // ============ \/ 6 \
  24932. // \ 18 /\ ============
  24933. // \ / \ \ 5 /\ 0 /
  24934. // \/ 13 \ \ / \ /
  24935. // ======= \/ 1 \/
  24936. // =============
  24937. // /\ 19 /\ 2 /\
  24938. // / \ / \ / \
  24939. // / 14 \/ 9 \/ 3 \
  24940. // ===================
  24941. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24942. var ustep = 138 / 1024;
  24943. var vstep = 239 / 1024;
  24944. var uoffset = 60 / 1024;
  24945. var voffset = 26 / 1024;
  24946. // Second island should have margin, not to touch the first island
  24947. // avoid any borderline artefact in pixel rounding
  24948. var island_u_offset = -40 / 1024;
  24949. var island_v_offset = +20 / 1024;
  24950. // face is either island 0 or 1 :
  24951. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24952. var island = [
  24953. 0, 0, 0, 0, 1,
  24954. 0, 0, 1, 1, 0,
  24955. 0, 0, 1, 1, 0,
  24956. 0, 1, 1, 1, 0 // 15 - 19
  24957. ];
  24958. var indices = [];
  24959. var positions = [];
  24960. var normals = [];
  24961. var uvs = [];
  24962. var current_indice = 0;
  24963. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24964. var face_vertex_pos = new Array(3);
  24965. var face_vertex_uv = new Array(3);
  24966. var v012;
  24967. for (v012 = 0; v012 < 3; v012++) {
  24968. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24969. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24970. }
  24971. // create all with normals
  24972. for (var face = 0; face < 20; face++) {
  24973. // 3 vertex per face
  24974. for (v012 = 0; v012 < 3; v012++) {
  24975. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24976. var v_id = ico_indices[3 * face + v012];
  24977. // vertex have 3D position (x,y,z)
  24978. 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]);
  24979. // Normalize to get normal, then scale to radius
  24980. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24981. // uv Coordinates from vertex ID
  24982. 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);
  24983. }
  24984. // Subdivide the face (interpolate pos, norm, uv)
  24985. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24986. // - norm is linear interpolation of vertex corner normal
  24987. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24988. // - uv is linear interpolation
  24989. //
  24990. // Topology is as below for sub-divide by 2
  24991. // vertex shown as v0,v1,v2
  24992. // interp index is i1 to progress in range [v0,v1[
  24993. // interp index is i2 to progress in range [v0,v2[
  24994. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24995. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24996. //
  24997. //
  24998. // i2 v2
  24999. // ^ ^
  25000. // / / \
  25001. // / / \
  25002. // / / \
  25003. // / / (0,1) \
  25004. // / #---------\
  25005. // / / \ (0,0)'/ \
  25006. // / / \ / \
  25007. // / / \ / \
  25008. // / / (0,0) \ / (1,0) \
  25009. // / #---------#---------\
  25010. // v0 v1
  25011. //
  25012. // --------------------> i1
  25013. //
  25014. // interp of (i1,i2):
  25015. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25016. // along i1 : lerp(x0,x1, i1/(S-i2))
  25017. //
  25018. // centroid of triangle is needed to get help normal computation
  25019. // (c1,c2) are used for centroid location
  25020. var interp_vertex = function (i1, i2, c1, c2) {
  25021. // vertex is interpolated from
  25022. // - face_vertex_pos[0..2]
  25023. // - face_vertex_uv[0..2]
  25024. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25025. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25026. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25027. pos_interp.normalize();
  25028. var vertex_normal;
  25029. if (flat) {
  25030. // in flat mode, recalculate normal as face centroid normal
  25031. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25032. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25033. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25034. }
  25035. else {
  25036. // in smooth mode, recalculate normal from each single vertex position
  25037. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25038. }
  25039. // Vertex normal need correction due to X,Y,Z radius scaling
  25040. vertex_normal.x /= radiusX;
  25041. vertex_normal.y /= radiusY;
  25042. vertex_normal.z /= radiusZ;
  25043. vertex_normal.normalize();
  25044. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25045. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25046. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25047. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25048. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25049. uvs.push(uv_interp.x, uv_interp.y);
  25050. // push each vertex has member of a face
  25051. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25052. indices.push(current_indice);
  25053. current_indice++;
  25054. };
  25055. for (var i2 = 0; i2 < subdivisions; i2++) {
  25056. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25057. // face : (i1,i2) for /\ :
  25058. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25059. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25060. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25061. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25062. if (i1 + i2 + 1 < subdivisions) {
  25063. // face : (i1,i2)' for \/ :
  25064. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25065. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25066. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25067. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25068. }
  25069. }
  25070. }
  25071. }
  25072. // Sides
  25073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25074. // Result
  25075. var vertexData = new VertexData();
  25076. vertexData.indices = indices;
  25077. vertexData.positions = positions;
  25078. vertexData.normals = normals;
  25079. vertexData.uvs = uvs;
  25080. return vertexData;
  25081. };
  25082. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25083. VertexData.CreatePolyhedron = function (options) {
  25084. // provided polyhedron types :
  25085. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25086. // 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)
  25087. var polyhedra = [];
  25088. 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]] };
  25089. 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]] };
  25090. polyhedra[2] = {
  25091. 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]],
  25092. 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]]
  25093. };
  25094. polyhedra[3] = {
  25095. 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]],
  25096. 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]]
  25097. };
  25098. polyhedra[4] = {
  25099. 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]],
  25100. 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]]
  25101. };
  25102. 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]] };
  25103. 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]] };
  25104. 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]] };
  25105. 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]] };
  25106. 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]] };
  25107. 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]] };
  25108. 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]] };
  25109. 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]] };
  25110. 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]] };
  25111. polyhedra[14] = {
  25112. 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]],
  25113. 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]]
  25114. };
  25115. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25116. var size = options.size;
  25117. var sizeX = options.sizeX || size || 1;
  25118. var sizeY = options.sizeY || size || 1;
  25119. var sizeZ = options.sizeZ || size || 1;
  25120. var data = options.custom || polyhedra[type];
  25121. var nbfaces = data.face.length;
  25122. var faceUV = options.faceUV || new Array(nbfaces);
  25123. var faceColors = options.faceColors;
  25124. var flat = (options.flat === undefined) ? true : options.flat;
  25125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25126. var positions = [];
  25127. var indices = [];
  25128. var normals = [];
  25129. var uvs = [];
  25130. var colors = [];
  25131. var index = 0;
  25132. var faceIdx = 0; // face cursor in the array "indexes"
  25133. var indexes = [];
  25134. var i = 0;
  25135. var f = 0;
  25136. var u, v, ang, x, y, tmp;
  25137. // default face colors and UV if undefined
  25138. if (flat) {
  25139. for (f = 0; f < nbfaces; f++) {
  25140. if (faceColors && faceColors[f] === undefined) {
  25141. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25142. }
  25143. if (faceUV && faceUV[f] === undefined) {
  25144. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25145. }
  25146. }
  25147. }
  25148. if (!flat) {
  25149. for (i = 0; i < data.vertex.length; i++) {
  25150. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25151. uvs.push(0, 0);
  25152. }
  25153. for (f = 0; f < nbfaces; f++) {
  25154. for (i = 0; i < data.face[f].length - 2; i++) {
  25155. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25156. }
  25157. }
  25158. }
  25159. else {
  25160. for (f = 0; f < nbfaces; f++) {
  25161. var fl = data.face[f].length; // number of vertices of the current face
  25162. ang = 2 * Math.PI / fl;
  25163. x = 0.5 * Math.tan(ang / 2);
  25164. y = 0.5;
  25165. // positions, uvs, colors
  25166. for (i = 0; i < fl; i++) {
  25167. // positions
  25168. 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);
  25169. indexes.push(index);
  25170. index++;
  25171. // uvs
  25172. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25173. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25174. uvs.push(u, v);
  25175. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25176. y = x * Math.sin(ang) + y * Math.cos(ang);
  25177. x = tmp;
  25178. // colors
  25179. if (faceColors) {
  25180. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25181. }
  25182. }
  25183. // indices from indexes
  25184. for (i = 0; i < fl - 2; i++) {
  25185. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25186. }
  25187. faceIdx += fl;
  25188. }
  25189. }
  25190. VertexData.ComputeNormals(positions, indices, normals);
  25191. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25192. var vertexData = new VertexData();
  25193. vertexData.positions = positions;
  25194. vertexData.indices = indices;
  25195. vertexData.normals = normals;
  25196. vertexData.uvs = uvs;
  25197. if (faceColors && flat) {
  25198. vertexData.colors = colors;
  25199. }
  25200. return vertexData;
  25201. };
  25202. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25203. VertexData.CreateTorusKnot = function (options) {
  25204. var indices = [];
  25205. var positions = [];
  25206. var normals = [];
  25207. var uvs = [];
  25208. var radius = options.radius || 2;
  25209. var tube = options.tube || 0.5;
  25210. var radialSegments = options.radialSegments || 32;
  25211. var tubularSegments = options.tubularSegments || 32;
  25212. var p = options.p || 2;
  25213. var q = options.q || 3;
  25214. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25215. // Helper
  25216. var getPos = function (angle) {
  25217. var cu = Math.cos(angle);
  25218. var su = Math.sin(angle);
  25219. var quOverP = q / p * angle;
  25220. var cs = Math.cos(quOverP);
  25221. var tx = radius * (2 + cs) * 0.5 * cu;
  25222. var ty = radius * (2 + cs) * su * 0.5;
  25223. var tz = radius * Math.sin(quOverP) * 0.5;
  25224. return new BABYLON.Vector3(tx, ty, tz);
  25225. };
  25226. // Vertices
  25227. var i;
  25228. var j;
  25229. for (i = 0; i <= radialSegments; i++) {
  25230. var modI = i % radialSegments;
  25231. var u = modI / radialSegments * 2 * p * Math.PI;
  25232. var p1 = getPos(u);
  25233. var p2 = getPos(u + 0.01);
  25234. var tang = p2.subtract(p1);
  25235. var n = p2.add(p1);
  25236. var bitan = BABYLON.Vector3.Cross(tang, n);
  25237. n = BABYLON.Vector3.Cross(bitan, tang);
  25238. bitan.normalize();
  25239. n.normalize();
  25240. for (j = 0; j < tubularSegments; j++) {
  25241. var modJ = j % tubularSegments;
  25242. var v = modJ / tubularSegments * 2 * Math.PI;
  25243. var cx = -tube * Math.cos(v);
  25244. var cy = tube * Math.sin(v);
  25245. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25246. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25247. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25248. uvs.push(i / radialSegments);
  25249. uvs.push(j / tubularSegments);
  25250. }
  25251. }
  25252. for (i = 0; i < radialSegments; i++) {
  25253. for (j = 0; j < tubularSegments; j++) {
  25254. var jNext = (j + 1) % tubularSegments;
  25255. var a = i * tubularSegments + j;
  25256. var b = (i + 1) * tubularSegments + j;
  25257. var c = (i + 1) * tubularSegments + jNext;
  25258. var d = i * tubularSegments + jNext;
  25259. indices.push(d);
  25260. indices.push(b);
  25261. indices.push(a);
  25262. indices.push(d);
  25263. indices.push(c);
  25264. indices.push(b);
  25265. }
  25266. }
  25267. // Normals
  25268. VertexData.ComputeNormals(positions, indices, normals);
  25269. // Sides
  25270. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25271. // Result
  25272. var vertexData = new VertexData();
  25273. vertexData.indices = indices;
  25274. vertexData.positions = positions;
  25275. vertexData.normals = normals;
  25276. vertexData.uvs = uvs;
  25277. return vertexData;
  25278. };
  25279. // Tools
  25280. /**
  25281. * @param {any} - positions (number[] or Float32Array)
  25282. * @param {any} - indices (number[] or Uint16Array)
  25283. * @param {any} - normals (number[] or Float32Array)
  25284. */
  25285. VertexData.ComputeNormals = function (positions, indices, normals) {
  25286. var index = 0;
  25287. var p1p2x = 0.0;
  25288. var p1p2y = 0.0;
  25289. var p1p2z = 0.0;
  25290. var p3p2x = 0.0;
  25291. var p3p2y = 0.0;
  25292. var p3p2z = 0.0;
  25293. var faceNormalx = 0.0;
  25294. var faceNormaly = 0.0;
  25295. var faceNormalz = 0.0;
  25296. var length = 0.0;
  25297. var i1 = 0;
  25298. var i2 = 0;
  25299. var i3 = 0;
  25300. for (index = 0; index < positions.length; index++) {
  25301. normals[index] = 0.0;
  25302. }
  25303. // indice triplet = 1 face
  25304. var nbFaces = indices.length / 3;
  25305. for (index = 0; index < nbFaces; index++) {
  25306. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25307. i2 = indices[index * 3 + 1];
  25308. i3 = indices[index * 3 + 2];
  25309. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25310. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25311. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25312. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25313. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25314. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25315. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25316. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25317. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25318. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25319. length = (length === 0) ? 1.0 : length;
  25320. faceNormalx /= length; // normalize this normal
  25321. faceNormaly /= length;
  25322. faceNormalz /= length;
  25323. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25324. normals[i1 * 3 + 1] += faceNormaly;
  25325. normals[i1 * 3 + 2] += faceNormalz;
  25326. normals[i2 * 3] += faceNormalx;
  25327. normals[i2 * 3 + 1] += faceNormaly;
  25328. normals[i2 * 3 + 2] += faceNormalz;
  25329. normals[i3 * 3] += faceNormalx;
  25330. normals[i3 * 3 + 1] += faceNormaly;
  25331. normals[i3 * 3 + 2] += faceNormalz;
  25332. }
  25333. // last normalization of each normal
  25334. for (index = 0; index < normals.length / 3; index++) {
  25335. faceNormalx = normals[index * 3];
  25336. faceNormaly = normals[index * 3 + 1];
  25337. faceNormalz = normals[index * 3 + 2];
  25338. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25339. length = (length === 0) ? 1.0 : length;
  25340. faceNormalx /= length;
  25341. faceNormaly /= length;
  25342. faceNormalz /= length;
  25343. normals[index * 3] = faceNormalx;
  25344. normals[index * 3 + 1] = faceNormaly;
  25345. normals[index * 3 + 2] = faceNormalz;
  25346. }
  25347. };
  25348. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25349. var li = indices.length;
  25350. var ln = normals.length;
  25351. var i;
  25352. var n;
  25353. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25354. switch (sideOrientation) {
  25355. case BABYLON.Mesh.FRONTSIDE:
  25356. // nothing changed
  25357. break;
  25358. case BABYLON.Mesh.BACKSIDE:
  25359. var tmp;
  25360. // indices
  25361. for (i = 0; i < li; i += 3) {
  25362. tmp = indices[i];
  25363. indices[i] = indices[i + 2];
  25364. indices[i + 2] = tmp;
  25365. }
  25366. // normals
  25367. for (n = 0; n < ln; n++) {
  25368. normals[n] = -normals[n];
  25369. }
  25370. break;
  25371. case BABYLON.Mesh.DOUBLESIDE:
  25372. // positions
  25373. var lp = positions.length;
  25374. var l = lp / 3;
  25375. for (var p = 0; p < lp; p++) {
  25376. positions[lp + p] = positions[p];
  25377. }
  25378. // indices
  25379. for (i = 0; i < li; i += 3) {
  25380. indices[i + li] = indices[i + 2] + l;
  25381. indices[i + 1 + li] = indices[i + 1] + l;
  25382. indices[i + 2 + li] = indices[i] + l;
  25383. }
  25384. // normals
  25385. for (n = 0; n < ln; n++) {
  25386. normals[ln + n] = -normals[n];
  25387. }
  25388. // uvs
  25389. var lu = uvs.length;
  25390. for (var u = 0; u < lu; u++) {
  25391. uvs[u + lu] = uvs[u];
  25392. }
  25393. break;
  25394. }
  25395. };
  25396. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25397. var vertexData = new VertexData();
  25398. // positions
  25399. var positions = parsedVertexData.positions;
  25400. if (positions) {
  25401. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25402. }
  25403. // normals
  25404. var normals = parsedVertexData.normals;
  25405. if (normals) {
  25406. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25407. }
  25408. // uvs
  25409. var uvs = parsedVertexData.uvs;
  25410. if (uvs) {
  25411. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25412. }
  25413. // uv2s
  25414. var uv2s = parsedVertexData.uv2s;
  25415. if (uv2s) {
  25416. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25417. }
  25418. // uv3s
  25419. var uv3s = parsedVertexData.uv3s;
  25420. if (uv3s) {
  25421. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25422. }
  25423. // uv4s
  25424. var uv4s = parsedVertexData.uv4s;
  25425. if (uv4s) {
  25426. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25427. }
  25428. // uv5s
  25429. var uv5s = parsedVertexData.uv5s;
  25430. if (uv5s) {
  25431. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25432. }
  25433. // uv6s
  25434. var uv6s = parsedVertexData.uv6s;
  25435. if (uv6s) {
  25436. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25437. }
  25438. // colors
  25439. var colors = parsedVertexData.colors;
  25440. if (colors) {
  25441. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25442. }
  25443. // matricesIndices
  25444. var matricesIndices = parsedVertexData.matricesIndices;
  25445. if (matricesIndices) {
  25446. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25447. }
  25448. // matricesWeights
  25449. var matricesWeights = parsedVertexData.matricesWeights;
  25450. if (matricesWeights) {
  25451. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25452. }
  25453. // indices
  25454. var indices = parsedVertexData.indices;
  25455. if (indices) {
  25456. vertexData.indices = indices;
  25457. }
  25458. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25459. };
  25460. return VertexData;
  25461. })();
  25462. BABYLON.VertexData = VertexData;
  25463. })(BABYLON || (BABYLON = {}));
  25464. var BABYLON;
  25465. (function (BABYLON) {
  25466. var Tags = (function () {
  25467. function Tags() {
  25468. }
  25469. Tags.EnableFor = function (obj) {
  25470. obj._tags = obj._tags || {};
  25471. obj.hasTags = function () {
  25472. return Tags.HasTags(obj);
  25473. };
  25474. obj.addTags = function (tagsString) {
  25475. return Tags.AddTagsTo(obj, tagsString);
  25476. };
  25477. obj.removeTags = function (tagsString) {
  25478. return Tags.RemoveTagsFrom(obj, tagsString);
  25479. };
  25480. obj.matchesTagsQuery = function (tagsQuery) {
  25481. return Tags.MatchesQuery(obj, tagsQuery);
  25482. };
  25483. };
  25484. Tags.DisableFor = function (obj) {
  25485. delete obj._tags;
  25486. delete obj.hasTags;
  25487. delete obj.addTags;
  25488. delete obj.removeTags;
  25489. delete obj.matchesTagsQuery;
  25490. };
  25491. Tags.HasTags = function (obj) {
  25492. if (!obj._tags) {
  25493. return false;
  25494. }
  25495. return !BABYLON.Tools.IsEmpty(obj._tags);
  25496. };
  25497. Tags.GetTags = function (obj, asString) {
  25498. if (asString === void 0) { asString = true; }
  25499. if (!obj._tags) {
  25500. return null;
  25501. }
  25502. if (asString) {
  25503. var tagsArray = [];
  25504. for (var tag in obj._tags) {
  25505. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25506. tagsArray.push(tag);
  25507. }
  25508. }
  25509. return tagsArray.join(" ");
  25510. }
  25511. else {
  25512. return obj._tags;
  25513. }
  25514. };
  25515. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25516. // a tag cannot start with '||', '&&', and '!'
  25517. // it cannot contain whitespaces
  25518. Tags.AddTagsTo = function (obj, tagsString) {
  25519. if (!tagsString) {
  25520. return;
  25521. }
  25522. if (typeof tagsString !== "string") {
  25523. return;
  25524. }
  25525. var tags = tagsString.split(" ");
  25526. for (var t in tags) {
  25527. Tags._AddTagTo(obj, tags[t]);
  25528. }
  25529. };
  25530. Tags._AddTagTo = function (obj, tag) {
  25531. tag = tag.trim();
  25532. if (tag === "" || tag === "true" || tag === "false") {
  25533. return;
  25534. }
  25535. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25536. return;
  25537. }
  25538. Tags.EnableFor(obj);
  25539. obj._tags[tag] = true;
  25540. };
  25541. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25542. if (!Tags.HasTags(obj)) {
  25543. return;
  25544. }
  25545. var tags = tagsString.split(" ");
  25546. for (var t in tags) {
  25547. Tags._RemoveTagFrom(obj, tags[t]);
  25548. }
  25549. };
  25550. Tags._RemoveTagFrom = function (obj, tag) {
  25551. delete obj._tags[tag];
  25552. };
  25553. Tags.MatchesQuery = function (obj, tagsQuery) {
  25554. if (tagsQuery === undefined) {
  25555. return true;
  25556. }
  25557. if (tagsQuery === "") {
  25558. return Tags.HasTags(obj);
  25559. }
  25560. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25561. };
  25562. return Tags;
  25563. })();
  25564. BABYLON.Tags = Tags;
  25565. })(BABYLON || (BABYLON = {}));
  25566. var BABYLON;
  25567. (function (BABYLON) {
  25568. var Internals;
  25569. (function (Internals) {
  25570. var AndOrNotEvaluator = (function () {
  25571. function AndOrNotEvaluator() {
  25572. }
  25573. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25574. if (!query.match(/\([^\(\)]*\)/g)) {
  25575. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25576. }
  25577. else {
  25578. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25579. // remove parenthesis
  25580. r = r.slice(1, r.length - 1);
  25581. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25582. });
  25583. }
  25584. if (query === "true") {
  25585. return true;
  25586. }
  25587. if (query === "false") {
  25588. return false;
  25589. }
  25590. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25591. };
  25592. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25593. evaluateCallback = evaluateCallback || (function (r) {
  25594. return r === "true" ? true : false;
  25595. });
  25596. var result;
  25597. var or = parenthesisContent.split("||");
  25598. for (var i in or) {
  25599. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25600. var and = ori.split("&&");
  25601. if (and.length > 1) {
  25602. for (var j = 0; j < and.length; ++j) {
  25603. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25604. if (andj !== "true" && andj !== "false") {
  25605. if (andj[0] === "!") {
  25606. result = !evaluateCallback(andj.substring(1));
  25607. }
  25608. else {
  25609. result = evaluateCallback(andj);
  25610. }
  25611. }
  25612. else {
  25613. result = andj === "true" ? true : false;
  25614. }
  25615. if (!result) {
  25616. ori = "false";
  25617. break;
  25618. }
  25619. }
  25620. }
  25621. if (result || ori === "true") {
  25622. result = true;
  25623. break;
  25624. }
  25625. // result equals false (or undefined)
  25626. if (ori !== "true" && ori !== "false") {
  25627. if (ori[0] === "!") {
  25628. result = !evaluateCallback(ori.substring(1));
  25629. }
  25630. else {
  25631. result = evaluateCallback(ori);
  25632. }
  25633. }
  25634. else {
  25635. result = ori === "true" ? true : false;
  25636. }
  25637. }
  25638. // the whole parenthesis scope is replaced by 'true' or 'false'
  25639. return result ? "true" : "false";
  25640. };
  25641. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25642. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25643. // remove whitespaces
  25644. r = r.replace(/[\s]/g, function () { return ""; });
  25645. return r.length % 2 ? "!" : "";
  25646. });
  25647. booleanString = booleanString.trim();
  25648. if (booleanString === "!true") {
  25649. booleanString = "false";
  25650. }
  25651. else if (booleanString === "!false") {
  25652. booleanString = "true";
  25653. }
  25654. return booleanString;
  25655. };
  25656. return AndOrNotEvaluator;
  25657. })();
  25658. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25659. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25660. })(BABYLON || (BABYLON = {}));
  25661. var BABYLON;
  25662. (function (BABYLON) {
  25663. var PostProcessRenderPass = (function () {
  25664. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25665. this._enabled = true;
  25666. this._refCount = 0;
  25667. this._name = name;
  25668. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25669. this.setRenderList(renderList);
  25670. this._renderTexture.onBeforeRender = beforeRender;
  25671. this._renderTexture.onAfterRender = afterRender;
  25672. this._scene = scene;
  25673. this._renderList = renderList;
  25674. }
  25675. // private
  25676. PostProcessRenderPass.prototype._incRefCount = function () {
  25677. if (this._refCount === 0) {
  25678. this._scene.customRenderTargets.push(this._renderTexture);
  25679. }
  25680. return ++this._refCount;
  25681. };
  25682. PostProcessRenderPass.prototype._decRefCount = function () {
  25683. this._refCount--;
  25684. if (this._refCount <= 0) {
  25685. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25686. }
  25687. return this._refCount;
  25688. };
  25689. PostProcessRenderPass.prototype._update = function () {
  25690. this.setRenderList(this._renderList);
  25691. };
  25692. // public
  25693. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25694. this._renderTexture.renderList = renderList;
  25695. };
  25696. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25697. return this._renderTexture;
  25698. };
  25699. return PostProcessRenderPass;
  25700. })();
  25701. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25702. })(BABYLON || (BABYLON = {}));
  25703. var BABYLON;
  25704. (function (BABYLON) {
  25705. var PostProcessRenderEffect = (function () {
  25706. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25707. this._engine = engine;
  25708. this._name = name;
  25709. this._singleInstance = singleInstance || true;
  25710. this._getPostProcess = getPostProcess;
  25711. this._cameras = [];
  25712. this._indicesForCamera = [];
  25713. this._postProcesses = {};
  25714. this._renderPasses = {};
  25715. this._renderEffectAsPasses = {};
  25716. }
  25717. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25718. get: function () {
  25719. for (var index in this._postProcesses) {
  25720. if (!this._postProcesses[index].isSupported) {
  25721. return false;
  25722. }
  25723. }
  25724. return true;
  25725. },
  25726. enumerable: true,
  25727. configurable: true
  25728. });
  25729. PostProcessRenderEffect.prototype._update = function () {
  25730. for (var renderPassName in this._renderPasses) {
  25731. this._renderPasses[renderPassName]._update();
  25732. }
  25733. };
  25734. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25735. this._renderPasses[renderPass._name] = renderPass;
  25736. this._linkParameters();
  25737. };
  25738. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25739. delete this._renderPasses[renderPass._name];
  25740. this._linkParameters();
  25741. };
  25742. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25743. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25744. this._linkParameters();
  25745. };
  25746. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25747. for (var renderPassName in this._renderPasses) {
  25748. if (renderPassName === passName) {
  25749. return this._renderPasses[passName];
  25750. }
  25751. }
  25752. };
  25753. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25754. this._renderPasses = {};
  25755. this._linkParameters();
  25756. };
  25757. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25758. var cameraKey;
  25759. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25760. for (var i = 0; i < _cam.length; i++) {
  25761. var camera = _cam[i];
  25762. var cameraName = camera.name;
  25763. if (this._singleInstance) {
  25764. cameraKey = 0;
  25765. }
  25766. else {
  25767. cameraKey = cameraName;
  25768. }
  25769. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25770. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25771. if (!this._indicesForCamera[cameraName]) {
  25772. this._indicesForCamera[cameraName] = [];
  25773. }
  25774. this._indicesForCamera[cameraName].push(index);
  25775. if (this._cameras.indexOf(camera) === -1) {
  25776. this._cameras[cameraName] = camera;
  25777. }
  25778. for (var passName in this._renderPasses) {
  25779. this._renderPasses[passName]._incRefCount();
  25780. }
  25781. }
  25782. this._linkParameters();
  25783. };
  25784. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25785. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25786. for (var i = 0; i < _cam.length; i++) {
  25787. var camera = _cam[i];
  25788. var cameraName = camera.name;
  25789. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25790. var index = this._cameras.indexOf(cameraName);
  25791. this._indicesForCamera.splice(index, 1);
  25792. this._cameras.splice(index, 1);
  25793. for (var passName in this._renderPasses) {
  25794. this._renderPasses[passName]._decRefCount();
  25795. }
  25796. }
  25797. };
  25798. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25799. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25800. for (var i = 0; i < _cam.length; i++) {
  25801. var camera = _cam[i];
  25802. var cameraName = camera.name;
  25803. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25804. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25805. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25806. }
  25807. }
  25808. for (var passName in this._renderPasses) {
  25809. this._renderPasses[passName]._incRefCount();
  25810. }
  25811. }
  25812. };
  25813. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25814. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25815. for (var i = 0; i < _cam.length; i++) {
  25816. var camera = _cam[i];
  25817. var cameraName = camera.Name;
  25818. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25819. for (var passName in this._renderPasses) {
  25820. this._renderPasses[passName]._decRefCount();
  25821. }
  25822. }
  25823. };
  25824. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25825. if (this._singleInstance) {
  25826. return this._postProcesses[0];
  25827. }
  25828. else {
  25829. return this._postProcesses[camera.name];
  25830. }
  25831. };
  25832. PostProcessRenderEffect.prototype._linkParameters = function () {
  25833. var _this = this;
  25834. for (var index in this._postProcesses) {
  25835. if (this.applyParameters) {
  25836. this.applyParameters(this._postProcesses[index]);
  25837. }
  25838. this._postProcesses[index].onBeforeRender = function (effect) {
  25839. _this._linkTextures(effect);
  25840. };
  25841. }
  25842. };
  25843. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25844. for (var renderPassName in this._renderPasses) {
  25845. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25846. }
  25847. for (var renderEffectName in this._renderEffectAsPasses) {
  25848. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25849. }
  25850. };
  25851. return PostProcessRenderEffect;
  25852. })();
  25853. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25854. })(BABYLON || (BABYLON = {}));
  25855. var BABYLON;
  25856. (function (BABYLON) {
  25857. var PostProcessRenderPipeline = (function () {
  25858. function PostProcessRenderPipeline(engine, name) {
  25859. this._engine = engine;
  25860. this._name = name;
  25861. this._renderEffects = {};
  25862. this._renderEffectsForIsolatedPass = {};
  25863. this._cameras = [];
  25864. }
  25865. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25866. get: function () {
  25867. for (var renderEffectName in this._renderEffects) {
  25868. if (!this._renderEffects[renderEffectName].isSupported) {
  25869. return false;
  25870. }
  25871. }
  25872. return true;
  25873. },
  25874. enumerable: true,
  25875. configurable: true
  25876. });
  25877. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25878. this._renderEffects[renderEffect._name] = renderEffect;
  25879. };
  25880. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25881. var renderEffects = this._renderEffects[renderEffectName];
  25882. if (!renderEffects) {
  25883. return;
  25884. }
  25885. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25886. };
  25887. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25888. var renderEffects = this._renderEffects[renderEffectName];
  25889. if (!renderEffects) {
  25890. return;
  25891. }
  25892. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25893. };
  25894. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25895. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25896. var indicesToDelete = [];
  25897. var i;
  25898. for (i = 0; i < _cam.length; i++) {
  25899. var camera = _cam[i];
  25900. var cameraName = camera.name;
  25901. if (this._cameras.indexOf(camera) === -1) {
  25902. this._cameras[cameraName] = camera;
  25903. }
  25904. else if (unique) {
  25905. indicesToDelete.push(i);
  25906. }
  25907. }
  25908. for (i = 0; i < indicesToDelete.length; i++) {
  25909. cameras.splice(indicesToDelete[i], 1);
  25910. }
  25911. for (var renderEffectName in this._renderEffects) {
  25912. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25913. }
  25914. };
  25915. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25916. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25917. for (var renderEffectName in this._renderEffects) {
  25918. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25919. }
  25920. for (var i = 0; i < _cam.length; i++) {
  25921. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25922. }
  25923. };
  25924. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25925. var _this = this;
  25926. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25927. var pass = null;
  25928. var renderEffectName;
  25929. for (renderEffectName in this._renderEffects) {
  25930. pass = this._renderEffects[renderEffectName].getPass(passName);
  25931. if (pass != null) {
  25932. break;
  25933. }
  25934. }
  25935. if (pass === null) {
  25936. return;
  25937. }
  25938. for (renderEffectName in this._renderEffects) {
  25939. this._renderEffects[renderEffectName]._disable(_cam);
  25940. }
  25941. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25942. for (var i = 0; i < _cam.length; i++) {
  25943. var camera = _cam[i];
  25944. var cameraName = camera.name;
  25945. 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); });
  25946. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25947. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25948. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25949. }
  25950. };
  25951. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25952. var _this = this;
  25953. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25954. for (var i = 0; i < _cam.length; i++) {
  25955. var camera = _cam[i];
  25956. var cameraName = camera.name;
  25957. 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); });
  25958. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25959. }
  25960. for (var renderEffectName in this._renderEffects) {
  25961. this._renderEffects[renderEffectName]._enable(_cam);
  25962. }
  25963. };
  25964. PostProcessRenderPipeline.prototype._update = function () {
  25965. for (var renderEffectName in this._renderEffects) {
  25966. this._renderEffects[renderEffectName]._update();
  25967. }
  25968. for (var i = 0; i < this._cameras.length; i++) {
  25969. var cameraName = this._cameras[i].name;
  25970. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25971. this._renderEffectsForIsolatedPass[cameraName]._update();
  25972. }
  25973. }
  25974. };
  25975. PostProcessRenderPipeline.prototype.dispose = function () {
  25976. // Must be implemented by children
  25977. };
  25978. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25979. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25980. return PostProcessRenderPipeline;
  25981. })();
  25982. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25983. })(BABYLON || (BABYLON = {}));
  25984. var BABYLON;
  25985. (function (BABYLON) {
  25986. var PostProcessRenderPipelineManager = (function () {
  25987. function PostProcessRenderPipelineManager() {
  25988. this._renderPipelines = {};
  25989. }
  25990. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25991. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25992. };
  25993. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25994. var renderPipeline = this._renderPipelines[renderPipelineName];
  25995. if (!renderPipeline) {
  25996. return;
  25997. }
  25998. renderPipeline._attachCameras(cameras, unique);
  25999. };
  26000. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26001. var renderPipeline = this._renderPipelines[renderPipelineName];
  26002. if (!renderPipeline) {
  26003. return;
  26004. }
  26005. renderPipeline._detachCameras(cameras);
  26006. };
  26007. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26008. var renderPipeline = this._renderPipelines[renderPipelineName];
  26009. if (!renderPipeline) {
  26010. return;
  26011. }
  26012. renderPipeline._enableEffect(renderEffectName, cameras);
  26013. };
  26014. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26015. var renderPipeline = this._renderPipelines[renderPipelineName];
  26016. if (!renderPipeline) {
  26017. return;
  26018. }
  26019. renderPipeline._disableEffect(renderEffectName, cameras);
  26020. };
  26021. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26022. var renderPipeline = this._renderPipelines[renderPipelineName];
  26023. if (!renderPipeline) {
  26024. return;
  26025. }
  26026. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26027. };
  26028. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26029. var renderPipeline = this._renderPipelines[renderPipelineName];
  26030. if (!renderPipeline) {
  26031. return;
  26032. }
  26033. renderPipeline._disableDisplayOnlyPass(cameras);
  26034. };
  26035. PostProcessRenderPipelineManager.prototype.update = function () {
  26036. for (var renderPipelineName in this._renderPipelines) {
  26037. var pipeline = this._renderPipelines[renderPipelineName];
  26038. if (!pipeline.isSupported) {
  26039. pipeline.dispose();
  26040. delete this._renderPipelines[renderPipelineName];
  26041. }
  26042. else {
  26043. pipeline._update();
  26044. }
  26045. }
  26046. };
  26047. return PostProcessRenderPipelineManager;
  26048. })();
  26049. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26050. })(BABYLON || (BABYLON = {}));
  26051. var BABYLON;
  26052. (function (BABYLON) {
  26053. var BoundingBoxRenderer = (function () {
  26054. function BoundingBoxRenderer(scene) {
  26055. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26056. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26057. this.showBackLines = true;
  26058. this.renderList = new BABYLON.SmartArray(32);
  26059. this._scene = scene;
  26060. }
  26061. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26062. if (this._colorShader) {
  26063. return;
  26064. }
  26065. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26066. attributes: ["position"],
  26067. uniforms: ["worldViewProjection", "color"]
  26068. });
  26069. var engine = this._scene.getEngine();
  26070. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26071. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26072. 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]);
  26073. };
  26074. BoundingBoxRenderer.prototype.reset = function () {
  26075. this.renderList.reset();
  26076. };
  26077. BoundingBoxRenderer.prototype.render = function () {
  26078. if (this.renderList.length === 0) {
  26079. return;
  26080. }
  26081. this._prepareRessources();
  26082. if (!this._colorShader.isReady()) {
  26083. return;
  26084. }
  26085. var engine = this._scene.getEngine();
  26086. engine.setDepthWrite(false);
  26087. this._colorShader._preBind();
  26088. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26089. var boundingBox = this.renderList.data[boundingBoxIndex];
  26090. var min = boundingBox.minimum;
  26091. var max = boundingBox.maximum;
  26092. var diff = max.subtract(min);
  26093. var median = min.add(diff.scale(0.5));
  26094. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26095. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26096. .multiply(boundingBox.getWorldMatrix());
  26097. // VBOs
  26098. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26099. if (this.showBackLines) {
  26100. // Back
  26101. engine.setDepthFunctionToGreaterOrEqual();
  26102. this._scene.resetCachedMaterial();
  26103. this._colorShader.setColor4("color", this.backColor.toColor4());
  26104. this._colorShader.bind(worldMatrix);
  26105. // Draw order
  26106. engine.draw(false, 0, 24);
  26107. }
  26108. // Front
  26109. engine.setDepthFunctionToLess();
  26110. this._scene.resetCachedMaterial();
  26111. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26112. this._colorShader.bind(worldMatrix);
  26113. // Draw order
  26114. engine.draw(false, 0, 24);
  26115. }
  26116. this._colorShader.unbind();
  26117. engine.setDepthFunctionToLessOrEqual();
  26118. engine.setDepthWrite(true);
  26119. };
  26120. BoundingBoxRenderer.prototype.dispose = function () {
  26121. if (!this._colorShader) {
  26122. return;
  26123. }
  26124. this._colorShader.dispose();
  26125. this._vb.dispose();
  26126. this._scene.getEngine()._releaseBuffer(this._ib);
  26127. };
  26128. return BoundingBoxRenderer;
  26129. })();
  26130. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26131. })(BABYLON || (BABYLON = {}));
  26132. var BABYLON;
  26133. (function (BABYLON) {
  26134. var Condition = (function () {
  26135. function Condition(actionManager) {
  26136. this._actionManager = actionManager;
  26137. }
  26138. Condition.prototype.isValid = function () {
  26139. return true;
  26140. };
  26141. Condition.prototype._getProperty = function (propertyPath) {
  26142. return this._actionManager._getProperty(propertyPath);
  26143. };
  26144. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26145. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26146. };
  26147. return Condition;
  26148. })();
  26149. BABYLON.Condition = Condition;
  26150. var ValueCondition = (function (_super) {
  26151. __extends(ValueCondition, _super);
  26152. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26153. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26154. _super.call(this, actionManager);
  26155. this.propertyPath = propertyPath;
  26156. this.value = value;
  26157. this.operator = operator;
  26158. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26159. this._property = this._getProperty(this.propertyPath);
  26160. }
  26161. Object.defineProperty(ValueCondition, "IsEqual", {
  26162. get: function () {
  26163. return ValueCondition._IsEqual;
  26164. },
  26165. enumerable: true,
  26166. configurable: true
  26167. });
  26168. Object.defineProperty(ValueCondition, "IsDifferent", {
  26169. get: function () {
  26170. return ValueCondition._IsDifferent;
  26171. },
  26172. enumerable: true,
  26173. configurable: true
  26174. });
  26175. Object.defineProperty(ValueCondition, "IsGreater", {
  26176. get: function () {
  26177. return ValueCondition._IsGreater;
  26178. },
  26179. enumerable: true,
  26180. configurable: true
  26181. });
  26182. Object.defineProperty(ValueCondition, "IsLesser", {
  26183. get: function () {
  26184. return ValueCondition._IsLesser;
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. // Methods
  26190. ValueCondition.prototype.isValid = function () {
  26191. switch (this.operator) {
  26192. case ValueCondition.IsGreater:
  26193. return this._target[this._property] > this.value;
  26194. case ValueCondition.IsLesser:
  26195. return this._target[this._property] < this.value;
  26196. case ValueCondition.IsEqual:
  26197. case ValueCondition.IsDifferent:
  26198. var check;
  26199. if (this.value.equals) {
  26200. check = this.value.equals(this._target[this._property]);
  26201. }
  26202. else {
  26203. check = this.value === this._target[this._property];
  26204. }
  26205. return this.operator === ValueCondition.IsEqual ? check : !check;
  26206. }
  26207. return false;
  26208. };
  26209. // Statics
  26210. ValueCondition._IsEqual = 0;
  26211. ValueCondition._IsDifferent = 1;
  26212. ValueCondition._IsGreater = 2;
  26213. ValueCondition._IsLesser = 3;
  26214. return ValueCondition;
  26215. })(Condition);
  26216. BABYLON.ValueCondition = ValueCondition;
  26217. var PredicateCondition = (function (_super) {
  26218. __extends(PredicateCondition, _super);
  26219. function PredicateCondition(actionManager, predicate) {
  26220. _super.call(this, actionManager);
  26221. this.predicate = predicate;
  26222. }
  26223. PredicateCondition.prototype.isValid = function () {
  26224. return this.predicate();
  26225. };
  26226. return PredicateCondition;
  26227. })(Condition);
  26228. BABYLON.PredicateCondition = PredicateCondition;
  26229. var StateCondition = (function (_super) {
  26230. __extends(StateCondition, _super);
  26231. function StateCondition(actionManager, target, value) {
  26232. _super.call(this, actionManager);
  26233. this.value = value;
  26234. this._target = target;
  26235. }
  26236. // Methods
  26237. StateCondition.prototype.isValid = function () {
  26238. return this._target.state === this.value;
  26239. };
  26240. return StateCondition;
  26241. })(Condition);
  26242. BABYLON.StateCondition = StateCondition;
  26243. })(BABYLON || (BABYLON = {}));
  26244. var BABYLON;
  26245. (function (BABYLON) {
  26246. var Action = (function () {
  26247. function Action(triggerOptions, condition) {
  26248. this.triggerOptions = triggerOptions;
  26249. if (triggerOptions.parameter) {
  26250. this.trigger = triggerOptions.trigger;
  26251. this._triggerParameter = triggerOptions.parameter;
  26252. }
  26253. else {
  26254. this.trigger = triggerOptions;
  26255. }
  26256. this._nextActiveAction = this;
  26257. this._condition = condition;
  26258. }
  26259. // Methods
  26260. Action.prototype._prepare = function () {
  26261. };
  26262. Action.prototype.getTriggerParameter = function () {
  26263. return this._triggerParameter;
  26264. };
  26265. Action.prototype._executeCurrent = function (evt) {
  26266. if (this._nextActiveAction._condition) {
  26267. var condition = this._nextActiveAction._condition;
  26268. var currentRenderId = this._actionManager.getScene().getRenderId();
  26269. // We cache the current evaluation for the current frame
  26270. if (condition._evaluationId === currentRenderId) {
  26271. if (!condition._currentResult) {
  26272. return;
  26273. }
  26274. }
  26275. else {
  26276. condition._evaluationId = currentRenderId;
  26277. if (!condition.isValid()) {
  26278. condition._currentResult = false;
  26279. return;
  26280. }
  26281. condition._currentResult = true;
  26282. }
  26283. }
  26284. this._nextActiveAction.execute(evt);
  26285. this.skipToNextActiveAction();
  26286. };
  26287. Action.prototype.execute = function (evt) {
  26288. };
  26289. Action.prototype.skipToNextActiveAction = function () {
  26290. if (this._nextActiveAction._child) {
  26291. if (!this._nextActiveAction._child._actionManager) {
  26292. this._nextActiveAction._child._actionManager = this._actionManager;
  26293. }
  26294. this._nextActiveAction = this._nextActiveAction._child;
  26295. }
  26296. else {
  26297. this._nextActiveAction = this;
  26298. }
  26299. };
  26300. Action.prototype.then = function (action) {
  26301. this._child = action;
  26302. action._actionManager = this._actionManager;
  26303. action._prepare();
  26304. return action;
  26305. };
  26306. Action.prototype._getProperty = function (propertyPath) {
  26307. return this._actionManager._getProperty(propertyPath);
  26308. };
  26309. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26310. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26311. };
  26312. return Action;
  26313. })();
  26314. BABYLON.Action = Action;
  26315. })(BABYLON || (BABYLON = {}));
  26316. var BABYLON;
  26317. (function (BABYLON) {
  26318. /**
  26319. * ActionEvent is the event beint sent when an action is triggered.
  26320. */
  26321. var ActionEvent = (function () {
  26322. /**
  26323. * @constructor
  26324. * @param source The mesh or sprite that triggered the action.
  26325. * @param pointerX The X mouse cursor position at the time of the event
  26326. * @param pointerY The Y mouse cursor position at the time of the event
  26327. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26328. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26329. */
  26330. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26331. this.source = source;
  26332. this.pointerX = pointerX;
  26333. this.pointerY = pointerY;
  26334. this.meshUnderPointer = meshUnderPointer;
  26335. this.sourceEvent = sourceEvent;
  26336. this.additionalData = additionalData;
  26337. }
  26338. /**
  26339. * Helper function to auto-create an ActionEvent from a source mesh.
  26340. * @param source The source mesh that triggered the event
  26341. * @param evt {Event} The original (browser) event
  26342. */
  26343. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26344. var scene = source.getScene();
  26345. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26346. };
  26347. /**
  26348. * Helper function to auto-create an ActionEvent from a source mesh.
  26349. * @param source The source sprite that triggered the event
  26350. * @param scene Scene associated with the sprite
  26351. * @param evt {Event} The original (browser) event
  26352. */
  26353. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26354. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26355. };
  26356. /**
  26357. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26358. * @param scene the scene where the event occurred
  26359. * @param evt {Event} The original (browser) event
  26360. */
  26361. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26362. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26363. };
  26364. return ActionEvent;
  26365. })();
  26366. BABYLON.ActionEvent = ActionEvent;
  26367. /**
  26368. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26369. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26370. */
  26371. var ActionManager = (function () {
  26372. function ActionManager(scene) {
  26373. // Members
  26374. this.actions = new Array();
  26375. this._scene = scene;
  26376. scene._actionManagers.push(this);
  26377. }
  26378. Object.defineProperty(ActionManager, "NothingTrigger", {
  26379. get: function () {
  26380. return ActionManager._NothingTrigger;
  26381. },
  26382. enumerable: true,
  26383. configurable: true
  26384. });
  26385. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26386. get: function () {
  26387. return ActionManager._OnPickTrigger;
  26388. },
  26389. enumerable: true,
  26390. configurable: true
  26391. });
  26392. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26393. get: function () {
  26394. return ActionManager._OnLeftPickTrigger;
  26395. },
  26396. enumerable: true,
  26397. configurable: true
  26398. });
  26399. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26400. get: function () {
  26401. return ActionManager._OnRightPickTrigger;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26407. get: function () {
  26408. return ActionManager._OnCenterPickTrigger;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26414. get: function () {
  26415. return ActionManager._OnPickDownTrigger;
  26416. },
  26417. enumerable: true,
  26418. configurable: true
  26419. });
  26420. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26421. get: function () {
  26422. return ActionManager._OnPickUpTrigger;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26428. /// This trigger will only be raised if you also declared a OnPickDown
  26429. get: function () {
  26430. return ActionManager._OnPickOutTrigger;
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26436. get: function () {
  26437. return ActionManager._OnLongPressTrigger;
  26438. },
  26439. enumerable: true,
  26440. configurable: true
  26441. });
  26442. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26443. get: function () {
  26444. return ActionManager._OnPointerOverTrigger;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26450. get: function () {
  26451. return ActionManager._OnPointerOutTrigger;
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26457. get: function () {
  26458. return ActionManager._OnEveryFrameTrigger;
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26464. get: function () {
  26465. return ActionManager._OnIntersectionEnterTrigger;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26471. get: function () {
  26472. return ActionManager._OnIntersectionExitTrigger;
  26473. },
  26474. enumerable: true,
  26475. configurable: true
  26476. });
  26477. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26478. get: function () {
  26479. return ActionManager._OnKeyDownTrigger;
  26480. },
  26481. enumerable: true,
  26482. configurable: true
  26483. });
  26484. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26485. get: function () {
  26486. return ActionManager._OnKeyUpTrigger;
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. // Methods
  26492. ActionManager.prototype.dispose = function () {
  26493. var index = this._scene._actionManagers.indexOf(this);
  26494. if (index > -1) {
  26495. this._scene._actionManagers.splice(index, 1);
  26496. }
  26497. };
  26498. ActionManager.prototype.getScene = function () {
  26499. return this._scene;
  26500. };
  26501. /**
  26502. * Does this action manager handles actions of any of the given triggers
  26503. * @param {number[]} triggers - the triggers to be tested
  26504. * @return {boolean} whether one (or more) of the triggers is handeled
  26505. */
  26506. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26507. for (var index = 0; index < this.actions.length; index++) {
  26508. var action = this.actions[index];
  26509. if (triggers.indexOf(action.trigger) > -1) {
  26510. return true;
  26511. }
  26512. }
  26513. return false;
  26514. };
  26515. /**
  26516. * Does this action manager handles actions of a given trigger
  26517. * @param {number} trigger - the trigger to be tested
  26518. * @return {boolean} whether the trigger is handeled
  26519. */
  26520. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26521. for (var index = 0; index < this.actions.length; index++) {
  26522. var action = this.actions[index];
  26523. if (action.trigger === trigger) {
  26524. return true;
  26525. }
  26526. }
  26527. return false;
  26528. };
  26529. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26530. /**
  26531. * Does this action manager has pointer triggers
  26532. * @return {boolean} whether or not it has pointer triggers
  26533. */
  26534. get: function () {
  26535. for (var index = 0; index < this.actions.length; index++) {
  26536. var action = this.actions[index];
  26537. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26538. return true;
  26539. }
  26540. }
  26541. return false;
  26542. },
  26543. enumerable: true,
  26544. configurable: true
  26545. });
  26546. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26547. /**
  26548. * Does this action manager has pick triggers
  26549. * @return {boolean} whether or not it has pick triggers
  26550. */
  26551. get: function () {
  26552. for (var index = 0; index < this.actions.length; index++) {
  26553. var action = this.actions[index];
  26554. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26555. return true;
  26556. }
  26557. }
  26558. return false;
  26559. },
  26560. enumerable: true,
  26561. configurable: true
  26562. });
  26563. /**
  26564. * Registers an action to this action manager
  26565. * @param {BABYLON.Action} action - the action to be registered
  26566. * @return {BABYLON.Action} the action amended (prepared) after registration
  26567. */
  26568. ActionManager.prototype.registerAction = function (action) {
  26569. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26570. if (this.getScene().actionManager !== this) {
  26571. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26572. return null;
  26573. }
  26574. }
  26575. this.actions.push(action);
  26576. action._actionManager = this;
  26577. action._prepare();
  26578. return action;
  26579. };
  26580. /**
  26581. * Process a specific trigger
  26582. * @param {number} trigger - the trigger to process
  26583. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26584. */
  26585. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26586. for (var index = 0; index < this.actions.length; index++) {
  26587. var action = this.actions[index];
  26588. if (action.trigger === trigger) {
  26589. if (trigger === ActionManager.OnKeyUpTrigger
  26590. || trigger === ActionManager.OnKeyDownTrigger) {
  26591. var parameter = action.getTriggerParameter();
  26592. if (parameter) {
  26593. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26594. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26595. if (actualkey !== parameter.toLowerCase()) {
  26596. continue;
  26597. }
  26598. }
  26599. }
  26600. action._executeCurrent(evt);
  26601. }
  26602. }
  26603. };
  26604. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26605. var properties = propertyPath.split(".");
  26606. for (var index = 0; index < properties.length - 1; index++) {
  26607. target = target[properties[index]];
  26608. }
  26609. return target;
  26610. };
  26611. ActionManager.prototype._getProperty = function (propertyPath) {
  26612. var properties = propertyPath.split(".");
  26613. return properties[properties.length - 1];
  26614. };
  26615. ActionManager.Parse = function (parsedActions, object, scene) {
  26616. var actionManager = new BABYLON.ActionManager(scene);
  26617. if (object === null)
  26618. scene.actionManager = actionManager;
  26619. else
  26620. object.actionManager = actionManager;
  26621. // instanciate a new object
  26622. var instanciate = function (name, params) {
  26623. var newInstance = Object.create(BABYLON[name].prototype);
  26624. newInstance.constructor.apply(newInstance, params);
  26625. return newInstance;
  26626. };
  26627. var parseParameter = function (name, value, target, propertyPath) {
  26628. if (propertyPath === null) {
  26629. // String, boolean or float
  26630. var floatValue = parseFloat(value);
  26631. if (value === "true" || value === "false")
  26632. return value === "true";
  26633. else
  26634. return isNaN(floatValue) ? value : floatValue;
  26635. }
  26636. var effectiveTarget = propertyPath.split(".");
  26637. var values = value.split(",");
  26638. // Get effective Target
  26639. for (var i = 0; i < effectiveTarget.length; i++) {
  26640. target = target[effectiveTarget[i]];
  26641. }
  26642. // Return appropriate value with its type
  26643. if (typeof (target) === "boolean")
  26644. return values[0] === "true";
  26645. if (typeof (target) === "string")
  26646. return values[0];
  26647. // Parameters with multiple values such as Vector3 etc.
  26648. var split = new Array();
  26649. for (var i = 0; i < values.length; i++)
  26650. split.push(parseFloat(values[i]));
  26651. if (target instanceof BABYLON.Vector3)
  26652. return BABYLON.Vector3.FromArray(split);
  26653. if (target instanceof BABYLON.Vector4)
  26654. return BABYLON.Vector4.FromArray(split);
  26655. if (target instanceof BABYLON.Color3)
  26656. return BABYLON.Color3.FromArray(split);
  26657. if (target instanceof BABYLON.Color4)
  26658. return BABYLON.Color4.FromArray(split);
  26659. return parseFloat(values[0]);
  26660. };
  26661. // traverse graph per trigger
  26662. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26663. if (combineArray === void 0) { combineArray = null; }
  26664. if (parsedAction.detached)
  26665. return;
  26666. var parameters = new Array();
  26667. var target = null;
  26668. var propertyPath = null;
  26669. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26670. // Parameters
  26671. if (parsedAction.type === 2)
  26672. parameters.push(actionManager);
  26673. else
  26674. parameters.push(trigger);
  26675. if (combine) {
  26676. var actions = new Array();
  26677. for (var j = 0; j < parsedAction.combine.length; j++) {
  26678. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26679. }
  26680. parameters.push(actions);
  26681. }
  26682. else {
  26683. for (var i = 0; i < parsedAction.properties.length; i++) {
  26684. var value = parsedAction.properties[i].value;
  26685. var name = parsedAction.properties[i].name;
  26686. var targetType = parsedAction.properties[i].targetType;
  26687. if (name === "target")
  26688. if (targetType !== null && targetType === "SceneProperties")
  26689. value = target = scene;
  26690. else
  26691. value = target = scene.getNodeByName(value);
  26692. else if (name === "parent")
  26693. value = scene.getNodeByName(value);
  26694. else if (name === "sound")
  26695. value = scene.getSoundByName(value);
  26696. else if (name !== "propertyPath") {
  26697. if (parsedAction.type === 2 && name === "operator")
  26698. value = BABYLON.ValueCondition[value];
  26699. else
  26700. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26701. }
  26702. else {
  26703. propertyPath = value;
  26704. }
  26705. parameters.push(value);
  26706. }
  26707. }
  26708. if (combineArray === null) {
  26709. parameters.push(condition);
  26710. }
  26711. else {
  26712. parameters.push(null);
  26713. }
  26714. // If interpolate value action
  26715. if (parsedAction.name === "InterpolateValueAction") {
  26716. var param = parameters[parameters.length - 2];
  26717. parameters[parameters.length - 1] = param;
  26718. parameters[parameters.length - 2] = condition;
  26719. }
  26720. // Action or condition(s) and not CombineAction
  26721. var newAction = instanciate(parsedAction.name, parameters);
  26722. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26723. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26724. if (action)
  26725. action.then(nothing);
  26726. else
  26727. actionManager.registerAction(nothing);
  26728. action = nothing;
  26729. }
  26730. if (combineArray === null) {
  26731. if (newAction instanceof BABYLON.Condition) {
  26732. condition = newAction;
  26733. newAction = action;
  26734. }
  26735. else {
  26736. condition = null;
  26737. if (action)
  26738. action.then(newAction);
  26739. else
  26740. actionManager.registerAction(newAction);
  26741. }
  26742. }
  26743. else {
  26744. combineArray.push(newAction);
  26745. }
  26746. for (var i = 0; i < parsedAction.children.length; i++)
  26747. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26748. };
  26749. // triggers
  26750. for (var i = 0; i < parsedActions.children.length; i++) {
  26751. var triggerParams;
  26752. var trigger = parsedActions.children[i];
  26753. if (trigger.properties.length > 0) {
  26754. var param = trigger.properties[0].value;
  26755. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26756. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26757. }
  26758. else
  26759. triggerParams = BABYLON.ActionManager[trigger.name];
  26760. for (var j = 0; j < trigger.children.length; j++) {
  26761. if (!trigger.detached)
  26762. traverse(trigger.children[j], triggerParams, null, null);
  26763. }
  26764. }
  26765. };
  26766. // Statics
  26767. ActionManager._NothingTrigger = 0;
  26768. ActionManager._OnPickTrigger = 1;
  26769. ActionManager._OnLeftPickTrigger = 2;
  26770. ActionManager._OnRightPickTrigger = 3;
  26771. ActionManager._OnCenterPickTrigger = 4;
  26772. ActionManager._OnPickDownTrigger = 5;
  26773. ActionManager._OnPickUpTrigger = 6;
  26774. ActionManager._OnLongPressTrigger = 7;
  26775. ActionManager._OnPointerOverTrigger = 8;
  26776. ActionManager._OnPointerOutTrigger = 9;
  26777. ActionManager._OnEveryFrameTrigger = 10;
  26778. ActionManager._OnIntersectionEnterTrigger = 11;
  26779. ActionManager._OnIntersectionExitTrigger = 12;
  26780. ActionManager._OnKeyDownTrigger = 13;
  26781. ActionManager._OnKeyUpTrigger = 14;
  26782. ActionManager._OnPickOutTrigger = 15;
  26783. ActionManager.DragMovementThreshold = 10; // in pixels
  26784. ActionManager.LongPressDelay = 500; // in milliseconds
  26785. return ActionManager;
  26786. })();
  26787. BABYLON.ActionManager = ActionManager;
  26788. })(BABYLON || (BABYLON = {}));
  26789. var BABYLON;
  26790. (function (BABYLON) {
  26791. var InterpolateValueAction = (function (_super) {
  26792. __extends(InterpolateValueAction, _super);
  26793. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26794. if (duration === void 0) { duration = 1000; }
  26795. _super.call(this, triggerOptions, condition);
  26796. this.propertyPath = propertyPath;
  26797. this.value = value;
  26798. this.duration = duration;
  26799. this.stopOtherAnimations = stopOtherAnimations;
  26800. this.onInterpolationDone = onInterpolationDone;
  26801. this._target = target;
  26802. }
  26803. InterpolateValueAction.prototype._prepare = function () {
  26804. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26805. this._property = this._getProperty(this.propertyPath);
  26806. };
  26807. InterpolateValueAction.prototype.execute = function () {
  26808. var scene = this._actionManager.getScene();
  26809. var keys = [
  26810. {
  26811. frame: 0,
  26812. value: this._target[this._property]
  26813. }, {
  26814. frame: 100,
  26815. value: this.value
  26816. }
  26817. ];
  26818. var dataType;
  26819. if (typeof this.value === "number") {
  26820. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26821. }
  26822. else if (this.value instanceof BABYLON.Color3) {
  26823. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26824. }
  26825. else if (this.value instanceof BABYLON.Vector3) {
  26826. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26827. }
  26828. else if (this.value instanceof BABYLON.Matrix) {
  26829. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26830. }
  26831. else if (this.value instanceof BABYLON.Quaternion) {
  26832. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26833. }
  26834. else {
  26835. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26836. return;
  26837. }
  26838. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26839. animation.setKeys(keys);
  26840. if (this.stopOtherAnimations) {
  26841. scene.stopAnimation(this._target);
  26842. }
  26843. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26844. };
  26845. return InterpolateValueAction;
  26846. })(BABYLON.Action);
  26847. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26848. })(BABYLON || (BABYLON = {}));
  26849. var BABYLON;
  26850. (function (BABYLON) {
  26851. var SwitchBooleanAction = (function (_super) {
  26852. __extends(SwitchBooleanAction, _super);
  26853. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26854. _super.call(this, triggerOptions, condition);
  26855. this.propertyPath = propertyPath;
  26856. this._target = target;
  26857. }
  26858. SwitchBooleanAction.prototype._prepare = function () {
  26859. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26860. this._property = this._getProperty(this.propertyPath);
  26861. };
  26862. SwitchBooleanAction.prototype.execute = function () {
  26863. this._target[this._property] = !this._target[this._property];
  26864. };
  26865. return SwitchBooleanAction;
  26866. })(BABYLON.Action);
  26867. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26868. var SetStateAction = (function (_super) {
  26869. __extends(SetStateAction, _super);
  26870. function SetStateAction(triggerOptions, target, value, condition) {
  26871. _super.call(this, triggerOptions, condition);
  26872. this.value = value;
  26873. this._target = target;
  26874. }
  26875. SetStateAction.prototype.execute = function () {
  26876. this._target.state = this.value;
  26877. };
  26878. return SetStateAction;
  26879. })(BABYLON.Action);
  26880. BABYLON.SetStateAction = SetStateAction;
  26881. var SetValueAction = (function (_super) {
  26882. __extends(SetValueAction, _super);
  26883. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26884. _super.call(this, triggerOptions, condition);
  26885. this.propertyPath = propertyPath;
  26886. this.value = value;
  26887. this._target = target;
  26888. }
  26889. SetValueAction.prototype._prepare = function () {
  26890. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26891. this._property = this._getProperty(this.propertyPath);
  26892. };
  26893. SetValueAction.prototype.execute = function () {
  26894. this._target[this._property] = this.value;
  26895. };
  26896. return SetValueAction;
  26897. })(BABYLON.Action);
  26898. BABYLON.SetValueAction = SetValueAction;
  26899. var IncrementValueAction = (function (_super) {
  26900. __extends(IncrementValueAction, _super);
  26901. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26902. _super.call(this, triggerOptions, condition);
  26903. this.propertyPath = propertyPath;
  26904. this.value = value;
  26905. this._target = target;
  26906. }
  26907. IncrementValueAction.prototype._prepare = function () {
  26908. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26909. this._property = this._getProperty(this.propertyPath);
  26910. if (typeof this._target[this._property] !== "number") {
  26911. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26912. }
  26913. };
  26914. IncrementValueAction.prototype.execute = function () {
  26915. this._target[this._property] += this.value;
  26916. };
  26917. return IncrementValueAction;
  26918. })(BABYLON.Action);
  26919. BABYLON.IncrementValueAction = IncrementValueAction;
  26920. var PlayAnimationAction = (function (_super) {
  26921. __extends(PlayAnimationAction, _super);
  26922. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26923. _super.call(this, triggerOptions, condition);
  26924. this.from = from;
  26925. this.to = to;
  26926. this.loop = loop;
  26927. this._target = target;
  26928. }
  26929. PlayAnimationAction.prototype._prepare = function () {
  26930. };
  26931. PlayAnimationAction.prototype.execute = function () {
  26932. var scene = this._actionManager.getScene();
  26933. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26934. };
  26935. return PlayAnimationAction;
  26936. })(BABYLON.Action);
  26937. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26938. var StopAnimationAction = (function (_super) {
  26939. __extends(StopAnimationAction, _super);
  26940. function StopAnimationAction(triggerOptions, target, condition) {
  26941. _super.call(this, triggerOptions, condition);
  26942. this._target = target;
  26943. }
  26944. StopAnimationAction.prototype._prepare = function () {
  26945. };
  26946. StopAnimationAction.prototype.execute = function () {
  26947. var scene = this._actionManager.getScene();
  26948. scene.stopAnimation(this._target);
  26949. };
  26950. return StopAnimationAction;
  26951. })(BABYLON.Action);
  26952. BABYLON.StopAnimationAction = StopAnimationAction;
  26953. var DoNothingAction = (function (_super) {
  26954. __extends(DoNothingAction, _super);
  26955. function DoNothingAction(triggerOptions, condition) {
  26956. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26957. _super.call(this, triggerOptions, condition);
  26958. }
  26959. DoNothingAction.prototype.execute = function () {
  26960. };
  26961. return DoNothingAction;
  26962. })(BABYLON.Action);
  26963. BABYLON.DoNothingAction = DoNothingAction;
  26964. var CombineAction = (function (_super) {
  26965. __extends(CombineAction, _super);
  26966. function CombineAction(triggerOptions, children, condition) {
  26967. _super.call(this, triggerOptions, condition);
  26968. this.children = children;
  26969. }
  26970. CombineAction.prototype._prepare = function () {
  26971. for (var index = 0; index < this.children.length; index++) {
  26972. this.children[index]._actionManager = this._actionManager;
  26973. this.children[index]._prepare();
  26974. }
  26975. };
  26976. CombineAction.prototype.execute = function (evt) {
  26977. for (var index = 0; index < this.children.length; index++) {
  26978. this.children[index].execute(evt);
  26979. }
  26980. };
  26981. return CombineAction;
  26982. })(BABYLON.Action);
  26983. BABYLON.CombineAction = CombineAction;
  26984. var ExecuteCodeAction = (function (_super) {
  26985. __extends(ExecuteCodeAction, _super);
  26986. function ExecuteCodeAction(triggerOptions, func, condition) {
  26987. _super.call(this, triggerOptions, condition);
  26988. this.func = func;
  26989. }
  26990. ExecuteCodeAction.prototype.execute = function (evt) {
  26991. this.func(evt);
  26992. };
  26993. return ExecuteCodeAction;
  26994. })(BABYLON.Action);
  26995. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26996. var SetParentAction = (function (_super) {
  26997. __extends(SetParentAction, _super);
  26998. function SetParentAction(triggerOptions, target, parent, condition) {
  26999. _super.call(this, triggerOptions, condition);
  27000. this._target = target;
  27001. this._parent = parent;
  27002. }
  27003. SetParentAction.prototype._prepare = function () {
  27004. };
  27005. SetParentAction.prototype.execute = function () {
  27006. if (this._target.parent === this._parent) {
  27007. return;
  27008. }
  27009. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27010. invertParentWorldMatrix.invert();
  27011. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27012. this._target.parent = this._parent;
  27013. };
  27014. return SetParentAction;
  27015. })(BABYLON.Action);
  27016. BABYLON.SetParentAction = SetParentAction;
  27017. var PlaySoundAction = (function (_super) {
  27018. __extends(PlaySoundAction, _super);
  27019. function PlaySoundAction(triggerOptions, sound, condition) {
  27020. _super.call(this, triggerOptions, condition);
  27021. this._sound = sound;
  27022. }
  27023. PlaySoundAction.prototype._prepare = function () {
  27024. };
  27025. PlaySoundAction.prototype.execute = function () {
  27026. if (this._sound !== undefined)
  27027. this._sound.play();
  27028. };
  27029. return PlaySoundAction;
  27030. })(BABYLON.Action);
  27031. BABYLON.PlaySoundAction = PlaySoundAction;
  27032. var StopSoundAction = (function (_super) {
  27033. __extends(StopSoundAction, _super);
  27034. function StopSoundAction(triggerOptions, sound, condition) {
  27035. _super.call(this, triggerOptions, condition);
  27036. this._sound = sound;
  27037. }
  27038. StopSoundAction.prototype._prepare = function () {
  27039. };
  27040. StopSoundAction.prototype.execute = function () {
  27041. if (this._sound !== undefined)
  27042. this._sound.stop();
  27043. };
  27044. return StopSoundAction;
  27045. })(BABYLON.Action);
  27046. BABYLON.StopSoundAction = StopSoundAction;
  27047. })(BABYLON || (BABYLON = {}));
  27048. var BABYLON;
  27049. (function (BABYLON) {
  27050. var Geometry = (function () {
  27051. function Geometry(id, scene, vertexData, updatable, mesh) {
  27052. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27053. this._totalVertices = 0;
  27054. this._isDisposed = false;
  27055. this.id = id;
  27056. this._engine = scene.getEngine();
  27057. this._meshes = [];
  27058. this._scene = scene;
  27059. //Init vertex buffer cache
  27060. this._vertexBuffers = {};
  27061. this._indices = [];
  27062. // vertexData
  27063. if (vertexData) {
  27064. this.setAllVerticesData(vertexData, updatable);
  27065. }
  27066. else {
  27067. this._totalVertices = 0;
  27068. this._indices = [];
  27069. }
  27070. // applyToMesh
  27071. if (mesh) {
  27072. this.applyToMesh(mesh);
  27073. mesh.computeWorldMatrix(true);
  27074. }
  27075. }
  27076. Object.defineProperty(Geometry.prototype, "extend", {
  27077. get: function () {
  27078. return this._extend;
  27079. },
  27080. enumerable: true,
  27081. configurable: true
  27082. });
  27083. Geometry.prototype.getScene = function () {
  27084. return this._scene;
  27085. };
  27086. Geometry.prototype.getEngine = function () {
  27087. return this._engine;
  27088. };
  27089. Geometry.prototype.isReady = function () {
  27090. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27091. };
  27092. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27093. vertexData.applyToGeometry(this, updatable);
  27094. this.notifyUpdate();
  27095. };
  27096. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27097. if (this._vertexBuffers[kind]) {
  27098. this._vertexBuffers[kind].dispose();
  27099. }
  27100. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27101. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27102. stride = this._vertexBuffers[kind].getStrideSize();
  27103. this._totalVertices = data.length / stride;
  27104. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27105. var meshes = this._meshes;
  27106. var numOfMeshes = meshes.length;
  27107. for (var index = 0; index < numOfMeshes; index++) {
  27108. var mesh = meshes[index];
  27109. mesh._resetPointsArrayCache();
  27110. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27111. mesh._createGlobalSubMesh();
  27112. mesh.computeWorldMatrix(true);
  27113. }
  27114. }
  27115. this.notifyUpdate(kind);
  27116. };
  27117. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27118. var vertexBuffer = this.getVertexBuffer(kind);
  27119. if (!vertexBuffer) {
  27120. return;
  27121. }
  27122. vertexBuffer.updateDirectly(data, offset);
  27123. this.notifyUpdate(kind);
  27124. };
  27125. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27126. var vertexBuffer = this.getVertexBuffer(kind);
  27127. if (!vertexBuffer) {
  27128. return;
  27129. }
  27130. vertexBuffer.update(data);
  27131. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27132. var stride = vertexBuffer.getStrideSize();
  27133. this._totalVertices = data.length / stride;
  27134. if (updateExtends) {
  27135. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27136. }
  27137. var meshes = this._meshes;
  27138. var numOfMeshes = meshes.length;
  27139. for (var index = 0; index < numOfMeshes; index++) {
  27140. var mesh = meshes[index];
  27141. mesh._resetPointsArrayCache();
  27142. if (updateExtends) {
  27143. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27144. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27145. var subMesh = mesh.subMeshes[subIndex];
  27146. subMesh.refreshBoundingInfo();
  27147. }
  27148. }
  27149. }
  27150. }
  27151. this.notifyUpdate(kind);
  27152. };
  27153. Geometry.prototype.getTotalVertices = function () {
  27154. if (!this.isReady()) {
  27155. return 0;
  27156. }
  27157. return this._totalVertices;
  27158. };
  27159. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27160. var vertexBuffer = this.getVertexBuffer(kind);
  27161. if (!vertexBuffer) {
  27162. return null;
  27163. }
  27164. var orig = vertexBuffer.getData();
  27165. if (!copyWhenShared || this._meshes.length === 1) {
  27166. return orig;
  27167. }
  27168. else {
  27169. var len = orig.length;
  27170. var copy = [];
  27171. for (var i = 0; i < len; i++) {
  27172. copy.push(orig[i]);
  27173. }
  27174. return copy;
  27175. }
  27176. };
  27177. Geometry.prototype.getVertexBuffer = function (kind) {
  27178. if (!this.isReady()) {
  27179. return null;
  27180. }
  27181. return this._vertexBuffers[kind];
  27182. };
  27183. Geometry.prototype.getVertexBuffers = function () {
  27184. if (!this.isReady()) {
  27185. return null;
  27186. }
  27187. return this._vertexBuffers;
  27188. };
  27189. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27190. if (!this._vertexBuffers) {
  27191. if (this._delayInfo) {
  27192. return this._delayInfo.indexOf(kind) !== -1;
  27193. }
  27194. return false;
  27195. }
  27196. return this._vertexBuffers[kind] !== undefined;
  27197. };
  27198. Geometry.prototype.getVerticesDataKinds = function () {
  27199. var result = [];
  27200. var kind;
  27201. if (!this._vertexBuffers && this._delayInfo) {
  27202. for (kind in this._delayInfo) {
  27203. result.push(kind);
  27204. }
  27205. }
  27206. else {
  27207. for (kind in this._vertexBuffers) {
  27208. result.push(kind);
  27209. }
  27210. }
  27211. return result;
  27212. };
  27213. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27214. if (this._indexBuffer) {
  27215. this._engine._releaseBuffer(this._indexBuffer);
  27216. }
  27217. this._indices = indices;
  27218. if (this._meshes.length !== 0 && this._indices) {
  27219. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27220. }
  27221. if (totalVertices !== undefined) {
  27222. this._totalVertices = totalVertices;
  27223. }
  27224. var meshes = this._meshes;
  27225. var numOfMeshes = meshes.length;
  27226. for (var index = 0; index < numOfMeshes; index++) {
  27227. meshes[index]._createGlobalSubMesh();
  27228. }
  27229. this.notifyUpdate();
  27230. };
  27231. Geometry.prototype.getTotalIndices = function () {
  27232. if (!this.isReady()) {
  27233. return 0;
  27234. }
  27235. return this._indices.length;
  27236. };
  27237. Geometry.prototype.getIndices = function (copyWhenShared) {
  27238. if (!this.isReady()) {
  27239. return null;
  27240. }
  27241. var orig = this._indices;
  27242. if (!copyWhenShared || this._meshes.length === 1) {
  27243. return orig;
  27244. }
  27245. else {
  27246. var len = orig.length;
  27247. var copy = [];
  27248. for (var i = 0; i < len; i++) {
  27249. copy.push(orig[i]);
  27250. }
  27251. return copy;
  27252. }
  27253. };
  27254. Geometry.prototype.getIndexBuffer = function () {
  27255. if (!this.isReady()) {
  27256. return null;
  27257. }
  27258. return this._indexBuffer;
  27259. };
  27260. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27261. var meshes = this._meshes;
  27262. var index = meshes.indexOf(mesh);
  27263. if (index === -1) {
  27264. return;
  27265. }
  27266. for (var kind in this._vertexBuffers) {
  27267. this._vertexBuffers[kind].dispose();
  27268. }
  27269. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27270. this._indexBuffer = null;
  27271. }
  27272. meshes.splice(index, 1);
  27273. mesh._geometry = null;
  27274. if (meshes.length === 0 && shouldDispose) {
  27275. this.dispose();
  27276. }
  27277. };
  27278. Geometry.prototype.applyToMesh = function (mesh) {
  27279. if (mesh._geometry === this) {
  27280. return;
  27281. }
  27282. var previousGeometry = mesh._geometry;
  27283. if (previousGeometry) {
  27284. previousGeometry.releaseForMesh(mesh);
  27285. }
  27286. var meshes = this._meshes;
  27287. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27288. mesh._geometry = this;
  27289. this._scene.pushGeometry(this);
  27290. meshes.push(mesh);
  27291. if (this.isReady()) {
  27292. this._applyToMesh(mesh);
  27293. }
  27294. else {
  27295. mesh._boundingInfo = this._boundingInfo;
  27296. }
  27297. };
  27298. Geometry.prototype._applyToMesh = function (mesh) {
  27299. var numOfMeshes = this._meshes.length;
  27300. // vertexBuffers
  27301. for (var kind in this._vertexBuffers) {
  27302. if (numOfMeshes === 1) {
  27303. this._vertexBuffers[kind].create();
  27304. }
  27305. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27306. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27307. mesh._resetPointsArrayCache();
  27308. if (!this._extend) {
  27309. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27310. }
  27311. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27312. mesh._createGlobalSubMesh();
  27313. //bounding info was just created again, world matrix should be applied again.
  27314. mesh._updateBoundingInfo();
  27315. }
  27316. }
  27317. // indexBuffer
  27318. if (numOfMeshes === 1 && this._indices) {
  27319. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27320. }
  27321. if (this._indexBuffer) {
  27322. this._indexBuffer.references = numOfMeshes;
  27323. }
  27324. };
  27325. Geometry.prototype.notifyUpdate = function (kind) {
  27326. if (this.onGeometryUpdated) {
  27327. this.onGeometryUpdated(this, kind);
  27328. }
  27329. };
  27330. Geometry.prototype.load = function (scene, onLoaded) {
  27331. var _this = this;
  27332. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27333. return;
  27334. }
  27335. if (this.isReady()) {
  27336. if (onLoaded) {
  27337. onLoaded();
  27338. }
  27339. return;
  27340. }
  27341. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27342. scene._addPendingData(this);
  27343. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27344. _this._delayLoadingFunction(JSON.parse(data), _this);
  27345. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27346. _this._delayInfo = [];
  27347. scene._removePendingData(_this);
  27348. var meshes = _this._meshes;
  27349. var numOfMeshes = meshes.length;
  27350. for (var index = 0; index < numOfMeshes; index++) {
  27351. _this._applyToMesh(meshes[index]);
  27352. }
  27353. if (onLoaded) {
  27354. onLoaded();
  27355. }
  27356. }, function () { }, scene.database);
  27357. };
  27358. Geometry.prototype.isDisposed = function () {
  27359. return this._isDisposed;
  27360. };
  27361. Geometry.prototype.dispose = function () {
  27362. var meshes = this._meshes;
  27363. var numOfMeshes = meshes.length;
  27364. var index;
  27365. for (index = 0; index < numOfMeshes; index++) {
  27366. this.releaseForMesh(meshes[index]);
  27367. }
  27368. this._meshes = [];
  27369. for (var kind in this._vertexBuffers) {
  27370. this._vertexBuffers[kind].dispose();
  27371. }
  27372. this._vertexBuffers = [];
  27373. this._totalVertices = 0;
  27374. if (this._indexBuffer) {
  27375. this._engine._releaseBuffer(this._indexBuffer);
  27376. }
  27377. this._indexBuffer = null;
  27378. this._indices = [];
  27379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27380. this.delayLoadingFile = null;
  27381. this._delayLoadingFunction = null;
  27382. this._delayInfo = [];
  27383. this._boundingInfo = null;
  27384. this._scene.removeGeometry(this);
  27385. this._isDisposed = true;
  27386. };
  27387. Geometry.prototype.copy = function (id) {
  27388. var vertexData = new BABYLON.VertexData();
  27389. vertexData.indices = [];
  27390. var indices = this.getIndices();
  27391. for (var index = 0; index < indices.length; index++) {
  27392. vertexData.indices.push(indices[index]);
  27393. }
  27394. var updatable = false;
  27395. var stopChecking = false;
  27396. var kind;
  27397. for (kind in this._vertexBuffers) {
  27398. // using slice() to make a copy of the array and not just reference it
  27399. var data = this.getVerticesData(kind);
  27400. if (data instanceof Float32Array) {
  27401. vertexData.set(new Float32Array(data), kind);
  27402. }
  27403. else {
  27404. vertexData.set(data.slice(0), kind);
  27405. }
  27406. if (!stopChecking) {
  27407. updatable = this.getVertexBuffer(kind).isUpdatable();
  27408. stopChecking = !updatable;
  27409. }
  27410. }
  27411. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27412. geometry.delayLoadState = this.delayLoadState;
  27413. geometry.delayLoadingFile = this.delayLoadingFile;
  27414. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27415. for (kind in this._delayInfo) {
  27416. geometry._delayInfo = geometry._delayInfo || [];
  27417. geometry._delayInfo.push(kind);
  27418. }
  27419. // Bounding info
  27420. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27421. return geometry;
  27422. };
  27423. Geometry.prototype.serialize = function () {
  27424. var serializationObject = {};
  27425. serializationObject.id = this.id;
  27426. if (BABYLON.Tags.HasTags(this)) {
  27427. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27428. }
  27429. return serializationObject;
  27430. };
  27431. Geometry.prototype.serializeVerticeData = function () {
  27432. var serializationObject = this.serialize();
  27433. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27434. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27435. }
  27436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27437. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27438. }
  27439. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27440. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27441. }
  27442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27443. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27444. }
  27445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27446. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27447. }
  27448. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27449. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27450. }
  27451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27452. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27453. }
  27454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27455. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27456. }
  27457. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27458. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27459. }
  27460. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27461. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27462. serializationObject.matricesIndices._isExpanded = true;
  27463. }
  27464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27465. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27466. }
  27467. serializationObject.indices = this.getIndices();
  27468. return serializationObject;
  27469. };
  27470. // Statics
  27471. Geometry.ExtractFromMesh = function (mesh, id) {
  27472. var geometry = mesh._geometry;
  27473. if (!geometry) {
  27474. return null;
  27475. }
  27476. return geometry.copy(id);
  27477. };
  27478. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27479. // be aware Math.random() could cause collisions
  27480. Geometry.RandomId = function () {
  27481. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27482. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27483. return v.toString(16);
  27484. });
  27485. };
  27486. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27487. var scene = mesh.getScene();
  27488. // Geometry
  27489. var geometryId = parsedGeometry.geometryId;
  27490. if (geometryId) {
  27491. var geometry = scene.getGeometryByID(geometryId);
  27492. if (geometry) {
  27493. geometry.applyToMesh(mesh);
  27494. }
  27495. }
  27496. else if (parsedGeometry instanceof ArrayBuffer) {
  27497. var binaryInfo = mesh._binaryInfo;
  27498. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27499. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27500. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27501. }
  27502. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27503. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27504. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27505. }
  27506. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27507. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27508. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27509. }
  27510. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27511. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27512. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27513. }
  27514. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27515. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27516. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27517. }
  27518. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27519. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27520. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27521. }
  27522. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27523. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27524. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27525. }
  27526. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27527. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27528. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27529. }
  27530. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27531. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27532. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27533. }
  27534. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27535. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27536. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27537. }
  27538. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27539. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27541. }
  27542. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27543. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27544. mesh.setIndices(indicesData);
  27545. }
  27546. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27547. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27548. mesh.subMeshes = [];
  27549. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27550. var materialIndex = subMeshesData[(i * 5) + 0];
  27551. var verticesStart = subMeshesData[(i * 5) + 1];
  27552. var verticesCount = subMeshesData[(i * 5) + 2];
  27553. var indexStart = subMeshesData[(i * 5) + 3];
  27554. var indexCount = subMeshesData[(i * 5) + 4];
  27555. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27556. }
  27557. }
  27558. }
  27559. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27560. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27561. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27562. if (parsedGeometry.uvs) {
  27563. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27564. }
  27565. if (parsedGeometry.uvs2) {
  27566. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27567. }
  27568. if (parsedGeometry.uvs3) {
  27569. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27570. }
  27571. if (parsedGeometry.uvs4) {
  27572. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27573. }
  27574. if (parsedGeometry.uvs5) {
  27575. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27576. }
  27577. if (parsedGeometry.uvs6) {
  27578. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27579. }
  27580. if (parsedGeometry.colors) {
  27581. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27582. }
  27583. if (parsedGeometry.matricesIndices) {
  27584. if (!parsedGeometry.matricesIndices._isExpanded) {
  27585. var floatIndices = [];
  27586. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27587. var matricesIndex = parsedGeometry.matricesIndices[i];
  27588. floatIndices.push(matricesIndex & 0x000000FF);
  27589. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27590. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27591. floatIndices.push(matricesIndex >> 24);
  27592. }
  27593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27594. }
  27595. else {
  27596. delete parsedGeometry.matricesIndices._isExpanded;
  27597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27598. }
  27599. }
  27600. if (parsedGeometry.matricesIndicesExtra) {
  27601. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27602. var floatIndices = [];
  27603. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27604. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27605. floatIndices.push(matricesIndex & 0x000000FF);
  27606. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27607. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27608. floatIndices.push(matricesIndex >> 24);
  27609. }
  27610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27611. }
  27612. else {
  27613. delete parsedGeometry.matricesIndices._isExpanded;
  27614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27615. }
  27616. }
  27617. if (parsedGeometry.matricesWeights) {
  27618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27619. }
  27620. if (parsedGeometry.matricesWeightsExtra) {
  27621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27622. }
  27623. mesh.setIndices(parsedGeometry.indices);
  27624. }
  27625. // SubMeshes
  27626. if (parsedGeometry.subMeshes) {
  27627. mesh.subMeshes = [];
  27628. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27629. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27630. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27631. }
  27632. }
  27633. // Flat shading
  27634. if (mesh._shouldGenerateFlatShading) {
  27635. mesh.convertToFlatShadedMesh();
  27636. delete mesh._shouldGenerateFlatShading;
  27637. }
  27638. // Update
  27639. mesh.computeWorldMatrix(true);
  27640. // Octree
  27641. if (scene['_selectionOctree']) {
  27642. scene['_selectionOctree'].addMesh(mesh);
  27643. }
  27644. };
  27645. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27646. if (scene.getGeometryByID(parsedVertexData.id)) {
  27647. return null; // null since geometry could be something else than a box...
  27648. }
  27649. var geometry = new Geometry(parsedVertexData.id, scene);
  27650. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27651. if (parsedVertexData.delayLoadingFile) {
  27652. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27653. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27654. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27655. geometry._delayInfo = [];
  27656. if (parsedVertexData.hasUVs) {
  27657. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27658. }
  27659. if (parsedVertexData.hasUVs2) {
  27660. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27661. }
  27662. if (parsedVertexData.hasUVs3) {
  27663. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27664. }
  27665. if (parsedVertexData.hasUVs4) {
  27666. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27667. }
  27668. if (parsedVertexData.hasUVs5) {
  27669. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27670. }
  27671. if (parsedVertexData.hasUVs6) {
  27672. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27673. }
  27674. if (parsedVertexData.hasColors) {
  27675. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27676. }
  27677. if (parsedVertexData.hasMatricesIndices) {
  27678. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27679. }
  27680. if (parsedVertexData.hasMatricesWeights) {
  27681. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27682. }
  27683. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27684. }
  27685. else {
  27686. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27687. }
  27688. scene.pushGeometry(geometry, true);
  27689. return geometry;
  27690. };
  27691. return Geometry;
  27692. })();
  27693. BABYLON.Geometry = Geometry;
  27694. /////// Primitives //////////////////////////////////////////////
  27695. var Geometry;
  27696. (function (Geometry) {
  27697. var Primitives;
  27698. (function (Primitives) {
  27699. /// Abstract class
  27700. var _Primitive = (function (_super) {
  27701. __extends(_Primitive, _super);
  27702. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27703. this._beingRegenerated = true;
  27704. this._canBeRegenerated = canBeRegenerated;
  27705. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27706. this._beingRegenerated = false;
  27707. }
  27708. _Primitive.prototype.canBeRegenerated = function () {
  27709. return this._canBeRegenerated;
  27710. };
  27711. _Primitive.prototype.regenerate = function () {
  27712. if (!this._canBeRegenerated) {
  27713. return;
  27714. }
  27715. this._beingRegenerated = true;
  27716. this.setAllVerticesData(this._regenerateVertexData(), false);
  27717. this._beingRegenerated = false;
  27718. };
  27719. _Primitive.prototype.asNewGeometry = function (id) {
  27720. return _super.prototype.copy.call(this, id);
  27721. };
  27722. // overrides
  27723. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27724. if (!this._beingRegenerated) {
  27725. return;
  27726. }
  27727. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27728. };
  27729. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27730. if (!this._beingRegenerated) {
  27731. return;
  27732. }
  27733. _super.prototype.setVerticesData.call(this, kind, data, false);
  27734. };
  27735. // to override
  27736. // protected
  27737. _Primitive.prototype._regenerateVertexData = function () {
  27738. throw new Error("Abstract method");
  27739. };
  27740. _Primitive.prototype.copy = function (id) {
  27741. throw new Error("Must be overriden in sub-classes.");
  27742. };
  27743. _Primitive.prototype.serialize = function () {
  27744. var serializationObject = _super.prototype.serialize.call(this);
  27745. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27746. return serializationObject;
  27747. };
  27748. return _Primitive;
  27749. })(Geometry);
  27750. Primitives._Primitive = _Primitive;
  27751. var Ribbon = (function (_super) {
  27752. __extends(Ribbon, _super);
  27753. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27755. this.pathArray = pathArray;
  27756. this.closeArray = closeArray;
  27757. this.closePath = closePath;
  27758. this.offset = offset;
  27759. this.side = side;
  27760. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27761. }
  27762. Ribbon.prototype._regenerateVertexData = function () {
  27763. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27764. };
  27765. Ribbon.prototype.copy = function (id) {
  27766. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27767. };
  27768. return Ribbon;
  27769. })(_Primitive);
  27770. Primitives.Ribbon = Ribbon;
  27771. var Box = (function (_super) {
  27772. __extends(Box, _super);
  27773. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27774. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27775. this.size = size;
  27776. this.side = side;
  27777. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27778. }
  27779. Box.prototype._regenerateVertexData = function () {
  27780. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27781. };
  27782. Box.prototype.copy = function (id) {
  27783. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27784. };
  27785. Box.prototype.serialize = function () {
  27786. var serializationObject = _super.prototype.serialize.call(this);
  27787. serializationObject.size = this.size;
  27788. return serializationObject;
  27789. };
  27790. Box.Parse = function (parsedBox, scene) {
  27791. if (scene.getGeometryByID(parsedBox.id)) {
  27792. return null; // null since geometry could be something else than a box...
  27793. }
  27794. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27795. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27796. scene.pushGeometry(box, true);
  27797. return box;
  27798. };
  27799. return Box;
  27800. })(_Primitive);
  27801. Primitives.Box = Box;
  27802. var Sphere = (function (_super) {
  27803. __extends(Sphere, _super);
  27804. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27805. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27806. this.segments = segments;
  27807. this.diameter = diameter;
  27808. this.side = side;
  27809. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27810. }
  27811. Sphere.prototype._regenerateVertexData = function () {
  27812. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27813. };
  27814. Sphere.prototype.copy = function (id) {
  27815. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27816. };
  27817. Sphere.prototype.serialize = function () {
  27818. var serializationObject = _super.prototype.serialize.call(this);
  27819. serializationObject.segments = this.segments;
  27820. serializationObject.diameter = this.diameter;
  27821. return serializationObject;
  27822. };
  27823. Sphere.Parse = function (parsedSphere, scene) {
  27824. if (scene.getGeometryByID(parsedSphere.id)) {
  27825. return null; // null since geometry could be something else than a sphere...
  27826. }
  27827. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27828. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27829. scene.pushGeometry(sphere, true);
  27830. return sphere;
  27831. };
  27832. return Sphere;
  27833. })(_Primitive);
  27834. Primitives.Sphere = Sphere;
  27835. var Disc = (function (_super) {
  27836. __extends(Disc, _super);
  27837. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27838. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27839. this.radius = radius;
  27840. this.tessellation = tessellation;
  27841. this.side = side;
  27842. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27843. }
  27844. Disc.prototype._regenerateVertexData = function () {
  27845. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27846. };
  27847. Disc.prototype.copy = function (id) {
  27848. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27849. };
  27850. return Disc;
  27851. })(_Primitive);
  27852. Primitives.Disc = Disc;
  27853. var Cylinder = (function (_super) {
  27854. __extends(Cylinder, _super);
  27855. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27856. if (subdivisions === void 0) { subdivisions = 1; }
  27857. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27858. this.height = height;
  27859. this.diameterTop = diameterTop;
  27860. this.diameterBottom = diameterBottom;
  27861. this.tessellation = tessellation;
  27862. this.subdivisions = subdivisions;
  27863. this.side = side;
  27864. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27865. }
  27866. Cylinder.prototype._regenerateVertexData = function () {
  27867. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27868. };
  27869. Cylinder.prototype.copy = function (id) {
  27870. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27871. };
  27872. Cylinder.prototype.serialize = function () {
  27873. var serializationObject = _super.prototype.serialize.call(this);
  27874. serializationObject.height = this.height;
  27875. serializationObject.diameterTop = this.diameterTop;
  27876. serializationObject.diameterBottom = this.diameterBottom;
  27877. serializationObject.tessellation = this.tessellation;
  27878. return serializationObject;
  27879. };
  27880. Cylinder.Parse = function (parsedCylinder, scene) {
  27881. if (scene.getGeometryByID(parsedCylinder.id)) {
  27882. return null; // null since geometry could be something else than a cylinder...
  27883. }
  27884. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27885. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27886. scene.pushGeometry(cylinder, true);
  27887. return cylinder;
  27888. };
  27889. return Cylinder;
  27890. })(_Primitive);
  27891. Primitives.Cylinder = Cylinder;
  27892. var Torus = (function (_super) {
  27893. __extends(Torus, _super);
  27894. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27895. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27896. this.diameter = diameter;
  27897. this.thickness = thickness;
  27898. this.tessellation = tessellation;
  27899. this.side = side;
  27900. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27901. }
  27902. Torus.prototype._regenerateVertexData = function () {
  27903. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27904. };
  27905. Torus.prototype.copy = function (id) {
  27906. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27907. };
  27908. Torus.prototype.serialize = function () {
  27909. var serializationObject = _super.prototype.serialize.call(this);
  27910. serializationObject.diameter = this.diameter;
  27911. serializationObject.thickness = this.thickness;
  27912. serializationObject.tessellation = this.tessellation;
  27913. return serializationObject;
  27914. };
  27915. Torus.Parse = function (parsedTorus, scene) {
  27916. if (scene.getGeometryByID(parsedTorus.id)) {
  27917. return null; // null since geometry could be something else than a torus...
  27918. }
  27919. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27920. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27921. scene.pushGeometry(torus, true);
  27922. return torus;
  27923. };
  27924. return Torus;
  27925. })(_Primitive);
  27926. Primitives.Torus = Torus;
  27927. var Ground = (function (_super) {
  27928. __extends(Ground, _super);
  27929. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27930. this.width = width;
  27931. this.height = height;
  27932. this.subdivisions = subdivisions;
  27933. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27934. }
  27935. Ground.prototype._regenerateVertexData = function () {
  27936. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27937. };
  27938. Ground.prototype.copy = function (id) {
  27939. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27940. };
  27941. Ground.prototype.serialize = function () {
  27942. var serializationObject = _super.prototype.serialize.call(this);
  27943. serializationObject.width = this.width;
  27944. serializationObject.height = this.height;
  27945. serializationObject.subdivisions = this.subdivisions;
  27946. return serializationObject;
  27947. };
  27948. Ground.Parse = function (parsedGround, scene) {
  27949. if (scene.getGeometryByID(parsedGround.id)) {
  27950. return null; // null since geometry could be something else than a ground...
  27951. }
  27952. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27953. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27954. scene.pushGeometry(ground, true);
  27955. return ground;
  27956. };
  27957. return Ground;
  27958. })(_Primitive);
  27959. Primitives.Ground = Ground;
  27960. var TiledGround = (function (_super) {
  27961. __extends(TiledGround, _super);
  27962. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27963. this.xmin = xmin;
  27964. this.zmin = zmin;
  27965. this.xmax = xmax;
  27966. this.zmax = zmax;
  27967. this.subdivisions = subdivisions;
  27968. this.precision = precision;
  27969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27970. }
  27971. TiledGround.prototype._regenerateVertexData = function () {
  27972. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27973. };
  27974. TiledGround.prototype.copy = function (id) {
  27975. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27976. };
  27977. return TiledGround;
  27978. })(_Primitive);
  27979. Primitives.TiledGround = TiledGround;
  27980. var Plane = (function (_super) {
  27981. __extends(Plane, _super);
  27982. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27984. this.size = size;
  27985. this.side = side;
  27986. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27987. }
  27988. Plane.prototype._regenerateVertexData = function () {
  27989. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27990. };
  27991. Plane.prototype.copy = function (id) {
  27992. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27993. };
  27994. Plane.prototype.serialize = function () {
  27995. var serializationObject = _super.prototype.serialize.call(this);
  27996. serializationObject.size = this.size;
  27997. return serializationObject;
  27998. };
  27999. Plane.Parse = function (parsedPlane, scene) {
  28000. if (scene.getGeometryByID(parsedPlane.id)) {
  28001. return null; // null since geometry could be something else than a ground...
  28002. }
  28003. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28004. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28005. scene.pushGeometry(plane, true);
  28006. return plane;
  28007. };
  28008. return Plane;
  28009. })(_Primitive);
  28010. Primitives.Plane = Plane;
  28011. var TorusKnot = (function (_super) {
  28012. __extends(TorusKnot, _super);
  28013. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28014. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28015. this.radius = radius;
  28016. this.tube = tube;
  28017. this.radialSegments = radialSegments;
  28018. this.tubularSegments = tubularSegments;
  28019. this.p = p;
  28020. this.q = q;
  28021. this.side = side;
  28022. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28023. }
  28024. TorusKnot.prototype._regenerateVertexData = function () {
  28025. 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 });
  28026. };
  28027. TorusKnot.prototype.copy = function (id) {
  28028. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28029. };
  28030. TorusKnot.prototype.serialize = function () {
  28031. var serializationObject = _super.prototype.serialize.call(this);
  28032. serializationObject.radius = this.radius;
  28033. serializationObject.tube = this.tube;
  28034. serializationObject.radialSegments = this.radialSegments;
  28035. serializationObject.tubularSegments = this.tubularSegments;
  28036. serializationObject.p = this.p;
  28037. serializationObject.q = this.q;
  28038. return serializationObject;
  28039. };
  28040. ;
  28041. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28042. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28043. return null; // null since geometry could be something else than a ground...
  28044. }
  28045. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28046. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28047. scene.pushGeometry(torusKnot, true);
  28048. return torusKnot;
  28049. };
  28050. return TorusKnot;
  28051. })(_Primitive);
  28052. Primitives.TorusKnot = TorusKnot;
  28053. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28054. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28055. })(BABYLON || (BABYLON = {}));
  28056. var BABYLON;
  28057. (function (BABYLON) {
  28058. var GroundMesh = (function (_super) {
  28059. __extends(GroundMesh, _super);
  28060. function GroundMesh(name, scene) {
  28061. _super.call(this, name, scene);
  28062. this.generateOctree = false;
  28063. this._worldInverse = new BABYLON.Matrix();
  28064. }
  28065. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28066. get: function () {
  28067. return this._subdivisions;
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28073. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28074. this._subdivisions = chunksCount;
  28075. this.subdivide(this._subdivisions);
  28076. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28077. };
  28078. /**
  28079. * Returns a height (y) value in the Worl system :
  28080. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28081. * Returns the ground y position if (x, z) are outside the ground surface.
  28082. * Not pertinent if the ground is rotated.
  28083. */
  28084. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28085. // express x and y in the ground local system
  28086. x -= this.position.x;
  28087. z -= this.position.z;
  28088. x /= this.scaling.x;
  28089. z /= this.scaling.z;
  28090. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28091. return this.position.y;
  28092. }
  28093. if (!this._heightQuads || this._heightQuads.length == 0) {
  28094. this._computeHeightQuads();
  28095. }
  28096. var facet = this._getFacetAt(x, z);
  28097. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28098. // return y in the World system
  28099. return y * this.scaling.y + this.position.y;
  28100. };
  28101. /**
  28102. * Returns a normalized vector (Vector3) orthogonal to the ground
  28103. * at the ground coordinates (x, z) expressed in the World system.
  28104. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28105. * Not pertinent if the ground is rotated.
  28106. */
  28107. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28108. var normal = new BABYLON.Vector3(0, 1, 0);
  28109. this.getNormalAtCoordinatesToRef(x, z, normal);
  28110. return normal;
  28111. };
  28112. /**
  28113. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28114. * at the ground coordinates (x, z) expressed in the World system.
  28115. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28116. * Not pertinent if the ground is rotated.
  28117. */
  28118. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28119. // express x and y in the ground local system
  28120. x -= this.position.x;
  28121. z -= this.position.z;
  28122. x /= this.scaling.x;
  28123. z /= this.scaling.z;
  28124. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28125. return;
  28126. }
  28127. if (!this._heightQuads || this._heightQuads.length == 0) {
  28128. this._computeHeightQuads();
  28129. }
  28130. var facet = this._getFacetAt(x, z);
  28131. ref.x = facet.x;
  28132. ref.y = facet.y;
  28133. ref.z = facet.z;
  28134. };
  28135. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28136. GroundMesh.prototype._getFacetAt = function (x, z) {
  28137. // retrieve col and row from x, z coordinates in the ground local system
  28138. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28139. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28140. var quad = this._heightQuads[row * this._subdivisions + col];
  28141. var facet;
  28142. if (z < quad.slope.x * x + quad.slope.y) {
  28143. facet = quad.facet1;
  28144. }
  28145. else {
  28146. facet = quad.facet2;
  28147. }
  28148. return facet;
  28149. };
  28150. // Populates the heightMap array with "facet" elements :
  28151. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28152. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28153. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28154. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28155. GroundMesh.prototype._computeHeightQuads = function () {
  28156. this._heightQuads = new Array();
  28157. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28158. var v1 = BABYLON.Vector3.Zero();
  28159. var v2 = BABYLON.Vector3.Zero();
  28160. var v3 = BABYLON.Vector3.Zero();
  28161. var v4 = BABYLON.Vector3.Zero();
  28162. var v1v2 = BABYLON.Vector3.Zero();
  28163. var v1v3 = BABYLON.Vector3.Zero();
  28164. var v1v4 = BABYLON.Vector3.Zero();
  28165. var norm1 = BABYLON.Vector3.Zero();
  28166. var norm2 = BABYLON.Vector3.Zero();
  28167. var i = 0;
  28168. var j = 0;
  28169. var k = 0;
  28170. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28171. var h = 0;
  28172. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28173. var d2 = 0;
  28174. for (var row = 0; row < this._subdivisions; row++) {
  28175. for (var col = 0; col < this._subdivisions; col++) {
  28176. i = col * 3;
  28177. j = row * (this._subdivisions + 1) * 3;
  28178. k = (row + 1) * (this._subdivisions + 1) * 3;
  28179. v1.x = positions[j + i];
  28180. v1.y = positions[j + i + 1];
  28181. v1.z = positions[j + i + 2];
  28182. v2.x = positions[j + i + 3];
  28183. v2.y = positions[j + i + 4];
  28184. v2.z = positions[j + i + 5];
  28185. v3.x = positions[k + i];
  28186. v3.y = positions[k + i + 1];
  28187. v3.z = positions[k + i + 2];
  28188. v4.x = positions[k + i + 3];
  28189. v4.y = positions[k + i + 4];
  28190. v4.z = positions[k + i + 5];
  28191. // 2D slope V1V4
  28192. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28193. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28194. var slope = new BABYLON.Vector2(cd, h);
  28195. // facet equations :
  28196. // we compute each facet normal vector
  28197. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28198. // we compute the value d by applying the equation to v1 which belongs to the plane
  28199. // then we store the facet equation in a Vector4
  28200. v2.subtractToRef(v1, v1v2);
  28201. v3.subtractToRef(v1, v1v3);
  28202. v4.subtractToRef(v1, v1v4);
  28203. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28204. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28205. norm1.normalize();
  28206. norm2.normalize();
  28207. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28208. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28209. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  28210. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  28211. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  28212. this._heightQuads.push(quad);
  28213. }
  28214. }
  28215. };
  28216. return GroundMesh;
  28217. })(BABYLON.Mesh);
  28218. BABYLON.GroundMesh = GroundMesh;
  28219. })(BABYLON || (BABYLON = {}));
  28220. var BABYLON;
  28221. (function (BABYLON) {
  28222. var LinesMesh = (function (_super) {
  28223. __extends(LinesMesh, _super);
  28224. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28225. if (parent === void 0) { parent = null; }
  28226. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28227. this.color = new BABYLON.Color3(1, 1, 1);
  28228. this.alpha = 1;
  28229. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28230. attributes: ["position"],
  28231. uniforms: ["worldViewProjection", "color"],
  28232. needAlphaBlending: true
  28233. });
  28234. }
  28235. Object.defineProperty(LinesMesh.prototype, "material", {
  28236. get: function () {
  28237. return this._colorShader;
  28238. },
  28239. enumerable: true,
  28240. configurable: true
  28241. });
  28242. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28243. get: function () {
  28244. return false;
  28245. },
  28246. enumerable: true,
  28247. configurable: true
  28248. });
  28249. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28250. get: function () {
  28251. return false;
  28252. },
  28253. enumerable: true,
  28254. configurable: true
  28255. });
  28256. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28257. var engine = this.getScene().getEngine();
  28258. var indexToBind = this._geometry.getIndexBuffer();
  28259. // VBOs
  28260. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28261. // Color
  28262. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28263. };
  28264. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28265. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28266. return;
  28267. }
  28268. var engine = this.getScene().getEngine();
  28269. // Draw order
  28270. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28271. };
  28272. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28273. return null;
  28274. };
  28275. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28276. this._colorShader.dispose();
  28277. _super.prototype.dispose.call(this, doNotRecurse);
  28278. };
  28279. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28280. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28281. };
  28282. return LinesMesh;
  28283. })(BABYLON.Mesh);
  28284. BABYLON.LinesMesh = LinesMesh;
  28285. })(BABYLON || (BABYLON = {}));
  28286. var BABYLON;
  28287. (function (BABYLON) {
  28288. var DebugLayer = (function () {
  28289. function DebugLayer(scene) {
  28290. var _this = this;
  28291. this._transformationMatrix = BABYLON.Matrix.Identity();
  28292. this._enabled = false;
  28293. this._labelsEnabled = false;
  28294. this._displayStatistics = true;
  28295. this._displayTree = false;
  28296. this._displayLogs = false;
  28297. this._identityMatrix = BABYLON.Matrix.Identity();
  28298. this.axisRatio = 0.02;
  28299. this.accentColor = "orange";
  28300. this._scene = scene;
  28301. this._syncPositions = function () {
  28302. var engine = _this._scene.getEngine();
  28303. var canvasRect = engine.getRenderingCanvasClientRect();
  28304. if (_this._showUI) {
  28305. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28306. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28307. _this._statsDiv.style.width = "400px";
  28308. _this._statsDiv.style.height = "auto";
  28309. _this._statsSubsetDiv.style.maxHeight = "240px";
  28310. _this._optionsDiv.style.left = "0px";
  28311. _this._optionsDiv.style.top = "10px";
  28312. _this._optionsDiv.style.width = "200px";
  28313. _this._optionsDiv.style.height = "auto";
  28314. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28315. _this._logDiv.style.left = "0px";
  28316. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28317. _this._logDiv.style.width = "600px";
  28318. _this._logDiv.style.height = "160px";
  28319. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28320. _this._treeDiv.style.top = "10px";
  28321. _this._treeDiv.style.width = "300px";
  28322. _this._treeDiv.style.height = "auto";
  28323. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28324. }
  28325. _this._globalDiv.style.left = canvasRect.left + "px";
  28326. _this._globalDiv.style.top = canvasRect.top + "px";
  28327. _this._drawingCanvas.style.left = "0px";
  28328. _this._drawingCanvas.style.top = "0px";
  28329. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28330. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28331. var devicePixelRatio = window.devicePixelRatio || 1;
  28332. var context = _this._drawingContext;
  28333. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28334. context.mozBackingStorePixelRatio ||
  28335. context.msBackingStorePixelRatio ||
  28336. context.oBackingStorePixelRatio ||
  28337. context.backingStorePixelRatio || 1;
  28338. _this._ratio = devicePixelRatio / backingStoreRatio;
  28339. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28340. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28341. };
  28342. this._onCanvasClick = function (evt) {
  28343. _this._clickPosition = {
  28344. x: evt.clientX * _this._ratio,
  28345. y: evt.clientY * _this._ratio
  28346. };
  28347. };
  28348. this._syncUI = function () {
  28349. if (_this._showUI) {
  28350. if (_this._displayStatistics) {
  28351. _this._displayStats();
  28352. _this._statsDiv.style.display = "";
  28353. }
  28354. else {
  28355. _this._statsDiv.style.display = "none";
  28356. }
  28357. if (_this._displayLogs) {
  28358. _this._logDiv.style.display = "";
  28359. }
  28360. else {
  28361. _this._logDiv.style.display = "none";
  28362. }
  28363. if (_this._displayTree) {
  28364. _this._treeDiv.style.display = "";
  28365. if (_this._needToRefreshMeshesTree) {
  28366. _this._needToRefreshMeshesTree = false;
  28367. _this._refreshMeshesTreeContent();
  28368. }
  28369. }
  28370. else {
  28371. _this._treeDiv.style.display = "none";
  28372. }
  28373. }
  28374. };
  28375. this._syncData = function () {
  28376. if (_this._labelsEnabled || !_this._showUI) {
  28377. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28378. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28379. var engine = _this._scene.getEngine();
  28380. var viewport = _this._camera.viewport;
  28381. var globalViewport = viewport.toGlobal(engine);
  28382. // Meshes
  28383. var meshes = _this._camera.getActiveMeshes();
  28384. var index;
  28385. var projectedPosition;
  28386. for (index = 0; index < meshes.length; index++) {
  28387. var mesh = meshes.data[index];
  28388. var position = mesh.getBoundingInfo().boundingSphere.center;
  28389. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28390. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28391. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28392. }
  28393. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28394. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28395. }
  28396. }
  28397. // Cameras
  28398. var cameras = _this._scene.cameras;
  28399. for (index = 0; index < cameras.length; index++) {
  28400. var camera = cameras[index];
  28401. if (camera === _this._camera) {
  28402. continue;
  28403. }
  28404. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28405. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28406. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28407. _this._camera.detachControl(engine.getRenderingCanvas());
  28408. _this._camera = camera;
  28409. _this._camera.attachControl(engine.getRenderingCanvas());
  28410. }, function () { return "purple"; });
  28411. }
  28412. }
  28413. // Lights
  28414. var lights = _this._scene.lights;
  28415. for (index = 0; index < lights.length; index++) {
  28416. var light = lights[index];
  28417. if (light.position) {
  28418. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28419. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28420. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28421. light.setEnabled(!light.isEnabled());
  28422. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28423. }
  28424. }
  28425. }
  28426. }
  28427. _this._clickPosition = undefined;
  28428. };
  28429. }
  28430. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28431. while (this._treeSubsetDiv.hasChildNodes()) {
  28432. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28433. }
  28434. // Add meshes
  28435. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28436. sortedArray.sort(function (a, b) {
  28437. if (a.name === b.name) {
  28438. return 0;
  28439. }
  28440. return (a.name > b.name) ? 1 : -1;
  28441. });
  28442. for (var index = 0; index < sortedArray.length; index++) {
  28443. var mesh = sortedArray[index];
  28444. if (!mesh.isEnabled()) {
  28445. continue;
  28446. }
  28447. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28448. m.isVisible = element.checked;
  28449. }, mesh);
  28450. }
  28451. };
  28452. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28453. this._drawingContext.beginPath();
  28454. this._drawingContext.moveTo(zero.x, zero.y);
  28455. this._drawingContext.lineTo(unit.x, unit.y);
  28456. this._drawingContext.strokeStyle = color;
  28457. this._drawingContext.lineWidth = 4;
  28458. this._drawingContext.stroke();
  28459. this._drawingContext.font = "normal 14px Segoe UI";
  28460. this._drawingContext.fillStyle = color;
  28461. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28462. };
  28463. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28464. var position = mesh.getBoundingInfo().boundingSphere.center;
  28465. var worldMatrix = mesh.getWorldMatrix();
  28466. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28467. var unit = (unprojectedVector.subtract(position)).length();
  28468. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28469. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28470. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28471. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28472. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28473. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28474. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28475. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28476. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28477. };
  28478. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28479. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28480. this._drawingContext.font = "normal 12px Segoe UI";
  28481. var textMetrics = this._drawingContext.measureText(text);
  28482. var centerX = projectedPosition.x - textMetrics.width / 2;
  28483. var centerY = projectedPosition.y;
  28484. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28485. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28486. onClick();
  28487. }
  28488. this._drawingContext.beginPath();
  28489. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28490. this._drawingContext.fillStyle = getFillStyle();
  28491. this._drawingContext.globalAlpha = 0.5;
  28492. this._drawingContext.fill();
  28493. this._drawingContext.globalAlpha = 1.0;
  28494. this._drawingContext.strokeStyle = '#FFFFFF';
  28495. this._drawingContext.lineWidth = 1;
  28496. this._drawingContext.stroke();
  28497. this._drawingContext.fillStyle = "#FFFFFF";
  28498. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28499. this._drawingContext.beginPath();
  28500. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28501. this._drawingContext.fill();
  28502. }
  28503. };
  28504. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28505. if (!this._clickPosition) {
  28506. return false;
  28507. }
  28508. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28509. return false;
  28510. }
  28511. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28512. return false;
  28513. }
  28514. return true;
  28515. };
  28516. DebugLayer.prototype.isVisible = function () {
  28517. return this._enabled;
  28518. };
  28519. DebugLayer.prototype.hide = function () {
  28520. if (!this._enabled) {
  28521. return;
  28522. }
  28523. this._enabled = false;
  28524. var engine = this._scene.getEngine();
  28525. this._scene.unregisterBeforeRender(this._syncData);
  28526. this._scene.unregisterAfterRender(this._syncUI);
  28527. this._rootElement.removeChild(this._globalDiv);
  28528. this._scene.forceShowBoundingBoxes = false;
  28529. this._scene.forceWireframe = false;
  28530. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28531. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28532. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28533. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28534. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28535. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28536. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28537. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28538. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28539. this._scene.shadowsEnabled = true;
  28540. this._scene.particlesEnabled = true;
  28541. this._scene.postProcessesEnabled = true;
  28542. this._scene.collisionsEnabled = true;
  28543. this._scene.lightsEnabled = true;
  28544. this._scene.texturesEnabled = true;
  28545. this._scene.lensFlaresEnabled = true;
  28546. this._scene.proceduralTexturesEnabled = true;
  28547. this._scene.renderTargetsEnabled = true;
  28548. this._scene.probesEnabled = true;
  28549. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28550. };
  28551. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28552. if (showUI === void 0) { showUI = true; }
  28553. if (camera === void 0) { camera = null; }
  28554. if (rootElement === void 0) { rootElement = null; }
  28555. if (this._enabled) {
  28556. return;
  28557. }
  28558. this._enabled = true;
  28559. if (camera) {
  28560. this._camera = camera;
  28561. }
  28562. else {
  28563. this._camera = this._scene.activeCamera;
  28564. }
  28565. this._showUI = showUI;
  28566. var engine = this._scene.getEngine();
  28567. this._globalDiv = document.createElement("div");
  28568. this._rootElement = rootElement || document.body;
  28569. this._rootElement.appendChild(this._globalDiv);
  28570. this._generateDOMelements();
  28571. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28572. this._syncPositions();
  28573. this._scene.registerBeforeRender(this._syncData);
  28574. this._scene.registerAfterRender(this._syncUI);
  28575. };
  28576. DebugLayer.prototype._clearLabels = function () {
  28577. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28578. for (var index = 0; index < this._scene.meshes.length; index++) {
  28579. var mesh = this._scene.meshes[index];
  28580. mesh.renderOverlay = false;
  28581. }
  28582. };
  28583. DebugLayer.prototype._generateheader = function (root, text) {
  28584. var header = document.createElement("div");
  28585. header.innerHTML = text + "&nbsp;";
  28586. header.style.textAlign = "right";
  28587. header.style.width = "100%";
  28588. header.style.color = "white";
  28589. header.style.backgroundColor = "Black";
  28590. header.style.padding = "5px 5px 4px 0px";
  28591. header.style.marginLeft = "-5px";
  28592. header.style.fontWeight = "bold";
  28593. root.appendChild(header);
  28594. };
  28595. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28596. var label = document.createElement("label");
  28597. label.innerHTML = title;
  28598. label.style.color = color;
  28599. root.appendChild(label);
  28600. root.appendChild(document.createElement("br"));
  28601. };
  28602. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28603. if (tag === void 0) { tag = null; }
  28604. var label = document.createElement("label");
  28605. var boundingBoxesCheckbox = document.createElement("input");
  28606. boundingBoxesCheckbox.type = "checkbox";
  28607. boundingBoxesCheckbox.checked = initialState;
  28608. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28609. task(evt.target, tag);
  28610. });
  28611. label.appendChild(boundingBoxesCheckbox);
  28612. var container = document.createElement("span");
  28613. var leftPart = document.createElement("span");
  28614. var rightPart = document.createElement("span");
  28615. rightPart.style.cssFloat = "right";
  28616. leftPart.innerHTML = leftTitle;
  28617. rightPart.innerHTML = rightTitle;
  28618. rightPart.style.fontSize = "12px";
  28619. rightPart.style.maxWidth = "200px";
  28620. container.appendChild(leftPart);
  28621. container.appendChild(rightPart);
  28622. label.appendChild(container);
  28623. root.appendChild(label);
  28624. root.appendChild(document.createElement("br"));
  28625. };
  28626. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28627. if (tag === void 0) { tag = null; }
  28628. var label = document.createElement("label");
  28629. var checkBox = document.createElement("input");
  28630. checkBox.type = "checkbox";
  28631. checkBox.checked = initialState;
  28632. checkBox.addEventListener("change", function (evt) {
  28633. task(evt.target, tag);
  28634. });
  28635. label.appendChild(checkBox);
  28636. label.appendChild(document.createTextNode(title));
  28637. root.appendChild(label);
  28638. root.appendChild(document.createElement("br"));
  28639. };
  28640. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28641. if (tag === void 0) { tag = null; }
  28642. var button = document.createElement("button");
  28643. button.innerHTML = title;
  28644. button.style.height = "24px";
  28645. button.style.width = "150px";
  28646. button.style.marginBottom = "5px";
  28647. button.style.color = "#444444";
  28648. button.style.border = "1px solid white";
  28649. button.className = "debugLayerButton";
  28650. button.addEventListener("click", function (evt) {
  28651. task(evt.target, tag);
  28652. });
  28653. root.appendChild(button);
  28654. root.appendChild(document.createElement("br"));
  28655. };
  28656. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28657. if (tag === void 0) { tag = null; }
  28658. var label = document.createElement("label");
  28659. var boundingBoxesRadio = document.createElement("input");
  28660. boundingBoxesRadio.type = "radio";
  28661. boundingBoxesRadio.name = name;
  28662. boundingBoxesRadio.checked = initialState;
  28663. boundingBoxesRadio.addEventListener("change", function (evt) {
  28664. task(evt.target, tag);
  28665. });
  28666. label.appendChild(boundingBoxesRadio);
  28667. label.appendChild(document.createTextNode(title));
  28668. root.appendChild(label);
  28669. root.appendChild(document.createElement("br"));
  28670. };
  28671. DebugLayer.prototype._generateDOMelements = function () {
  28672. var _this = this;
  28673. this._globalDiv.id = "DebugLayer";
  28674. this._globalDiv.style.position = "absolute";
  28675. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28676. this._globalDiv.style.fontSize = "14px";
  28677. this._globalDiv.style.color = "white";
  28678. // Drawing canvas
  28679. this._drawingCanvas = document.createElement("canvas");
  28680. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28681. this._drawingCanvas.style.position = "absolute";
  28682. this._drawingCanvas.style.pointerEvents = "none";
  28683. this._drawingCanvas.style.backgroundColor = "transparent";
  28684. this._drawingContext = this._drawingCanvas.getContext("2d");
  28685. this._globalDiv.appendChild(this._drawingCanvas);
  28686. if (this._showUI) {
  28687. var background = "rgba(128, 128, 128, 0.4)";
  28688. var border = "rgb(180, 180, 180) solid 1px";
  28689. // Stats
  28690. this._statsDiv = document.createElement("div");
  28691. this._statsDiv.id = "DebugLayerStats";
  28692. this._statsDiv.style.border = border;
  28693. this._statsDiv.style.position = "absolute";
  28694. this._statsDiv.style.background = background;
  28695. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28696. this._generateheader(this._statsDiv, "STATISTICS");
  28697. this._statsSubsetDiv = document.createElement("div");
  28698. this._statsSubsetDiv.style.paddingTop = "5px";
  28699. this._statsSubsetDiv.style.paddingBottom = "5px";
  28700. this._statsSubsetDiv.style.overflowY = "auto";
  28701. this._statsDiv.appendChild(this._statsSubsetDiv);
  28702. // Tree
  28703. this._treeDiv = document.createElement("div");
  28704. this._treeDiv.id = "DebugLayerTree";
  28705. this._treeDiv.style.border = border;
  28706. this._treeDiv.style.position = "absolute";
  28707. this._treeDiv.style.background = background;
  28708. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28709. this._treeDiv.style.display = "none";
  28710. this._generateheader(this._treeDiv, "MESHES TREE");
  28711. this._treeSubsetDiv = document.createElement("div");
  28712. this._treeSubsetDiv.style.paddingTop = "5px";
  28713. this._treeSubsetDiv.style.paddingRight = "5px";
  28714. this._treeSubsetDiv.style.overflowY = "auto";
  28715. this._treeSubsetDiv.style.maxHeight = "300px";
  28716. this._treeDiv.appendChild(this._treeSubsetDiv);
  28717. this._needToRefreshMeshesTree = true;
  28718. // Logs
  28719. this._logDiv = document.createElement("div");
  28720. this._logDiv.style.border = border;
  28721. this._logDiv.id = "DebugLayerLogs";
  28722. this._logDiv.style.position = "absolute";
  28723. this._logDiv.style.background = background;
  28724. this._logDiv.style.padding = "0px 0px 0px 5px";
  28725. this._logDiv.style.display = "none";
  28726. this._generateheader(this._logDiv, "LOGS");
  28727. this._logSubsetDiv = document.createElement("div");
  28728. this._logSubsetDiv.style.height = "127px";
  28729. this._logSubsetDiv.style.paddingTop = "5px";
  28730. this._logSubsetDiv.style.overflowY = "auto";
  28731. this._logSubsetDiv.style.fontSize = "12px";
  28732. this._logSubsetDiv.style.fontFamily = "consolas";
  28733. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28734. this._logDiv.appendChild(this._logSubsetDiv);
  28735. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28736. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28737. };
  28738. // Options
  28739. this._optionsDiv = document.createElement("div");
  28740. this._optionsDiv.id = "DebugLayerOptions";
  28741. this._optionsDiv.style.border = border;
  28742. this._optionsDiv.style.position = "absolute";
  28743. this._optionsDiv.style.background = background;
  28744. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28745. this._optionsDiv.style.overflowY = "auto";
  28746. this._generateheader(this._optionsDiv, "OPTIONS");
  28747. this._optionsSubsetDiv = document.createElement("div");
  28748. this._optionsSubsetDiv.style.paddingTop = "5px";
  28749. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28750. this._optionsSubsetDiv.style.overflowY = "auto";
  28751. this._optionsSubsetDiv.style.maxHeight = "200px";
  28752. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28753. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28754. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28755. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28756. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28757. _this._displayTree = element.checked;
  28758. _this._needToRefreshMeshesTree = true;
  28759. });
  28760. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28761. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28762. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28763. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28764. _this._labelsEnabled = element.checked;
  28765. if (!_this._labelsEnabled) {
  28766. _this._clearLabels();
  28767. }
  28768. });
  28769. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28770. if (element.checked) {
  28771. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28772. }
  28773. else {
  28774. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28775. }
  28776. });
  28777. ;
  28778. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28779. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28780. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28781. if (element.checked) {
  28782. _this._scene.forceWireframe = false;
  28783. _this._scene.forcePointsCloud = false;
  28784. }
  28785. });
  28786. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28787. if (element.checked) {
  28788. _this._scene.forceWireframe = true;
  28789. _this._scene.forcePointsCloud = false;
  28790. }
  28791. });
  28792. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28793. if (element.checked) {
  28794. _this._scene.forceWireframe = false;
  28795. _this._scene.forcePointsCloud = true;
  28796. }
  28797. });
  28798. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28799. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28800. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28801. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28802. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28803. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28804. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28805. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28806. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28807. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  28808. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  28809. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28810. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28811. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28812. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28813. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28814. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28815. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28816. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28817. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28818. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28819. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28820. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28821. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28822. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28823. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28824. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28825. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28826. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28827. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28828. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28829. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28830. if (element.checked) {
  28831. _this._scene.headphone = true;
  28832. }
  28833. });
  28834. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28835. if (element.checked) {
  28836. _this._scene.headphone = false;
  28837. }
  28838. });
  28839. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28840. _this._scene.audioEnabled = !element.checked;
  28841. });
  28842. }
  28843. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28844. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28845. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28846. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28847. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28848. if (_this._camera) {
  28849. console.log(_this._camera);
  28850. }
  28851. else {
  28852. console.warn("No camera defined, or debug layer created before camera creation!");
  28853. }
  28854. });
  28855. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28856. this._globalDiv.appendChild(this._statsDiv);
  28857. this._globalDiv.appendChild(this._logDiv);
  28858. this._globalDiv.appendChild(this._optionsDiv);
  28859. this._globalDiv.appendChild(this._treeDiv);
  28860. }
  28861. };
  28862. DebugLayer.prototype._displayStats = function () {
  28863. var scene = this._scene;
  28864. var engine = scene.getEngine();
  28865. var glInfo = engine.getGlInfo();
  28866. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28867. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28868. + "<b>Count</b><br>"
  28869. + "Total meshes: " + scene.meshes.length + "<br>"
  28870. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28871. + "Total materials: " + scene.materials.length + "<br>"
  28872. + "Total textures: " + scene.textures.length + "<br>"
  28873. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28874. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28875. + "Active bones: " + scene.getActiveBones() + "<br>"
  28876. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28877. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  28878. + "<b>Duration</b><br>"
  28879. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28880. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28881. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28882. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28883. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28884. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28885. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  28886. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  28887. + "</div>"
  28888. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28889. + "<b>Extensions</b><br>"
  28890. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28891. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28892. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28893. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  28894. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28895. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28896. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  28897. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  28898. + "</div><br>"
  28899. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28900. + "<b>Caps.</b><br>"
  28901. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28902. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28903. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  28904. + "<b>Info</b><br>"
  28905. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  28906. + glInfo.version + "<br>"
  28907. + "</div><br>"
  28908. + glInfo.renderer + "<br>";
  28909. if (this.customStatsFunction) {
  28910. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28911. }
  28912. };
  28913. return DebugLayer;
  28914. })();
  28915. BABYLON.DebugLayer = DebugLayer;
  28916. })(BABYLON || (BABYLON = {}));
  28917. var BABYLON;
  28918. (function (BABYLON) {
  28919. var DefaultLoadingScreen = (function () {
  28920. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28921. var _this = this;
  28922. if (_loadingText === void 0) { _loadingText = ""; }
  28923. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28924. this._renderingCanvas = _renderingCanvas;
  28925. this._loadingText = _loadingText;
  28926. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28927. // Resize
  28928. this._resizeLoadingUI = function () {
  28929. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28930. _this._loadingDiv.style.position = "absolute";
  28931. _this._loadingDiv.style.left = canvasRect.left + "px";
  28932. _this._loadingDiv.style.top = canvasRect.top + "px";
  28933. _this._loadingDiv.style.width = canvasRect.width + "px";
  28934. _this._loadingDiv.style.height = canvasRect.height + "px";
  28935. };
  28936. }
  28937. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28938. var _this = this;
  28939. if (this._loadingDiv) {
  28940. // Do not add a loading screen if there is already one
  28941. return;
  28942. }
  28943. this._loadingDiv = document.createElement("div");
  28944. this._loadingDiv.id = "babylonjsLoadingDiv";
  28945. this._loadingDiv.style.opacity = "0";
  28946. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28947. // Loading text
  28948. this._loadingTextDiv = document.createElement("div");
  28949. this._loadingTextDiv.style.position = "absolute";
  28950. this._loadingTextDiv.style.left = "0";
  28951. this._loadingTextDiv.style.top = "50%";
  28952. this._loadingTextDiv.style.marginTop = "80px";
  28953. this._loadingTextDiv.style.width = "100%";
  28954. this._loadingTextDiv.style.height = "20px";
  28955. this._loadingTextDiv.style.fontFamily = "Arial";
  28956. this._loadingTextDiv.style.fontSize = "14px";
  28957. this._loadingTextDiv.style.color = "white";
  28958. this._loadingTextDiv.style.textAlign = "center";
  28959. this._loadingTextDiv.innerHTML = "Loading";
  28960. this._loadingDiv.appendChild(this._loadingTextDiv);
  28961. //set the predefined text
  28962. this._loadingTextDiv.innerHTML = this._loadingText;
  28963. // Loading img
  28964. var imgBack = new Image();
  28965. 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==";
  28966. imgBack.style.position = "absolute";
  28967. imgBack.style.left = "50%";
  28968. imgBack.style.top = "50%";
  28969. imgBack.style.marginLeft = "-50px";
  28970. imgBack.style.marginTop = "-50px";
  28971. imgBack.style.transition = "transform 1.0s ease";
  28972. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28973. var deg = 360;
  28974. var onTransitionEnd = function () {
  28975. deg += 360;
  28976. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28977. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28978. };
  28979. imgBack.addEventListener("transitionend", onTransitionEnd);
  28980. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28981. this._loadingDiv.appendChild(imgBack);
  28982. // front image
  28983. var imgFront = new Image();
  28984. 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=";
  28985. imgFront.style.position = "absolute";
  28986. imgFront.style.left = "50%";
  28987. imgFront.style.top = "50%";
  28988. imgFront.style.marginLeft = "-50px";
  28989. imgFront.style.marginTop = "-50px";
  28990. this._loadingDiv.appendChild(imgFront);
  28991. this._resizeLoadingUI();
  28992. window.addEventListener("resize", this._resizeLoadingUI);
  28993. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28994. document.body.appendChild(this._loadingDiv);
  28995. setTimeout(function () {
  28996. _this._loadingDiv.style.opacity = "1";
  28997. imgBack.style.transform = "rotateZ(360deg)";
  28998. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28999. }, 0);
  29000. };
  29001. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29002. var _this = this;
  29003. if (!this._loadingDiv) {
  29004. return;
  29005. }
  29006. var onTransitionEnd = function () {
  29007. if (!_this._loadingDiv) {
  29008. return;
  29009. }
  29010. document.body.removeChild(_this._loadingDiv);
  29011. window.removeEventListener("resize", _this._resizeLoadingUI);
  29012. _this._loadingDiv = null;
  29013. };
  29014. this._loadingDiv.style.opacity = "0";
  29015. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29016. };
  29017. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29018. set: function (text) {
  29019. this._loadingText = text;
  29020. if (this._loadingTextDiv) {
  29021. this._loadingTextDiv.innerHTML = this._loadingText;
  29022. }
  29023. },
  29024. enumerable: true,
  29025. configurable: true
  29026. });
  29027. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29028. get: function () {
  29029. return this._loadingDivBackgroundColor;
  29030. },
  29031. set: function (color) {
  29032. this._loadingDivBackgroundColor = color;
  29033. if (!this._loadingDiv) {
  29034. return;
  29035. }
  29036. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29037. },
  29038. enumerable: true,
  29039. configurable: true
  29040. });
  29041. return DefaultLoadingScreen;
  29042. })();
  29043. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29044. })(BABYLON || (BABYLON = {}));
  29045. var BABYLON;
  29046. (function (BABYLON) {
  29047. var SIMDVector3 = (function () {
  29048. function SIMDVector3() {
  29049. }
  29050. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29051. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29052. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29053. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29054. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29055. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29056. 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));
  29057. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29058. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29059. };
  29060. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29061. var v0 = SIMD.float32x4.splat(x);
  29062. var v1 = SIMD.float32x4.splat(y);
  29063. var v2 = SIMD.float32x4.splat(z);
  29064. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29065. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29066. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29067. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29068. 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));
  29069. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29070. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29071. };
  29072. return SIMDVector3;
  29073. })();
  29074. BABYLON.SIMDVector3 = SIMDVector3;
  29075. var SIMDMatrix = (function () {
  29076. function SIMDMatrix() {
  29077. }
  29078. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29079. if (offset === void 0) { offset = 0; }
  29080. var tm = this.m;
  29081. var om = other.m;
  29082. var om0 = SIMD.float32x4.load(om, 0);
  29083. var om1 = SIMD.float32x4.load(om, 4);
  29084. var om2 = SIMD.float32x4.load(om, 8);
  29085. var om3 = SIMD.float32x4.load(om, 12);
  29086. var tm0 = SIMD.float32x4.load(tm, 0);
  29087. 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)))));
  29088. var tm1 = SIMD.float32x4.load(tm, 4);
  29089. 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)))));
  29090. var tm2 = SIMD.float32x4.load(tm, 8);
  29091. 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)))));
  29092. var tm3 = SIMD.float32x4.load(tm, 12);
  29093. 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)))));
  29094. };
  29095. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29096. var src = this.m;
  29097. var dest = other.m;
  29098. var row0, row1, row2, row3;
  29099. var tmp1;
  29100. var minor0, minor1, minor2, minor3;
  29101. var det;
  29102. // Load the 4 rows
  29103. var src0 = SIMD.float32x4.load(src, 0);
  29104. var src1 = SIMD.float32x4.load(src, 4);
  29105. var src2 = SIMD.float32x4.load(src, 8);
  29106. var src3 = SIMD.float32x4.load(src, 12);
  29107. // Transpose the source matrix. Sort of. Not a true transpose operation
  29108. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29109. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29110. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29111. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29112. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29113. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29114. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29115. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29116. // This is a true transposition, but it will lead to an incorrect result
  29117. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29118. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29119. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29120. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29121. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29122. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29123. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29124. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29125. // ----
  29126. tmp1 = SIMD.float32x4.mul(row2, row3);
  29127. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29128. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29129. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29130. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29131. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29132. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29133. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29134. // ----
  29135. tmp1 = SIMD.float32x4.mul(row1, row2);
  29136. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29137. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29138. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29139. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29140. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29141. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29142. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29143. // ----
  29144. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29145. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29146. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29147. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29148. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29149. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29150. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29151. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29152. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29153. // ----
  29154. tmp1 = SIMD.float32x4.mul(row0, row1);
  29155. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29156. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29157. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29158. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29159. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29160. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29161. // ----
  29162. tmp1 = SIMD.float32x4.mul(row0, row3);
  29163. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29164. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29165. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29166. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29167. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29168. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29169. // ----
  29170. tmp1 = SIMD.float32x4.mul(row0, row2);
  29171. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29172. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29173. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29174. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29175. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29176. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29177. // Compute determinant
  29178. det = SIMD.float32x4.mul(row0, minor0);
  29179. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29180. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29181. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29182. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29183. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29184. // These shuffles aren't necessary if the faulty transposition is done
  29185. // up at the top of this function.
  29186. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29187. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29188. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29189. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29190. // Compute final values by multiplying with 1/det
  29191. minor0 = SIMD.float32x4.mul(det, minor0);
  29192. minor1 = SIMD.float32x4.mul(det, minor1);
  29193. minor2 = SIMD.float32x4.mul(det, minor2);
  29194. minor3 = SIMD.float32x4.mul(det, minor3);
  29195. SIMD.float32x4.store(dest, 0, minor0);
  29196. SIMD.float32x4.store(dest, 4, minor1);
  29197. SIMD.float32x4.store(dest, 8, minor2);
  29198. SIMD.float32x4.store(dest, 12, minor3);
  29199. return this;
  29200. };
  29201. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29202. var out = result.m;
  29203. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29204. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29205. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29206. // cc.kmVec3Subtract(f, pCenter, pEye);
  29207. var f = SIMD.float32x4.sub(center, eye);
  29208. // cc.kmVec3Normalize(f, f);
  29209. var tmp = SIMD.float32x4.mul(f, f);
  29210. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29211. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29212. // cc.kmVec3Assign(up, pUp);
  29213. // cc.kmVec3Normalize(up, up);
  29214. tmp = SIMD.float32x4.mul(up, up);
  29215. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29216. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29217. // cc.kmVec3Cross(s, f, up);
  29218. 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)));
  29219. // cc.kmVec3Normalize(s, s);
  29220. tmp = SIMD.float32x4.mul(s, s);
  29221. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29222. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29223. // cc.kmVec3Cross(u, s, f);
  29224. 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)));
  29225. // cc.kmVec3Normalize(s, s);
  29226. tmp = SIMD.float32x4.mul(s, s);
  29227. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29228. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29229. var zero = SIMD.float32x4.splat(0.0);
  29230. s = SIMD.float32x4.neg(s);
  29231. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29232. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29233. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29234. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29235. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29236. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29237. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29238. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29239. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29240. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29241. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29242. var b3 = SIMD.float32x4.neg(eye);
  29243. b3 = SIMD.float32x4.withW(b3, 1.0);
  29244. 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)))));
  29245. 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)))));
  29246. 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)))));
  29247. 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)))));
  29248. };
  29249. return SIMDMatrix;
  29250. })();
  29251. BABYLON.SIMDMatrix = SIMDMatrix;
  29252. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29253. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29254. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29255. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29256. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29257. var SIMDHelper = (function () {
  29258. function SIMDHelper() {
  29259. }
  29260. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29261. get: function () {
  29262. return SIMDHelper._isEnabled;
  29263. },
  29264. enumerable: true,
  29265. configurable: true
  29266. });
  29267. SIMDHelper.DisableSIMD = function () {
  29268. // Replace functions
  29269. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29270. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29271. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29272. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29274. SIMDHelper._isEnabled = false;
  29275. };
  29276. SIMDHelper.EnableSIMD = function () {
  29277. if (window.SIMD === undefined) {
  29278. return;
  29279. }
  29280. // Replace functions
  29281. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29282. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29283. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29284. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29285. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29286. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29287. get: function () { return this._data[0]; },
  29288. set: function (value) {
  29289. if (!this._data) {
  29290. this._data = new Float32Array(3);
  29291. }
  29292. this._data[0] = value;
  29293. }
  29294. });
  29295. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29296. get: function () { return this._data[1]; },
  29297. set: function (value) {
  29298. this._data[1] = value;
  29299. }
  29300. });
  29301. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29302. get: function () { return this._data[2]; },
  29303. set: function (value) {
  29304. this._data[2] = value;
  29305. }
  29306. });
  29307. SIMDHelper._isEnabled = true;
  29308. };
  29309. SIMDHelper._isEnabled = false;
  29310. return SIMDHelper;
  29311. })();
  29312. BABYLON.SIMDHelper = SIMDHelper;
  29313. })(BABYLON || (BABYLON = {}));
  29314. var BABYLON;
  29315. (function (BABYLON) {
  29316. var ShaderMaterial = (function (_super) {
  29317. __extends(ShaderMaterial, _super);
  29318. function ShaderMaterial(name, scene, shaderPath, options) {
  29319. _super.call(this, name, scene);
  29320. this._textures = {};
  29321. this._floats = {};
  29322. this._floatsArrays = {};
  29323. this._colors3 = {};
  29324. this._colors4 = {};
  29325. this._vectors2 = {};
  29326. this._vectors3 = {};
  29327. this._vectors4 = {};
  29328. this._matrices = {};
  29329. this._matrices3x3 = {};
  29330. this._matrices2x2 = {};
  29331. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29332. this._shaderPath = shaderPath;
  29333. options.needAlphaBlending = options.needAlphaBlending || false;
  29334. options.needAlphaTesting = options.needAlphaTesting || false;
  29335. options.attributes = options.attributes || ["position", "normal", "uv"];
  29336. options.uniforms = options.uniforms || ["worldViewProjection"];
  29337. options.samplers = options.samplers || [];
  29338. options.defines = options.defines || [];
  29339. this._options = options;
  29340. }
  29341. ShaderMaterial.prototype.needAlphaBlending = function () {
  29342. return this._options.needAlphaBlending;
  29343. };
  29344. ShaderMaterial.prototype.needAlphaTesting = function () {
  29345. return this._options.needAlphaTesting;
  29346. };
  29347. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29348. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29349. this._options.uniforms.push(uniformName);
  29350. }
  29351. };
  29352. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29353. if (this._options.samplers.indexOf(name) === -1) {
  29354. this._options.samplers.push(name);
  29355. }
  29356. this._textures[name] = texture;
  29357. return this;
  29358. };
  29359. ShaderMaterial.prototype.setFloat = function (name, value) {
  29360. this._checkUniform(name);
  29361. this._floats[name] = value;
  29362. return this;
  29363. };
  29364. ShaderMaterial.prototype.setFloats = function (name, value) {
  29365. this._checkUniform(name);
  29366. this._floatsArrays[name] = value;
  29367. return this;
  29368. };
  29369. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29370. this._checkUniform(name);
  29371. this._colors3[name] = value;
  29372. return this;
  29373. };
  29374. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29375. this._checkUniform(name);
  29376. this._colors4[name] = value;
  29377. return this;
  29378. };
  29379. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29380. this._checkUniform(name);
  29381. this._vectors2[name] = value;
  29382. return this;
  29383. };
  29384. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29385. this._checkUniform(name);
  29386. this._vectors3[name] = value;
  29387. return this;
  29388. };
  29389. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29390. this._checkUniform(name);
  29391. this._vectors4[name] = value;
  29392. return this;
  29393. };
  29394. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29395. this._checkUniform(name);
  29396. this._matrices[name] = value;
  29397. return this;
  29398. };
  29399. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29400. this._checkUniform(name);
  29401. this._matrices3x3[name] = value;
  29402. return this;
  29403. };
  29404. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29405. this._checkUniform(name);
  29406. this._matrices2x2[name] = value;
  29407. return this;
  29408. };
  29409. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  29410. var scene = this.getScene();
  29411. var engine = scene.getEngine();
  29412. if (!this.checkReadyOnEveryCall) {
  29413. if (this._renderId === scene.getRenderId()) {
  29414. return true;
  29415. }
  29416. }
  29417. // Instances
  29418. var defines = [];
  29419. var fallbacks = new BABYLON.EffectFallbacks();
  29420. if (useInstances) {
  29421. defines.push("#define INSTANCES");
  29422. }
  29423. for (var index = 0; index < this._options.defines.length; index++) {
  29424. defines.push(this._options.defines[index]);
  29425. }
  29426. // Bones
  29427. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29428. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  29429. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29430. fallbacks.addCPUSkinningFallback(0, mesh);
  29431. }
  29432. // Alpha test
  29433. if (engine.getAlphaTesting()) {
  29434. defines.push("#define ALPHATEST");
  29435. }
  29436. var previousEffect = this._effect;
  29437. var join = defines.join("\n");
  29438. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  29439. if (!this._effect.isReady()) {
  29440. return false;
  29441. }
  29442. if (previousEffect !== this._effect) {
  29443. scene.resetCachedMaterial();
  29444. }
  29445. this._renderId = scene.getRenderId();
  29446. return true;
  29447. };
  29448. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29449. var scene = this.getScene();
  29450. if (this._options.uniforms.indexOf("world") !== -1) {
  29451. this._effect.setMatrix("world", world);
  29452. }
  29453. if (this._options.uniforms.indexOf("worldView") !== -1) {
  29454. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  29455. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  29456. }
  29457. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  29458. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  29459. }
  29460. };
  29461. ShaderMaterial.prototype.bind = function (world, mesh) {
  29462. // Std values
  29463. this.bindOnlyWorldMatrix(world);
  29464. if (this.getScene().getCachedMaterial() !== this) {
  29465. if (this._options.uniforms.indexOf("view") !== -1) {
  29466. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  29467. }
  29468. if (this._options.uniforms.indexOf("projection") !== -1) {
  29469. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  29470. }
  29471. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  29472. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29473. }
  29474. // Bones
  29475. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29476. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  29477. }
  29478. // Texture
  29479. for (var name in this._textures) {
  29480. this._effect.setTexture(name, this._textures[name]);
  29481. }
  29482. // Float
  29483. for (name in this._floats) {
  29484. this._effect.setFloat(name, this._floats[name]);
  29485. }
  29486. // Float s
  29487. for (name in this._floatsArrays) {
  29488. this._effect.setArray(name, this._floatsArrays[name]);
  29489. }
  29490. // Color3
  29491. for (name in this._colors3) {
  29492. this._effect.setColor3(name, this._colors3[name]);
  29493. }
  29494. // Color4
  29495. for (name in this._colors4) {
  29496. var color = this._colors4[name];
  29497. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29498. }
  29499. // Vector2
  29500. for (name in this._vectors2) {
  29501. this._effect.setVector2(name, this._vectors2[name]);
  29502. }
  29503. // Vector3
  29504. for (name in this._vectors3) {
  29505. this._effect.setVector3(name, this._vectors3[name]);
  29506. }
  29507. // Vector4
  29508. for (name in this._vectors4) {
  29509. this._effect.setVector4(name, this._vectors4[name]);
  29510. }
  29511. // Matrix
  29512. for (name in this._matrices) {
  29513. this._effect.setMatrix(name, this._matrices[name]);
  29514. }
  29515. // Matrix 3x3
  29516. for (name in this._matrices3x3) {
  29517. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  29518. }
  29519. // Matrix 2x2
  29520. for (name in this._matrices2x2) {
  29521. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  29522. }
  29523. }
  29524. _super.prototype.bind.call(this, world, mesh);
  29525. };
  29526. ShaderMaterial.prototype.clone = function (name) {
  29527. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  29528. return newShaderMaterial;
  29529. };
  29530. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  29531. for (var name in this._textures) {
  29532. this._textures[name].dispose();
  29533. }
  29534. this._textures = {};
  29535. _super.prototype.dispose.call(this, forceDisposeEffect);
  29536. };
  29537. ShaderMaterial.prototype.serialize = function () {
  29538. var serializationObject = _super.prototype.serialize.call(this);
  29539. serializationObject.options = this._options;
  29540. serializationObject.shaderPath = this._shaderPath;
  29541. serializationObject.customType = "BABYLON.ShaderMaterial";
  29542. // Texture
  29543. serializationObject.textures = {};
  29544. for (var name in this._textures) {
  29545. serializationObject.textures[name] = this._textures[name].serialize();
  29546. }
  29547. // Float
  29548. serializationObject.floats = {};
  29549. for (name in this._floats) {
  29550. serializationObject.floats[name] = this._floats[name];
  29551. }
  29552. // Float s
  29553. serializationObject.floatArrays = {};
  29554. for (name in this._floatsArrays) {
  29555. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29556. }
  29557. // Color3
  29558. serializationObject.colors3 = {};
  29559. for (name in this._colors3) {
  29560. serializationObject.colors3[name] = this._colors3[name].asArray();
  29561. }
  29562. // Color4
  29563. serializationObject.colors4 = {};
  29564. for (name in this._colors4) {
  29565. serializationObject.colors4[name] = this._colors4[name].asArray();
  29566. }
  29567. // Vector2
  29568. serializationObject.vectors2 = {};
  29569. for (name in this._vectors2) {
  29570. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29571. }
  29572. // Vector3
  29573. serializationObject.vectors3 = {};
  29574. for (name in this._vectors3) {
  29575. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29576. }
  29577. // Vector4
  29578. serializationObject.vectors4 = {};
  29579. for (name in this._vectors4) {
  29580. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29581. }
  29582. // Matrix
  29583. serializationObject.matrices = {};
  29584. for (name in this._matrices) {
  29585. serializationObject.matrices[name] = this._matrices[name].asArray();
  29586. }
  29587. // Matrix 3x3
  29588. serializationObject.matrices3x3 = {};
  29589. for (name in this._matrices3x3) {
  29590. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29591. }
  29592. // Matrix 2x2
  29593. serializationObject.matrices2x2 = {};
  29594. for (name in this._matrices2x2) {
  29595. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29596. }
  29597. return serializationObject;
  29598. };
  29599. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29600. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  29601. // Texture
  29602. for (var name in source.textures) {
  29603. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29604. }
  29605. // Float
  29606. for (name in source.floats) {
  29607. material.setFloat(name, source.floats[name]);
  29608. }
  29609. // Float s
  29610. for (name in source.floatsArrays) {
  29611. material.setFloats(name, source.floatsArrays[name]);
  29612. }
  29613. // Color3
  29614. for (name in source.colors3) {
  29615. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29616. }
  29617. // Color4
  29618. for (name in source.colors4) {
  29619. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29620. }
  29621. // Vector2
  29622. for (name in source.vectors2) {
  29623. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29624. }
  29625. // Vector3
  29626. for (name in source.vectors3) {
  29627. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29628. }
  29629. // Vector4
  29630. for (name in source.vectors4) {
  29631. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29632. }
  29633. // Matrix
  29634. for (name in source.matrices) {
  29635. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29636. }
  29637. // Matrix 3x3
  29638. for (name in source.matrices3x3) {
  29639. material.setMatrix3x3(name, source.matrices3x3[name]);
  29640. }
  29641. // Matrix 2x2
  29642. for (name in source.matrices2x2) {
  29643. material.setMatrix2x2(name, source.matrices2x2[name]);
  29644. }
  29645. return material;
  29646. };
  29647. return ShaderMaterial;
  29648. })(BABYLON.Material);
  29649. BABYLON.ShaderMaterial = ShaderMaterial;
  29650. })(BABYLON || (BABYLON = {}));
  29651. var BABYLON;
  29652. (function (BABYLON) {
  29653. var Internals;
  29654. (function (Internals) {
  29655. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29656. // All values and structures referenced from:
  29657. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29658. var DDS_MAGIC = 0x20534444;
  29659. 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;
  29660. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29661. 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;
  29662. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29663. function FourCCToInt32(value) {
  29664. return value.charCodeAt(0) +
  29665. (value.charCodeAt(1) << 8) +
  29666. (value.charCodeAt(2) << 16) +
  29667. (value.charCodeAt(3) << 24);
  29668. }
  29669. function Int32ToFourCC(value) {
  29670. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29671. }
  29672. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29673. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29674. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29675. var headerLengthInt = 31; // The header length in 32 bit ints
  29676. // Offsets into the header array
  29677. var off_magic = 0;
  29678. var off_size = 1;
  29679. var off_flags = 2;
  29680. var off_height = 3;
  29681. var off_width = 4;
  29682. var off_mipmapCount = 7;
  29683. var off_pfFlags = 20;
  29684. var off_pfFourCC = 21;
  29685. var off_RGBbpp = 22;
  29686. var off_RMask = 23;
  29687. var off_GMask = 24;
  29688. var off_BMask = 25;
  29689. var off_AMask = 26;
  29690. var off_caps1 = 27;
  29691. var off_caps2 = 28;
  29692. ;
  29693. var DDSTools = (function () {
  29694. function DDSTools() {
  29695. }
  29696. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29697. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29698. var mipmapCount = 1;
  29699. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29700. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29701. }
  29702. return {
  29703. width: header[off_width],
  29704. height: header[off_height],
  29705. mipmapCount: mipmapCount,
  29706. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29707. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29708. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29709. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29710. };
  29711. };
  29712. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29713. var byteArray = new Uint8Array(dataLength);
  29714. var srcData = new Uint8Array(arrayBuffer);
  29715. var index = 0;
  29716. for (var y = height - 1; y >= 0; y--) {
  29717. for (var x = 0; x < width; x++) {
  29718. var srcPos = dataOffset + (x + y * width) * 4;
  29719. byteArray[index + 2] = srcData[srcPos];
  29720. byteArray[index + 1] = srcData[srcPos + 1];
  29721. byteArray[index] = srcData[srcPos + 2];
  29722. byteArray[index + 3] = srcData[srcPos + 3];
  29723. index += 4;
  29724. }
  29725. }
  29726. return byteArray;
  29727. };
  29728. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29729. var byteArray = new Uint8Array(dataLength);
  29730. var srcData = new Uint8Array(arrayBuffer);
  29731. var index = 0;
  29732. for (var y = height - 1; y >= 0; y--) {
  29733. for (var x = 0; x < width; x++) {
  29734. var srcPos = dataOffset + (x + y * width) * 3;
  29735. byteArray[index + 2] = srcData[srcPos];
  29736. byteArray[index + 1] = srcData[srcPos + 1];
  29737. byteArray[index] = srcData[srcPos + 2];
  29738. index += 3;
  29739. }
  29740. }
  29741. return byteArray;
  29742. };
  29743. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29744. var byteArray = new Uint8Array(dataLength);
  29745. var srcData = new Uint8Array(arrayBuffer);
  29746. var index = 0;
  29747. for (var y = height - 1; y >= 0; y--) {
  29748. for (var x = 0; x < width; x++) {
  29749. var srcPos = dataOffset + (x + y * width);
  29750. byteArray[index] = srcData[srcPos];
  29751. index++;
  29752. }
  29753. }
  29754. return byteArray;
  29755. };
  29756. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29757. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29758. if (header[off_magic] != DDS_MAGIC) {
  29759. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29760. return;
  29761. }
  29762. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29763. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29764. return;
  29765. }
  29766. if (info.isFourCC) {
  29767. fourCC = header[off_pfFourCC];
  29768. switch (fourCC) {
  29769. case FOURCC_DXT1:
  29770. blockBytes = 8;
  29771. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29772. break;
  29773. case FOURCC_DXT3:
  29774. blockBytes = 16;
  29775. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29776. break;
  29777. case FOURCC_DXT5:
  29778. blockBytes = 16;
  29779. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29780. break;
  29781. default:
  29782. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29783. return;
  29784. }
  29785. }
  29786. mipmapCount = 1;
  29787. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29788. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29789. }
  29790. var bpp = header[off_RGBbpp];
  29791. for (var face = 0; face < faces; face++) {
  29792. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29793. width = header[off_width];
  29794. height = header[off_height];
  29795. dataOffset = header[off_size] + 4;
  29796. for (i = 0; i < mipmapCount; ++i) {
  29797. if (info.isRGB) {
  29798. if (bpp === 24) {
  29799. dataLength = width * height * 3;
  29800. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29801. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29802. }
  29803. else {
  29804. dataLength = width * height * 4;
  29805. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29806. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29807. }
  29808. }
  29809. else if (info.isLuminance) {
  29810. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29811. var unpaddedRowSize = width;
  29812. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29813. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29814. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29815. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29816. }
  29817. else {
  29818. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29819. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29820. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29821. }
  29822. dataOffset += dataLength;
  29823. width *= 0.5;
  29824. height *= 0.5;
  29825. width = Math.max(1.0, width);
  29826. height = Math.max(1.0, height);
  29827. }
  29828. }
  29829. };
  29830. return DDSTools;
  29831. })();
  29832. Internals.DDSTools = DDSTools;
  29833. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29834. })(BABYLON || (BABYLON = {}));
  29835. var BABYLON;
  29836. (function (BABYLON) {
  29837. var CannonJSPlugin = (function () {
  29838. function CannonJSPlugin(_useDeltaForWorldStep) {
  29839. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  29840. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  29841. this._registeredMeshes = [];
  29842. this._physicsMaterials = [];
  29843. this._fixedTimeStep = 1 / 60;
  29844. //private _maxSubSteps : number = 15;
  29845. this.name = "CannonJS";
  29846. this.updateBodyPosition = function (mesh) {
  29847. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29848. var registeredMesh = this._registeredMeshes[index];
  29849. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29850. var body = registeredMesh.body;
  29851. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29852. body.quaternion.copy(mesh.rotationQuaternion);
  29853. if (registeredMesh.deltaRotation) {
  29854. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29855. body.quaternion = body.quaternion.mult(tmpQ);
  29856. }
  29857. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29858. //calculate the correct body position:
  29859. var rotationQuaternion = mesh.rotationQuaternion;
  29860. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29861. mesh.computeWorldMatrix(true);
  29862. //get original center with no rotation
  29863. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29864. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29865. //rotation is back
  29866. mesh.rotationQuaternion = rotationQuaternion;
  29867. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29868. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29869. mesh.setPivotMatrix(p);
  29870. mesh.computeWorldMatrix(true);
  29871. //calculate the translation
  29872. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29873. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29874. //add it inverted to the delta
  29875. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29876. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29877. mesh.setPivotMatrix(oldPivot);
  29878. mesh.computeWorldMatrix(true);
  29879. }
  29880. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29881. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29882. }
  29883. body.position.set(center.x, center.y, center.z);
  29884. return;
  29885. }
  29886. }
  29887. };
  29888. }
  29889. CannonJSPlugin.prototype.initialize = function (iterations) {
  29890. if (iterations === void 0) { iterations = 10; }
  29891. this._world = new CANNON.World();
  29892. this._world.broadphase = new CANNON.NaiveBroadphase();
  29893. this._world.solver.iterations = iterations;
  29894. };
  29895. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29896. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29897. };
  29898. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29899. var _this = this;
  29900. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  29901. this._registeredMeshes.forEach(function (registeredMesh) {
  29902. // Body position
  29903. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29904. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29905. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29906. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29907. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29908. if (registeredMesh.deltaRotation) {
  29909. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29910. }
  29911. //is the physics collision callback is set?
  29912. if (registeredMesh.mesh.onPhysicsCollide) {
  29913. if (!registeredMesh.collisionFunction) {
  29914. registeredMesh.collisionFunction = function (e) {
  29915. //find the mesh that collided with the registered mesh
  29916. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29917. if (_this._registeredMeshes[idx].body == e.body) {
  29918. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29919. }
  29920. }
  29921. };
  29922. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29923. }
  29924. }
  29925. else {
  29926. //unregister, in case the function was removed for some reason
  29927. if (registeredMesh.collisionFunction) {
  29928. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29929. }
  29930. }
  29931. });
  29932. };
  29933. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29934. this._gravity = gravity;
  29935. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29936. };
  29937. CannonJSPlugin.prototype.getGravity = function () {
  29938. return this._gravity;
  29939. };
  29940. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29941. this.unregisterMesh(mesh);
  29942. if (!mesh.rotationQuaternion) {
  29943. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29944. }
  29945. mesh.computeWorldMatrix(true);
  29946. var shape = this._createShape(mesh, impostor);
  29947. return this._createRigidBodyFromShape(shape, mesh, options);
  29948. };
  29949. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29950. //get the correct bounding box
  29951. var oldQuaternion = mesh.rotationQuaternion;
  29952. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29953. mesh.computeWorldMatrix(true);
  29954. var returnValue;
  29955. switch (impostor) {
  29956. case BABYLON.PhysicsEngine.SphereImpostor:
  29957. var bbox = mesh.getBoundingInfo().boundingBox;
  29958. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29959. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29960. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29961. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29962. break;
  29963. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29964. case BABYLON.PhysicsEngine.CylinderImpostor:
  29965. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29966. case BABYLON.PhysicsEngine.BoxImpostor:
  29967. bbox = mesh.getBoundingInfo().boundingBox;
  29968. var min = bbox.minimumWorld;
  29969. var max = bbox.maximumWorld;
  29970. var box = max.subtract(min).scale(0.5);
  29971. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29972. break;
  29973. case BABYLON.PhysicsEngine.PlaneImpostor:
  29974. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29975. returnValue = new CANNON.Plane();
  29976. break;
  29977. case BABYLON.PhysicsEngine.MeshImpostor:
  29978. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29979. var rawFaces = mesh.getIndices();
  29980. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29981. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29982. break;
  29983. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29984. returnValue = this._createHeightmap(mesh);
  29985. break;
  29986. }
  29987. mesh.rotationQuaternion = oldQuaternion;
  29988. return returnValue;
  29989. };
  29990. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29991. var verts = [], faces = [];
  29992. mesh.computeWorldMatrix(true);
  29993. //reuse this variable
  29994. var transformed = BABYLON.Vector3.Zero();
  29995. // Get vertices
  29996. for (var i = 0; i < rawVerts.length; i += 3) {
  29997. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29998. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29999. }
  30000. // Get faces
  30001. for (var j = 0; j < rawFaces.length; j += 3) {
  30002. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  30003. }
  30004. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  30005. return shape;
  30006. };
  30007. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30008. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30009. var matrix = [];
  30010. //For now pointDepth will not be used and will be automatically calculated.
  30011. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30012. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30013. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30014. var elementSize = dim * 2 / arraySize;
  30015. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30016. for (var i = 0; i < pos.length; i = i + 3) {
  30017. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30018. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30019. var y = pos[i + 1] + minY;
  30020. if (!matrix[x]) {
  30021. matrix[x] = [];
  30022. }
  30023. if (!matrix[x][z]) {
  30024. matrix[x][z] = y;
  30025. }
  30026. matrix[x][z] = Math.max(y, matrix[x][z]);
  30027. }
  30028. for (var x = 0; x <= arraySize; ++x) {
  30029. if (!matrix[x]) {
  30030. var loc = 1;
  30031. while (!matrix[(x + loc) % arraySize]) {
  30032. loc++;
  30033. }
  30034. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30035. }
  30036. for (var z = 0; z <= arraySize; ++z) {
  30037. if (!matrix[x][z]) {
  30038. var loc = 1;
  30039. var newValue;
  30040. while (newValue === undefined) {
  30041. newValue = matrix[x][(z + loc++) % arraySize];
  30042. }
  30043. matrix[x][z] = newValue;
  30044. }
  30045. }
  30046. }
  30047. var shape = new CANNON.Heightfield(matrix, {
  30048. elementSize: elementSize
  30049. });
  30050. //For future reference, needed for body transformation
  30051. shape.minY = minY;
  30052. return shape;
  30053. };
  30054. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30055. var index;
  30056. var mat;
  30057. for (index = 0; index < this._physicsMaterials.length; index++) {
  30058. mat = this._physicsMaterials[index];
  30059. if (mat.friction === friction && mat.restitution === restitution) {
  30060. return mat;
  30061. }
  30062. }
  30063. var currentMat = new CANNON.Material("mat");
  30064. this._physicsMaterials.push(currentMat);
  30065. for (index = 0; index < this._physicsMaterials.length; index++) {
  30066. mat = this._physicsMaterials[index];
  30067. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30068. this._world.addContactMaterial(contactMaterial);
  30069. }
  30070. return currentMat;
  30071. };
  30072. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  30073. if (!mesh.rotationQuaternion) {
  30074. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30075. }
  30076. // The delta between the mesh position and the mesh bounding box center
  30077. var bbox = mesh.getBoundingInfo().boundingBox;
  30078. var deltaPosition = mesh.position.subtract(bbox.center);
  30079. var deltaRotation;
  30080. var material = this._addMaterial(options.friction, options.restitution);
  30081. var body = new CANNON.Body({
  30082. mass: options.mass,
  30083. material: material,
  30084. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  30085. });
  30086. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  30087. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30088. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30089. //-90 DEG in X, precalculated
  30090. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30091. body.quaternion = body.quaternion.mult(tmpQ);
  30092. //Invert! (Precalculated, 90 deg in X)
  30093. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30094. }
  30095. //If it is a heightfield, if should be centered.
  30096. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30097. //calculate the correct body position:
  30098. var rotationQuaternion = mesh.rotationQuaternion;
  30099. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30100. mesh.computeWorldMatrix(true);
  30101. //get original center with no rotation
  30102. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30103. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30104. //rotation is back
  30105. mesh.rotationQuaternion = rotationQuaternion;
  30106. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30107. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30108. mesh.setPivotMatrix(p);
  30109. mesh.computeWorldMatrix(true);
  30110. //calculate the translation
  30111. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30112. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30113. //add it inverted to the delta
  30114. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30115. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30116. mesh.setPivotMatrix(oldPivot);
  30117. mesh.computeWorldMatrix(true);
  30118. }
  30119. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  30120. deltaPosition = BABYLON.Vector3.Zero();
  30121. }
  30122. //add the shape
  30123. body.addShape(shape);
  30124. this._world.add(body);
  30125. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  30126. return body;
  30127. };
  30128. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30129. var initialMesh = parts[0].mesh;
  30130. this.unregisterMesh(initialMesh);
  30131. initialMesh.computeWorldMatrix(true);
  30132. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  30133. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  30134. for (var index = 1; index < parts.length; index++) {
  30135. var mesh = parts[index].mesh;
  30136. mesh.computeWorldMatrix(true);
  30137. var shape = this._createShape(mesh, parts[index].impostor);
  30138. var localPosition = mesh.position;
  30139. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30140. }
  30141. return body;
  30142. };
  30143. CannonJSPlugin.prototype._unbindBody = function (body) {
  30144. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30145. var registeredMesh = this._registeredMeshes[index];
  30146. if (registeredMesh.body === body) {
  30147. this._world.remove(registeredMesh.body);
  30148. registeredMesh.body = null;
  30149. registeredMesh.delta = null;
  30150. registeredMesh.deltaRotation = null;
  30151. }
  30152. }
  30153. };
  30154. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30155. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30156. var registeredMesh = this._registeredMeshes[index];
  30157. if (registeredMesh.mesh === mesh) {
  30158. // Remove body
  30159. if (registeredMesh.body) {
  30160. this._unbindBody(registeredMesh.body);
  30161. }
  30162. this._registeredMeshes.splice(index, 1);
  30163. return;
  30164. }
  30165. }
  30166. };
  30167. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30168. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30169. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30170. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30171. var registeredMesh = this._registeredMeshes[index];
  30172. if (registeredMesh.mesh === mesh) {
  30173. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30174. return;
  30175. }
  30176. }
  30177. };
  30178. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30179. var body1 = null, body2 = null;
  30180. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30181. var registeredMesh = this._registeredMeshes[index];
  30182. if (registeredMesh.mesh === mesh1) {
  30183. body1 = registeredMesh.body;
  30184. if (body2)
  30185. break;
  30186. }
  30187. else if (registeredMesh.mesh === mesh2) {
  30188. body2 = registeredMesh.body;
  30189. if (body1)
  30190. break;
  30191. }
  30192. }
  30193. if (!body1 || !body2) {
  30194. return false;
  30195. }
  30196. 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));
  30197. this._world.addConstraint(constraint);
  30198. return true;
  30199. };
  30200. CannonJSPlugin.prototype.dispose = function () {
  30201. while (this._registeredMeshes.length) {
  30202. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30203. }
  30204. };
  30205. CannonJSPlugin.prototype.isSupported = function () {
  30206. return window.CANNON !== undefined;
  30207. };
  30208. CannonJSPlugin.prototype.getWorldObject = function () {
  30209. return this._world;
  30210. };
  30211. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30212. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30213. var registeredMesh = this._registeredMeshes[index];
  30214. if (registeredMesh.mesh === mesh) {
  30215. return registeredMesh.body;
  30216. }
  30217. }
  30218. return null;
  30219. };
  30220. return CannonJSPlugin;
  30221. })();
  30222. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30223. })(BABYLON || (BABYLON = {}));
  30224. var BABYLON;
  30225. (function (BABYLON) {
  30226. var OimoJSPlugin = (function () {
  30227. function OimoJSPlugin() {
  30228. this._registeredMeshes = [];
  30229. this.name = "oimo";
  30230. /**
  30231. * Update the body position according to the mesh position
  30232. * @param mesh
  30233. */
  30234. this.updateBodyPosition = function (mesh) {
  30235. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30236. var registeredMesh = this._registeredMeshes[index];
  30237. var body = registeredMesh.body.body;
  30238. var updated = false;
  30239. var newPosition;
  30240. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30241. mesh.computeWorldMatrix(true);
  30242. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30243. updated = true;
  30244. }
  30245. else if (registeredMesh.mesh.parent === mesh) {
  30246. mesh.computeWorldMatrix(true);
  30247. registeredMesh.mesh.computeWorldMatrix(true);
  30248. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30249. updated = true;
  30250. }
  30251. if (updated) {
  30252. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30253. body.setQuaternion(mesh.rotationQuaternion);
  30254. body.sleeping = false;
  30255. //force Oimo to update the body's position
  30256. body.updatePosition(1);
  30257. }
  30258. }
  30259. };
  30260. }
  30261. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30262. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30263. };
  30264. OimoJSPlugin.prototype.initialize = function (iterations) {
  30265. this._world = new OIMO.World(null, null, iterations);
  30266. this._world.clear();
  30267. };
  30268. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30269. this._gravity = this._world.gravity = gravity;
  30270. };
  30271. OimoJSPlugin.prototype.getGravity = function () {
  30272. return this._gravity;
  30273. };
  30274. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30275. this.unregisterMesh(mesh);
  30276. if (!mesh.rotationQuaternion) {
  30277. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30278. }
  30279. mesh.computeWorldMatrix(true);
  30280. var bbox = mesh.getBoundingInfo().boundingBox;
  30281. // The delta between the mesh position and the mesh bounding box center
  30282. var deltaPosition = mesh.position.subtract(bbox.center);
  30283. //calculate rotation to fit Oimo's needs (Euler...)
  30284. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30285. //get the correct bounding box
  30286. var oldQuaternion = mesh.rotationQuaternion;
  30287. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30288. mesh.computeWorldMatrix(true);
  30289. var bodyConfig = {
  30290. name: mesh.uniqueId,
  30291. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30292. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30293. move: options.mass != 0,
  30294. config: [options.mass, options.friction, options.restitution],
  30295. world: this._world
  30296. };
  30297. // register mesh
  30298. switch (impostor) {
  30299. case BABYLON.PhysicsEngine.SphereImpostor:
  30300. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30301. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30302. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30303. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30304. bodyConfig.type = 'sphere';
  30305. bodyConfig.size = [size];
  30306. break;
  30307. case BABYLON.PhysicsEngine.PlaneImpostor:
  30308. //Oimo "fakes" a cylinder as a box, so why don't we!
  30309. case BABYLON.PhysicsEngine.CylinderImpostor:
  30310. case BABYLON.PhysicsEngine.BoxImpostor:
  30311. var min = bbox.minimumWorld;
  30312. var max = bbox.maximumWorld;
  30313. var box = max.subtract(min);
  30314. var sizeX = this._checkWithEpsilon(box.x);
  30315. var sizeY = this._checkWithEpsilon(box.y);
  30316. var sizeZ = this._checkWithEpsilon(box.z);
  30317. bodyConfig.type = 'box';
  30318. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30319. break;
  30320. }
  30321. var body = new OIMO.Body(bodyConfig);
  30322. //We have to access the rigid body's properties to set the quaternion.
  30323. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30324. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30325. //TEST
  30326. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30327. //update the internal rotation matrix
  30328. //body.body.syncShapes();
  30329. this._registeredMeshes.push({
  30330. mesh: mesh,
  30331. body: body,
  30332. delta: deltaPosition
  30333. });
  30334. //for the sake of consistency.
  30335. mesh.rotationQuaternion = oldQuaternion;
  30336. return body;
  30337. };
  30338. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30339. var types = [], sizes = [], positions = [], rotations = [];
  30340. var initialMesh = parts[0].mesh;
  30341. for (var index = 0; index < parts.length; index++) {
  30342. var part = parts[index];
  30343. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30344. types.push(bodyParameters.type);
  30345. sizes.push.apply(sizes, bodyParameters.size);
  30346. positions.push.apply(positions, bodyParameters.pos);
  30347. rotations.push.apply(rotations, bodyParameters.rot);
  30348. }
  30349. var body = new OIMO.Body({
  30350. name: initialMesh.uniqueId,
  30351. type: types,
  30352. size: sizes,
  30353. pos: positions,
  30354. rot: rotations,
  30355. move: options.mass != 0,
  30356. config: [options.mass, options.friction, options.restitution],
  30357. world: this._world
  30358. });
  30359. //Reset the body's rotation to be of the initial mesh's.
  30360. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30361. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30362. this._registeredMeshes.push({
  30363. mesh: initialMesh,
  30364. body: body
  30365. });
  30366. return body;
  30367. };
  30368. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30369. var mesh = part.mesh;
  30370. if (!mesh.rotationQuaternion) {
  30371. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30372. }
  30373. // We need the bounding box/sphere info to compute the physics body
  30374. mesh.computeWorldMatrix(true);
  30375. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30376. var bodyParameters = {
  30377. name: mesh.uniqueId,
  30378. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30379. //A bug in Oimo (Body class) prevents us from using rot directly.
  30380. rot: [0, 0, 0],
  30381. //For future reference, if the bug will ever be fixed.
  30382. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30383. };
  30384. var oldQuaternion = mesh.rotationQuaternion;
  30385. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30386. mesh.computeWorldMatrix(true);
  30387. switch (part.impostor) {
  30388. case BABYLON.PhysicsEngine.SphereImpostor:
  30389. var bbox = mesh.getBoundingInfo().boundingBox;
  30390. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30391. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30392. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30393. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30394. bodyParameters.type = 'sphere';
  30395. bodyParameters.size = [size, size, size];
  30396. break;
  30397. case BABYLON.PhysicsEngine.PlaneImpostor:
  30398. case BABYLON.PhysicsEngine.CylinderImpostor:
  30399. case BABYLON.PhysicsEngine.BoxImpostor:
  30400. bbox = mesh.getBoundingInfo().boundingBox;
  30401. var min = bbox.minimumWorld;
  30402. var max = bbox.maximumWorld;
  30403. var box = max.subtract(min);
  30404. var sizeX = this._checkWithEpsilon(box.x);
  30405. var sizeY = this._checkWithEpsilon(box.y);
  30406. var sizeZ = this._checkWithEpsilon(box.z);
  30407. bodyParameters.type = 'box';
  30408. bodyParameters.size = [sizeX, sizeY, sizeZ];
  30409. break;
  30410. }
  30411. mesh.rotationQuaternion = oldQuaternion;
  30412. return bodyParameters;
  30413. };
  30414. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  30415. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30416. var registeredMesh = this._registeredMeshes[index];
  30417. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30418. if (registeredMesh.body) {
  30419. this._world.removeRigidBody(registeredMesh.body.body);
  30420. this._unbindBody(registeredMesh.body);
  30421. }
  30422. this._registeredMeshes.splice(index, 1);
  30423. return;
  30424. }
  30425. }
  30426. };
  30427. OimoJSPlugin.prototype._unbindBody = function (body) {
  30428. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30429. var registeredMesh = this._registeredMeshes[index];
  30430. if (registeredMesh.body === body) {
  30431. registeredMesh.body = null;
  30432. }
  30433. }
  30434. };
  30435. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30436. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30437. var registeredMesh = this._registeredMeshes[index];
  30438. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30439. // Get object mass to have a behaviour similar to cannon.js
  30440. var mass = registeredMesh.body.body.massInfo.mass;
  30441. // The force is scaled with the mass of object
  30442. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30443. return;
  30444. }
  30445. }
  30446. };
  30447. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  30448. var body1 = null, body2 = null;
  30449. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30450. var registeredMesh = this._registeredMeshes[index];
  30451. if (registeredMesh.mesh === mesh1) {
  30452. body1 = registeredMesh.body.body;
  30453. }
  30454. else if (registeredMesh.mesh === mesh2) {
  30455. body2 = registeredMesh.body.body;
  30456. }
  30457. }
  30458. if (!body1 || !body2) {
  30459. return false;
  30460. }
  30461. if (!options) {
  30462. options = {};
  30463. }
  30464. new OIMO.Link({
  30465. type: options.type,
  30466. body1: body1,
  30467. body2: body2,
  30468. min: options.min,
  30469. max: options.max,
  30470. axe1: options.axe1,
  30471. axe2: options.axe2,
  30472. pos1: [pivot1.x, pivot1.y, pivot1.z],
  30473. pos2: [pivot2.x, pivot2.y, pivot2.z],
  30474. collision: options.collision,
  30475. spring: options.spring,
  30476. world: this._world
  30477. });
  30478. return true;
  30479. };
  30480. OimoJSPlugin.prototype.dispose = function () {
  30481. this._world.clear();
  30482. while (this._registeredMeshes.length) {
  30483. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30484. }
  30485. };
  30486. OimoJSPlugin.prototype.isSupported = function () {
  30487. return OIMO !== undefined;
  30488. };
  30489. OimoJSPlugin.prototype.getWorldObject = function () {
  30490. return this._world;
  30491. };
  30492. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30493. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30494. var registeredMesh = this._registeredMeshes[index];
  30495. if (registeredMesh.mesh === mesh) {
  30496. return registeredMesh.body;
  30497. }
  30498. }
  30499. return null;
  30500. };
  30501. OimoJSPlugin.prototype._getLastShape = function (body) {
  30502. var lastShape = body.shapes;
  30503. while (lastShape.next) {
  30504. lastShape = lastShape.next;
  30505. }
  30506. return lastShape;
  30507. };
  30508. OimoJSPlugin.prototype.runOneStep = function (time) {
  30509. this._world.step();
  30510. // Update the position of all registered meshes
  30511. var i = this._registeredMeshes.length;
  30512. var m;
  30513. while (i--) {
  30514. var body = this._registeredMeshes[i].body.body;
  30515. var mesh = this._registeredMeshes[i].mesh;
  30516. if (!this._registeredMeshes[i].delta) {
  30517. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  30518. }
  30519. if (!body.sleeping) {
  30520. //TODO check that
  30521. if (body.shapes.next) {
  30522. var parentShape = this._getLastShape(body);
  30523. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  30524. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  30525. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  30526. }
  30527. else {
  30528. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  30529. }
  30530. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  30531. mesh.computeWorldMatrix();
  30532. }
  30533. //check if the collide callback is set.
  30534. if (mesh.onPhysicsCollide) {
  30535. var meshUniqueName = mesh.uniqueId;
  30536. var contact = this._world.contacts;
  30537. while (contact !== null) {
  30538. //is this body colliding with any other?
  30539. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30540. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  30541. //get the mesh and execute the callback
  30542. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  30543. if (otherMesh)
  30544. mesh.onPhysicsCollide(otherMesh, contact);
  30545. }
  30546. contact = contact.next;
  30547. }
  30548. }
  30549. }
  30550. };
  30551. return OimoJSPlugin;
  30552. })();
  30553. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30554. })(BABYLON || (BABYLON = {}));
  30555. var BABYLON;
  30556. (function (BABYLON) {
  30557. var DisplayPassPostProcess = (function (_super) {
  30558. __extends(DisplayPassPostProcess, _super);
  30559. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30560. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30561. }
  30562. return DisplayPassPostProcess;
  30563. })(BABYLON.PostProcess);
  30564. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30565. })(BABYLON || (BABYLON = {}));
  30566. var BABYLON;
  30567. (function (BABYLON) {
  30568. var SimplificationSettings = (function () {
  30569. function SimplificationSettings(quality, distance, optimizeMesh) {
  30570. this.quality = quality;
  30571. this.distance = distance;
  30572. this.optimizeMesh = optimizeMesh;
  30573. }
  30574. return SimplificationSettings;
  30575. })();
  30576. BABYLON.SimplificationSettings = SimplificationSettings;
  30577. var SimplificationQueue = (function () {
  30578. function SimplificationQueue() {
  30579. this.running = false;
  30580. this._simplificationArray = [];
  30581. }
  30582. SimplificationQueue.prototype.addTask = function (task) {
  30583. this._simplificationArray.push(task);
  30584. };
  30585. SimplificationQueue.prototype.executeNext = function () {
  30586. var task = this._simplificationArray.pop();
  30587. if (task) {
  30588. this.running = true;
  30589. this.runSimplification(task);
  30590. }
  30591. else {
  30592. this.running = false;
  30593. }
  30594. };
  30595. SimplificationQueue.prototype.runSimplification = function (task) {
  30596. var _this = this;
  30597. if (task.parallelProcessing) {
  30598. //parallel simplifier
  30599. task.settings.forEach(function (setting) {
  30600. var simplifier = _this.getSimplifier(task);
  30601. simplifier.simplify(setting, function (newMesh) {
  30602. task.mesh.addLODLevel(setting.distance, newMesh);
  30603. newMesh.isVisible = true;
  30604. //check if it is the last
  30605. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30606. //all done, run the success callback.
  30607. task.successCallback();
  30608. }
  30609. _this.executeNext();
  30610. });
  30611. });
  30612. }
  30613. else {
  30614. //single simplifier.
  30615. var simplifier = this.getSimplifier(task);
  30616. var runDecimation = function (setting, callback) {
  30617. simplifier.simplify(setting, function (newMesh) {
  30618. task.mesh.addLODLevel(setting.distance, newMesh);
  30619. newMesh.isVisible = true;
  30620. //run the next quality level
  30621. callback();
  30622. });
  30623. };
  30624. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30625. runDecimation(task.settings[loop.index], function () {
  30626. loop.executeNext();
  30627. });
  30628. }, function () {
  30629. //execution ended, run the success callback.
  30630. if (task.successCallback) {
  30631. task.successCallback();
  30632. }
  30633. _this.executeNext();
  30634. });
  30635. }
  30636. };
  30637. SimplificationQueue.prototype.getSimplifier = function (task) {
  30638. switch (task.simplificationType) {
  30639. case SimplificationType.QUADRATIC:
  30640. default:
  30641. return new QuadraticErrorSimplification(task.mesh);
  30642. }
  30643. };
  30644. return SimplificationQueue;
  30645. })();
  30646. BABYLON.SimplificationQueue = SimplificationQueue;
  30647. /**
  30648. * The implemented types of simplification.
  30649. * At the moment only Quadratic Error Decimation is implemented.
  30650. */
  30651. (function (SimplificationType) {
  30652. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30653. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30654. var SimplificationType = BABYLON.SimplificationType;
  30655. var DecimationTriangle = (function () {
  30656. function DecimationTriangle(vertices) {
  30657. this.vertices = vertices;
  30658. this.error = new Array(4);
  30659. this.deleted = false;
  30660. this.isDirty = false;
  30661. this.deletePending = false;
  30662. this.borderFactor = 0;
  30663. }
  30664. return DecimationTriangle;
  30665. })();
  30666. BABYLON.DecimationTriangle = DecimationTriangle;
  30667. var DecimationVertex = (function () {
  30668. function DecimationVertex(position, id) {
  30669. this.position = position;
  30670. this.id = id;
  30671. this.isBorder = true;
  30672. this.q = new QuadraticMatrix();
  30673. this.triangleCount = 0;
  30674. this.triangleStart = 0;
  30675. this.originalOffsets = [];
  30676. }
  30677. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30678. this.position.copyFrom(newPosition);
  30679. };
  30680. return DecimationVertex;
  30681. })();
  30682. BABYLON.DecimationVertex = DecimationVertex;
  30683. var QuadraticMatrix = (function () {
  30684. function QuadraticMatrix(data) {
  30685. this.data = new Array(10);
  30686. for (var i = 0; i < 10; ++i) {
  30687. if (data && data[i]) {
  30688. this.data[i] = data[i];
  30689. }
  30690. else {
  30691. this.data[i] = 0;
  30692. }
  30693. }
  30694. }
  30695. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30696. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30697. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30698. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30699. return det;
  30700. };
  30701. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30702. for (var i = 0; i < 10; ++i) {
  30703. this.data[i] += matrix.data[i];
  30704. }
  30705. };
  30706. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30707. for (var i = 0; i < 10; ++i) {
  30708. this.data[i] += data[i];
  30709. }
  30710. };
  30711. QuadraticMatrix.prototype.add = function (matrix) {
  30712. var m = new QuadraticMatrix();
  30713. for (var i = 0; i < 10; ++i) {
  30714. m.data[i] = this.data[i] + matrix.data[i];
  30715. }
  30716. return m;
  30717. };
  30718. QuadraticMatrix.FromData = function (a, b, c, d) {
  30719. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30720. };
  30721. //returning an array to avoid garbage collection
  30722. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30723. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30724. };
  30725. return QuadraticMatrix;
  30726. })();
  30727. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30728. var Reference = (function () {
  30729. function Reference(vertexId, triangleId) {
  30730. this.vertexId = vertexId;
  30731. this.triangleId = triangleId;
  30732. }
  30733. return Reference;
  30734. })();
  30735. BABYLON.Reference = Reference;
  30736. /**
  30737. * An implementation of the Quadratic Error simplification algorithm.
  30738. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30739. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30740. * @author RaananW
  30741. */
  30742. var QuadraticErrorSimplification = (function () {
  30743. function QuadraticErrorSimplification(_mesh) {
  30744. this._mesh = _mesh;
  30745. this.initialized = false;
  30746. this.syncIterations = 5000;
  30747. this.aggressiveness = 7;
  30748. this.decimationIterations = 100;
  30749. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30750. }
  30751. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30752. var _this = this;
  30753. this.initDecimatedMesh();
  30754. //iterating through the submeshes array, one after the other.
  30755. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30756. _this.initWithMesh(loop.index, function () {
  30757. _this.runDecimation(settings, loop.index, function () {
  30758. loop.executeNext();
  30759. });
  30760. }, settings.optimizeMesh);
  30761. }, function () {
  30762. setTimeout(function () {
  30763. successCallback(_this._reconstructedMesh);
  30764. }, 0);
  30765. });
  30766. };
  30767. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30768. var _this = this;
  30769. var gCount = 0;
  30770. triangle.vertices.forEach(function (vertex) {
  30771. var count = 0;
  30772. var vPos = vertex.position;
  30773. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30774. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30775. ++count;
  30776. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30777. ++count;
  30778. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30779. ++count;
  30780. if (count > 1) {
  30781. ++gCount;
  30782. }
  30783. ;
  30784. });
  30785. if (gCount > 1) {
  30786. console.log(triangle, gCount);
  30787. }
  30788. return gCount > 1;
  30789. };
  30790. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30791. var _this = this;
  30792. var targetCount = ~~(this.triangles.length * settings.quality);
  30793. var deletedTriangles = 0;
  30794. var triangleCount = this.triangles.length;
  30795. var iterationFunction = function (iteration, callback) {
  30796. setTimeout(function () {
  30797. if (iteration % 5 === 0) {
  30798. _this.updateMesh(iteration === 0);
  30799. }
  30800. for (var i = 0; i < _this.triangles.length; ++i) {
  30801. _this.triangles[i].isDirty = false;
  30802. }
  30803. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30804. var trianglesIterator = function (i) {
  30805. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30806. var t = _this.triangles[tIdx];
  30807. if (!t)
  30808. return;
  30809. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30810. return;
  30811. }
  30812. for (var j = 0; j < 3; ++j) {
  30813. if (t.error[j] < threshold) {
  30814. var deleted0 = [];
  30815. var deleted1 = [];
  30816. var v0 = t.vertices[j];
  30817. var v1 = t.vertices[(j + 1) % 3];
  30818. if (v0.isBorder !== v1.isBorder)
  30819. continue;
  30820. var p = BABYLON.Vector3.Zero();
  30821. var n = BABYLON.Vector3.Zero();
  30822. var uv = BABYLON.Vector2.Zero();
  30823. var color = new BABYLON.Color4(0, 0, 0, 1);
  30824. _this.calculateError(v0, v1, p, n, uv, color);
  30825. var delTr = [];
  30826. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30827. continue;
  30828. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30829. continue;
  30830. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30831. continue;
  30832. var uniqueArray = [];
  30833. delTr.forEach(function (deletedT) {
  30834. if (uniqueArray.indexOf(deletedT) === -1) {
  30835. deletedT.deletePending = true;
  30836. uniqueArray.push(deletedT);
  30837. }
  30838. });
  30839. if (uniqueArray.length % 2 !== 0) {
  30840. continue;
  30841. }
  30842. v0.q = v1.q.add(v0.q);
  30843. v0.updatePosition(p);
  30844. var tStart = _this.references.length;
  30845. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30846. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30847. var tCount = _this.references.length - tStart;
  30848. if (tCount <= v0.triangleCount) {
  30849. if (tCount) {
  30850. for (var c = 0; c < tCount; c++) {
  30851. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30852. }
  30853. }
  30854. }
  30855. else {
  30856. v0.triangleStart = tStart;
  30857. }
  30858. v0.triangleCount = tCount;
  30859. break;
  30860. }
  30861. }
  30862. };
  30863. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30864. }, 0);
  30865. };
  30866. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30867. if (triangleCount - deletedTriangles <= targetCount)
  30868. loop.breakLoop();
  30869. else {
  30870. iterationFunction(loop.index, function () {
  30871. loop.executeNext();
  30872. });
  30873. }
  30874. }, function () {
  30875. setTimeout(function () {
  30876. //reconstruct this part of the mesh
  30877. _this.reconstructMesh(submeshIndex);
  30878. successCallback();
  30879. }, 0);
  30880. });
  30881. };
  30882. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30883. var _this = this;
  30884. this.vertices = [];
  30885. this.triangles = [];
  30886. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30887. var indices = this._mesh.getIndices();
  30888. var submesh = this._mesh.subMeshes[submeshIndex];
  30889. var findInVertices = function (positionToSearch) {
  30890. if (optimizeMesh) {
  30891. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30892. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30893. return _this.vertices[ii];
  30894. }
  30895. }
  30896. }
  30897. return null;
  30898. };
  30899. var vertexReferences = [];
  30900. var vertexInit = function (i) {
  30901. var offset = i + submesh.verticesStart;
  30902. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30903. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30904. vertex.originalOffsets.push(offset);
  30905. if (vertex.id === _this.vertices.length) {
  30906. _this.vertices.push(vertex);
  30907. }
  30908. vertexReferences.push(vertex.id);
  30909. };
  30910. //var totalVertices = mesh.getTotalVertices();
  30911. var totalVertices = submesh.verticesCount;
  30912. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30913. var indicesInit = function (i) {
  30914. var offset = (submesh.indexStart / 3) + i;
  30915. var pos = (offset * 3);
  30916. var i0 = indices[pos + 0];
  30917. var i1 = indices[pos + 1];
  30918. var i2 = indices[pos + 2];
  30919. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30920. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30921. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30922. var triangle = new DecimationTriangle([v0, v1, v2]);
  30923. triangle.originalOffset = pos;
  30924. _this.triangles.push(triangle);
  30925. };
  30926. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30927. _this.init(callback);
  30928. });
  30929. });
  30930. };
  30931. QuadraticErrorSimplification.prototype.init = function (callback) {
  30932. var _this = this;
  30933. var triangleInit1 = function (i) {
  30934. var t = _this.triangles[i];
  30935. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30936. for (var j = 0; j < 3; j++) {
  30937. 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))));
  30938. }
  30939. };
  30940. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30941. var triangleInit2 = function (i) {
  30942. var t = _this.triangles[i];
  30943. for (var j = 0; j < 3; ++j) {
  30944. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30945. }
  30946. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30947. };
  30948. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30949. _this.initialized = true;
  30950. callback();
  30951. });
  30952. });
  30953. };
  30954. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30955. var newTriangles = [];
  30956. var i;
  30957. for (i = 0; i < this.vertices.length; ++i) {
  30958. this.vertices[i].triangleCount = 0;
  30959. }
  30960. var t;
  30961. var j;
  30962. for (i = 0; i < this.triangles.length; ++i) {
  30963. if (!this.triangles[i].deleted) {
  30964. t = this.triangles[i];
  30965. for (j = 0; j < 3; ++j) {
  30966. t.vertices[j].triangleCount = 1;
  30967. }
  30968. newTriangles.push(t);
  30969. }
  30970. }
  30971. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30972. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30973. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30974. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30975. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30976. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30977. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30978. var vertexCount = 0;
  30979. for (i = 0; i < this.vertices.length; ++i) {
  30980. var vertex = this.vertices[i];
  30981. vertex.id = vertexCount;
  30982. if (vertex.triangleCount) {
  30983. vertex.originalOffsets.forEach(function (originalOffset) {
  30984. newPositionData.push(vertex.position.x);
  30985. newPositionData.push(vertex.position.y);
  30986. newPositionData.push(vertex.position.z);
  30987. newNormalData.push(normalData[originalOffset * 3]);
  30988. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30989. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30990. if (uvs && uvs.length) {
  30991. newUVsData.push(uvs[(originalOffset * 2)]);
  30992. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30993. }
  30994. else if (colorsData && colorsData.length) {
  30995. newColorsData.push(colorsData[(originalOffset * 4)]);
  30996. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30997. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30998. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30999. }
  31000. ++vertexCount;
  31001. });
  31002. }
  31003. }
  31004. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31005. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31006. var submeshesArray = this._reconstructedMesh.subMeshes;
  31007. this._reconstructedMesh.subMeshes = [];
  31008. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31009. var originalIndices = this._mesh.getIndices();
  31010. for (i = 0; i < newTriangles.length; ++i) {
  31011. t = newTriangles[i]; //now get the new referencing point for each vertex
  31012. [0, 1, 2].forEach(function (idx) {
  31013. var id = originalIndices[t.originalOffset + idx];
  31014. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31015. if (offset < 0)
  31016. offset = 0;
  31017. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31018. });
  31019. }
  31020. //overwriting the old vertex buffers and indices.
  31021. this._reconstructedMesh.setIndices(newIndicesArray);
  31022. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31023. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31024. if (newUVsData.length > 0)
  31025. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31026. if (newColorsData.length > 0)
  31027. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31028. //create submesh
  31029. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31030. if (submeshIndex > 0) {
  31031. this._reconstructedMesh.subMeshes = [];
  31032. submeshesArray.forEach(function (submesh) {
  31033. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31034. });
  31035. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31036. }
  31037. };
  31038. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31039. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31040. this._reconstructedMesh.material = this._mesh.material;
  31041. this._reconstructedMesh.parent = this._mesh.parent;
  31042. this._reconstructedMesh.isVisible = false;
  31043. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31044. };
  31045. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31046. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31047. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31048. if (t.deleted)
  31049. continue;
  31050. var s = this.references[vertex1.triangleStart + i].vertexId;
  31051. var v1 = t.vertices[(s + 1) % 3];
  31052. var v2 = t.vertices[(s + 2) % 3];
  31053. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31054. deletedArray[i] = true;
  31055. delTr.push(t);
  31056. continue;
  31057. }
  31058. var d1 = v1.position.subtract(point);
  31059. d1 = d1.normalize();
  31060. var d2 = v2.position.subtract(point);
  31061. d2 = d2.normalize();
  31062. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31063. return true;
  31064. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31065. deletedArray[i] = false;
  31066. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31067. return true;
  31068. }
  31069. return false;
  31070. };
  31071. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31072. var newDeleted = deletedTriangles;
  31073. for (var i = 0; i < vertex.triangleCount; ++i) {
  31074. var ref = this.references[vertex.triangleStart + i];
  31075. var t = this.triangles[ref.triangleId];
  31076. if (t.deleted)
  31077. continue;
  31078. if (deletedArray[i] && t.deletePending) {
  31079. t.deleted = true;
  31080. newDeleted++;
  31081. continue;
  31082. }
  31083. t.vertices[ref.vertexId] = origVertex;
  31084. t.isDirty = true;
  31085. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31086. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31087. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31088. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31089. this.references.push(ref);
  31090. }
  31091. return newDeleted;
  31092. };
  31093. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31094. for (var i = 0; i < this.vertices.length; ++i) {
  31095. var vCount = [];
  31096. var vId = [];
  31097. var v = this.vertices[i];
  31098. var j;
  31099. for (j = 0; j < v.triangleCount; ++j) {
  31100. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31101. for (var ii = 0; ii < 3; ii++) {
  31102. var ofs = 0;
  31103. var vv = triangle.vertices[ii];
  31104. while (ofs < vCount.length) {
  31105. if (vId[ofs] === vv.id)
  31106. break;
  31107. ++ofs;
  31108. }
  31109. if (ofs === vCount.length) {
  31110. vCount.push(1);
  31111. vId.push(vv.id);
  31112. }
  31113. else {
  31114. vCount[ofs]++;
  31115. }
  31116. }
  31117. }
  31118. for (j = 0; j < vCount.length; ++j) {
  31119. if (vCount[j] === 1) {
  31120. this.vertices[vId[j]].isBorder = true;
  31121. }
  31122. else {
  31123. this.vertices[vId[j]].isBorder = false;
  31124. }
  31125. }
  31126. }
  31127. };
  31128. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31129. if (identifyBorders === void 0) { identifyBorders = false; }
  31130. var i;
  31131. if (!identifyBorders) {
  31132. var newTrianglesVector = [];
  31133. for (i = 0; i < this.triangles.length; ++i) {
  31134. if (!this.triangles[i].deleted) {
  31135. newTrianglesVector.push(this.triangles[i]);
  31136. }
  31137. }
  31138. this.triangles = newTrianglesVector;
  31139. }
  31140. for (i = 0; i < this.vertices.length; ++i) {
  31141. this.vertices[i].triangleCount = 0;
  31142. this.vertices[i].triangleStart = 0;
  31143. }
  31144. var t;
  31145. var j;
  31146. var v;
  31147. for (i = 0; i < this.triangles.length; ++i) {
  31148. t = this.triangles[i];
  31149. for (j = 0; j < 3; ++j) {
  31150. v = t.vertices[j];
  31151. v.triangleCount++;
  31152. }
  31153. }
  31154. var tStart = 0;
  31155. for (i = 0; i < this.vertices.length; ++i) {
  31156. this.vertices[i].triangleStart = tStart;
  31157. tStart += this.vertices[i].triangleCount;
  31158. this.vertices[i].triangleCount = 0;
  31159. }
  31160. var newReferences = new Array(this.triangles.length * 3);
  31161. for (i = 0; i < this.triangles.length; ++i) {
  31162. t = this.triangles[i];
  31163. for (j = 0; j < 3; ++j) {
  31164. v = t.vertices[j];
  31165. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31166. v.triangleCount++;
  31167. }
  31168. }
  31169. this.references = newReferences;
  31170. if (identifyBorders) {
  31171. this.identifyBorder();
  31172. }
  31173. };
  31174. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31175. var x = point.x;
  31176. var y = point.y;
  31177. var z = point.z;
  31178. 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
  31179. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31180. };
  31181. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31182. var q = vertex1.q.add(vertex2.q);
  31183. var border = vertex1.isBorder && vertex2.isBorder;
  31184. var error = 0;
  31185. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31186. if (qDet !== 0 && !border) {
  31187. if (!pointResult) {
  31188. pointResult = BABYLON.Vector3.Zero();
  31189. }
  31190. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31191. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31192. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31193. error = this.vertexError(q, pointResult);
  31194. }
  31195. else {
  31196. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31197. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31198. var error1 = this.vertexError(q, vertex1.position);
  31199. var error2 = this.vertexError(q, vertex2.position);
  31200. var error3 = this.vertexError(q, p3);
  31201. error = Math.min(error1, error2, error3);
  31202. if (error === error1) {
  31203. if (pointResult) {
  31204. pointResult.copyFrom(vertex1.position);
  31205. }
  31206. }
  31207. else if (error === error2) {
  31208. if (pointResult) {
  31209. pointResult.copyFrom(vertex2.position);
  31210. }
  31211. }
  31212. else {
  31213. if (pointResult) {
  31214. pointResult.copyFrom(p3);
  31215. }
  31216. }
  31217. }
  31218. return error;
  31219. };
  31220. return QuadraticErrorSimplification;
  31221. })();
  31222. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31223. })(BABYLON || (BABYLON = {}));
  31224. var BABYLON;
  31225. (function (BABYLON) {
  31226. var serializedGeometries = [];
  31227. var serializeGeometry = function (geometry, serializationGeometries) {
  31228. if (serializedGeometries[geometry.id]) {
  31229. return;
  31230. }
  31231. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31232. serializationGeometries.boxes.push(geometry.serialize());
  31233. }
  31234. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31235. serializationGeometries.spheres.push(geometry.serialize());
  31236. }
  31237. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31238. serializationGeometries.cylinders.push(geometry.serialize());
  31239. }
  31240. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31241. serializationGeometries.toruses.push(geometry.serialize());
  31242. }
  31243. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31244. serializationGeometries.grounds.push(geometry.serialize());
  31245. }
  31246. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31247. serializationGeometries.planes.push(geometry.serialize());
  31248. }
  31249. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31250. serializationGeometries.torusKnots.push(geometry.serialize());
  31251. }
  31252. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31253. throw new Error("Unknown primitive type");
  31254. }
  31255. else {
  31256. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31257. }
  31258. serializedGeometries[geometry.id] = true;
  31259. };
  31260. var serializeMesh = function (mesh, serializationScene) {
  31261. var serializationObject = {};
  31262. serializationObject.name = mesh.name;
  31263. serializationObject.id = mesh.id;
  31264. if (BABYLON.Tags.HasTags(mesh)) {
  31265. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31266. }
  31267. serializationObject.position = mesh.position.asArray();
  31268. if (mesh.rotationQuaternion) {
  31269. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31270. }
  31271. else if (mesh.rotation) {
  31272. serializationObject.rotation = mesh.rotation.asArray();
  31273. }
  31274. serializationObject.scaling = mesh.scaling.asArray();
  31275. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31276. serializationObject.isEnabled = mesh.isEnabled();
  31277. serializationObject.isVisible = mesh.isVisible;
  31278. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31279. serializationObject.pickable = mesh.isPickable;
  31280. serializationObject.receiveShadows = mesh.receiveShadows;
  31281. serializationObject.billboardMode = mesh.billboardMode;
  31282. serializationObject.visibility = mesh.visibility;
  31283. serializationObject.checkCollisions = mesh.checkCollisions;
  31284. // Parent
  31285. if (mesh.parent) {
  31286. serializationObject.parentId = mesh.parent.id;
  31287. }
  31288. // Geometry
  31289. var geometry = mesh._geometry;
  31290. if (geometry) {
  31291. var geometryId = geometry.id;
  31292. serializationObject.geometryId = geometryId;
  31293. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31294. // 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
  31295. serializeGeometry(geometry, serializationScene.geometries);
  31296. }
  31297. // SubMeshes
  31298. serializationObject.subMeshes = [];
  31299. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31300. var subMesh = mesh.subMeshes[subIndex];
  31301. serializationObject.subMeshes.push({
  31302. materialIndex: subMesh.materialIndex,
  31303. verticesStart: subMesh.verticesStart,
  31304. verticesCount: subMesh.verticesCount,
  31305. indexStart: subMesh.indexStart,
  31306. indexCount: subMesh.indexCount
  31307. });
  31308. }
  31309. }
  31310. // Material
  31311. if (mesh.material) {
  31312. serializationObject.materialId = mesh.material.id;
  31313. }
  31314. else {
  31315. mesh.material = null;
  31316. }
  31317. // Skeleton
  31318. if (mesh.skeleton) {
  31319. serializationObject.skeletonId = mesh.skeleton.id;
  31320. }
  31321. // Physics
  31322. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31323. serializationObject.physicsMass = mesh.getPhysicsMass();
  31324. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31325. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31326. switch (mesh.getPhysicsImpostor()) {
  31327. case BABYLON.PhysicsEngine.BoxImpostor:
  31328. serializationObject.physicsImpostor = 1;
  31329. break;
  31330. case BABYLON.PhysicsEngine.SphereImpostor:
  31331. serializationObject.physicsImpostor = 2;
  31332. break;
  31333. }
  31334. }
  31335. // Instances
  31336. serializationObject.instances = [];
  31337. for (var index = 0; index < mesh.instances.length; index++) {
  31338. var instance = mesh.instances[index];
  31339. var serializationInstance = {
  31340. name: instance.name,
  31341. position: instance.position.asArray(),
  31342. scaling: instance.scaling.asArray()
  31343. };
  31344. if (instance.rotationQuaternion) {
  31345. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31346. }
  31347. else if (instance.rotation) {
  31348. serializationInstance.rotation = instance.rotation.asArray();
  31349. }
  31350. serializationObject.instances.push(serializationInstance);
  31351. // Animations
  31352. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31353. serializationInstance.ranges = instance.serializeAnimationRanges();
  31354. }
  31355. // Animations
  31356. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31357. serializationObject.ranges = mesh.serializeAnimationRanges();
  31358. // Layer mask
  31359. serializationObject.layerMask = mesh.layerMask;
  31360. return serializationObject;
  31361. };
  31362. var finalizeSingleMesh = function (mesh, serializationObject) {
  31363. //only works if the mesh is already loaded
  31364. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31365. //serialize material
  31366. if (mesh.material) {
  31367. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31368. serializationObject.materials = serializationObject.materials || [];
  31369. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31370. serializationObject.materials.push(mesh.material.serialize());
  31371. }
  31372. }
  31373. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31374. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31375. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31376. serializationObject.multiMaterials.push(mesh.material.serialize());
  31377. }
  31378. }
  31379. }
  31380. //serialize geometry
  31381. var geometry = mesh._geometry;
  31382. if (geometry) {
  31383. if (!serializationObject.geometries) {
  31384. serializationObject.geometries = {};
  31385. serializationObject.geometries.boxes = [];
  31386. serializationObject.geometries.spheres = [];
  31387. serializationObject.geometries.cylinders = [];
  31388. serializationObject.geometries.toruses = [];
  31389. serializationObject.geometries.grounds = [];
  31390. serializationObject.geometries.planes = [];
  31391. serializationObject.geometries.torusKnots = [];
  31392. serializationObject.geometries.vertexData = [];
  31393. }
  31394. serializeGeometry(geometry, serializationObject.geometries);
  31395. }
  31396. // Skeletons
  31397. if (mesh.skeleton) {
  31398. serializationObject.skeletons = serializationObject.skeletons || [];
  31399. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31400. }
  31401. //serialize the actual mesh
  31402. serializationObject.meshes = serializationObject.meshes || [];
  31403. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31404. }
  31405. };
  31406. var SceneSerializer = (function () {
  31407. function SceneSerializer() {
  31408. }
  31409. SceneSerializer.ClearCache = function () {
  31410. serializedGeometries = [];
  31411. };
  31412. SceneSerializer.Serialize = function (scene) {
  31413. var serializationObject = {};
  31414. // Scene
  31415. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  31416. serializationObject.autoClear = scene.autoClear;
  31417. serializationObject.clearColor = scene.clearColor.asArray();
  31418. serializationObject.ambientColor = scene.ambientColor.asArray();
  31419. serializationObject.gravity = scene.gravity.asArray();
  31420. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  31421. serializationObject.workerCollisions = scene.workerCollisions;
  31422. // Fog
  31423. if (scene.fogMode && scene.fogMode !== 0) {
  31424. serializationObject.fogMode = scene.fogMode;
  31425. serializationObject.fogColor = scene.fogColor.asArray();
  31426. serializationObject.fogStart = scene.fogStart;
  31427. serializationObject.fogEnd = scene.fogEnd;
  31428. serializationObject.fogDensity = scene.fogDensity;
  31429. }
  31430. //Physics
  31431. if (scene.isPhysicsEnabled()) {
  31432. serializationObject.physicsEnabled = true;
  31433. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  31434. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  31435. }
  31436. // Lights
  31437. serializationObject.lights = [];
  31438. var index;
  31439. var light;
  31440. for (index = 0; index < scene.lights.length; index++) {
  31441. light = scene.lights[index];
  31442. serializationObject.lights.push(light.serialize());
  31443. }
  31444. // Cameras
  31445. serializationObject.cameras = [];
  31446. for (index = 0; index < scene.cameras.length; index++) {
  31447. var camera = scene.cameras[index];
  31448. serializationObject.cameras.push(camera.serialize());
  31449. }
  31450. if (scene.activeCamera) {
  31451. serializationObject.activeCameraID = scene.activeCamera.id;
  31452. }
  31453. // Animations
  31454. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  31455. // Materials
  31456. serializationObject.materials = [];
  31457. serializationObject.multiMaterials = [];
  31458. var material;
  31459. for (index = 0; index < scene.materials.length; index++) {
  31460. material = scene.materials[index];
  31461. serializationObject.materials.push(material.serialize());
  31462. }
  31463. // MultiMaterials
  31464. serializationObject.multiMaterials = [];
  31465. for (index = 0; index < scene.multiMaterials.length; index++) {
  31466. var multiMaterial = scene.multiMaterials[index];
  31467. serializationObject.multiMaterials.push(multiMaterial.serialize());
  31468. }
  31469. // Skeletons
  31470. serializationObject.skeletons = [];
  31471. for (index = 0; index < scene.skeletons.length; index++) {
  31472. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  31473. }
  31474. // Geometries
  31475. serializationObject.geometries = {};
  31476. serializationObject.geometries.boxes = [];
  31477. serializationObject.geometries.spheres = [];
  31478. serializationObject.geometries.cylinders = [];
  31479. serializationObject.geometries.toruses = [];
  31480. serializationObject.geometries.grounds = [];
  31481. serializationObject.geometries.planes = [];
  31482. serializationObject.geometries.torusKnots = [];
  31483. serializationObject.geometries.vertexData = [];
  31484. serializedGeometries = [];
  31485. var geometries = scene.getGeometries();
  31486. for (index = 0; index < geometries.length; index++) {
  31487. var geometry = geometries[index];
  31488. if (geometry.isReady()) {
  31489. serializeGeometry(geometry, serializationObject.geometries);
  31490. }
  31491. }
  31492. // Meshes
  31493. serializationObject.meshes = [];
  31494. for (index = 0; index < scene.meshes.length; index++) {
  31495. var abstractMesh = scene.meshes[index];
  31496. if (abstractMesh instanceof BABYLON.Mesh) {
  31497. var mesh = abstractMesh;
  31498. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31499. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31500. }
  31501. }
  31502. }
  31503. // Particles Systems
  31504. serializationObject.particleSystems = [];
  31505. for (index = 0; index < scene.particleSystems.length; index++) {
  31506. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  31507. }
  31508. // Lens flares
  31509. serializationObject.lensFlareSystems = [];
  31510. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  31511. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  31512. }
  31513. // Shadows
  31514. serializationObject.shadowGenerators = [];
  31515. for (index = 0; index < scene.lights.length; index++) {
  31516. light = scene.lights[index];
  31517. if (light.getShadowGenerator()) {
  31518. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  31519. }
  31520. }
  31521. return serializationObject;
  31522. };
  31523. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  31524. if (withParents === void 0) { withParents = false; }
  31525. if (withChildren === void 0) { withChildren = false; }
  31526. var serializationObject = {};
  31527. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  31528. if (withParents || withChildren) {
  31529. //deliberate for loop! not for each, appended should be processed as well.
  31530. for (var i = 0; i < toSerialize.length; ++i) {
  31531. if (withChildren) {
  31532. toSerialize[i].getDescendants().forEach(function (node) {
  31533. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  31534. toSerialize.push(node);
  31535. }
  31536. });
  31537. }
  31538. //make sure the array doesn't contain the object already
  31539. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  31540. toSerialize.push(toSerialize[i].parent);
  31541. }
  31542. }
  31543. }
  31544. toSerialize.forEach(function (mesh) {
  31545. finalizeSingleMesh(mesh, serializationObject);
  31546. });
  31547. return serializationObject;
  31548. };
  31549. return SceneSerializer;
  31550. })();
  31551. BABYLON.SceneSerializer = SceneSerializer;
  31552. })(BABYLON || (BABYLON = {}));
  31553. var BABYLON;
  31554. (function (BABYLON) {
  31555. // Unique ID when we import meshes from Babylon to CSG
  31556. var currentCSGMeshId = 0;
  31557. // # class Vertex
  31558. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31559. // one to provide additional features like texture coordinates and vertex
  31560. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31561. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31562. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31563. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31564. // is not used anywhere else.
  31565. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31566. var Vertex = (function () {
  31567. function Vertex(pos, normal, uv) {
  31568. this.pos = pos;
  31569. this.normal = normal;
  31570. this.uv = uv;
  31571. }
  31572. Vertex.prototype.clone = function () {
  31573. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31574. };
  31575. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31576. // orientation of a polygon is flipped.
  31577. Vertex.prototype.flip = function () {
  31578. this.normal = this.normal.scale(-1);
  31579. };
  31580. // Create a new vertex between this vertex and `other` by linearly
  31581. // interpolating all properties using a parameter of `t`. Subclasses should
  31582. // override this to interpolate additional properties.
  31583. Vertex.prototype.interpolate = function (other, t) {
  31584. 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));
  31585. };
  31586. return Vertex;
  31587. })();
  31588. // # class Plane
  31589. // Represents a plane in 3D space.
  31590. var Plane = (function () {
  31591. function Plane(normal, w) {
  31592. this.normal = normal;
  31593. this.w = w;
  31594. }
  31595. Plane.FromPoints = function (a, b, c) {
  31596. var v0 = c.subtract(a);
  31597. var v1 = b.subtract(a);
  31598. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31599. return null;
  31600. }
  31601. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31602. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31603. };
  31604. Plane.prototype.clone = function () {
  31605. return new Plane(this.normal.clone(), this.w);
  31606. };
  31607. Plane.prototype.flip = function () {
  31608. this.normal.scaleInPlace(-1);
  31609. this.w = -this.w;
  31610. };
  31611. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31612. // fragments in the appropriate lists. Coplanar polygons go into either
  31613. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31614. // respect to this plane. Polygons in front or in back of this plane go into
  31615. // either `front` or `back`.
  31616. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31617. var COPLANAR = 0;
  31618. var FRONT = 1;
  31619. var BACK = 2;
  31620. var SPANNING = 3;
  31621. // Classify each point as well as the entire polygon into one of the above
  31622. // four classes.
  31623. var polygonType = 0;
  31624. var types = [];
  31625. var i;
  31626. var t;
  31627. for (i = 0; i < polygon.vertices.length; i++) {
  31628. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31629. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31630. polygonType |= type;
  31631. types.push(type);
  31632. }
  31633. // Put the polygon in the correct list, splitting it when necessary.
  31634. switch (polygonType) {
  31635. case COPLANAR:
  31636. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31637. break;
  31638. case FRONT:
  31639. front.push(polygon);
  31640. break;
  31641. case BACK:
  31642. back.push(polygon);
  31643. break;
  31644. case SPANNING:
  31645. var f = [], b = [];
  31646. for (i = 0; i < polygon.vertices.length; i++) {
  31647. var j = (i + 1) % polygon.vertices.length;
  31648. var ti = types[i], tj = types[j];
  31649. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31650. if (ti !== BACK)
  31651. f.push(vi);
  31652. if (ti !== FRONT)
  31653. b.push(ti !== BACK ? vi.clone() : vi);
  31654. if ((ti | tj) === SPANNING) {
  31655. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31656. var v = vi.interpolate(vj, t);
  31657. f.push(v);
  31658. b.push(v.clone());
  31659. }
  31660. }
  31661. var poly;
  31662. if (f.length >= 3) {
  31663. poly = new Polygon(f, polygon.shared);
  31664. if (poly.plane)
  31665. front.push(poly);
  31666. }
  31667. if (b.length >= 3) {
  31668. poly = new Polygon(b, polygon.shared);
  31669. if (poly.plane)
  31670. back.push(poly);
  31671. }
  31672. break;
  31673. }
  31674. };
  31675. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31676. // point is on the plane.
  31677. Plane.EPSILON = 1e-5;
  31678. return Plane;
  31679. })();
  31680. // # class Polygon
  31681. // Represents a convex polygon. The vertices used to initialize a polygon must
  31682. // be coplanar and form a convex loop.
  31683. //
  31684. // Each convex polygon has a `shared` property, which is shared between all
  31685. // polygons that are clones of each other or were split from the same polygon.
  31686. // This can be used to define per-polygon properties (such as surface color).
  31687. var Polygon = (function () {
  31688. function Polygon(vertices, shared) {
  31689. this.vertices = vertices;
  31690. this.shared = shared;
  31691. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31692. }
  31693. Polygon.prototype.clone = function () {
  31694. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31695. return new Polygon(vertices, this.shared);
  31696. };
  31697. Polygon.prototype.flip = function () {
  31698. this.vertices.reverse().map(function (v) { v.flip(); });
  31699. this.plane.flip();
  31700. };
  31701. return Polygon;
  31702. })();
  31703. // # class Node
  31704. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31705. // by picking a polygon to split along. That polygon (and all other coplanar
  31706. // polygons) are added directly to that node and the other polygons are added to
  31707. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31708. // no distinction between internal and leaf nodes.
  31709. var Node = (function () {
  31710. function Node(polygons) {
  31711. this.plane = null;
  31712. this.front = null;
  31713. this.back = null;
  31714. this.polygons = [];
  31715. if (polygons) {
  31716. this.build(polygons);
  31717. }
  31718. }
  31719. Node.prototype.clone = function () {
  31720. var node = new Node();
  31721. node.plane = this.plane && this.plane.clone();
  31722. node.front = this.front && this.front.clone();
  31723. node.back = this.back && this.back.clone();
  31724. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31725. return node;
  31726. };
  31727. // Convert solid space to empty space and empty space to solid space.
  31728. Node.prototype.invert = function () {
  31729. for (var i = 0; i < this.polygons.length; i++) {
  31730. this.polygons[i].flip();
  31731. }
  31732. if (this.plane) {
  31733. this.plane.flip();
  31734. }
  31735. if (this.front) {
  31736. this.front.invert();
  31737. }
  31738. if (this.back) {
  31739. this.back.invert();
  31740. }
  31741. var temp = this.front;
  31742. this.front = this.back;
  31743. this.back = temp;
  31744. };
  31745. // Recursively remove all polygons in `polygons` that are inside this BSP
  31746. // tree.
  31747. Node.prototype.clipPolygons = function (polygons) {
  31748. if (!this.plane)
  31749. return polygons.slice();
  31750. var front = [], back = [];
  31751. for (var i = 0; i < polygons.length; i++) {
  31752. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31753. }
  31754. if (this.front) {
  31755. front = this.front.clipPolygons(front);
  31756. }
  31757. if (this.back) {
  31758. back = this.back.clipPolygons(back);
  31759. }
  31760. else {
  31761. back = [];
  31762. }
  31763. return front.concat(back);
  31764. };
  31765. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31766. // `bsp`.
  31767. Node.prototype.clipTo = function (bsp) {
  31768. this.polygons = bsp.clipPolygons(this.polygons);
  31769. if (this.front)
  31770. this.front.clipTo(bsp);
  31771. if (this.back)
  31772. this.back.clipTo(bsp);
  31773. };
  31774. // Return a list of all polygons in this BSP tree.
  31775. Node.prototype.allPolygons = function () {
  31776. var polygons = this.polygons.slice();
  31777. if (this.front)
  31778. polygons = polygons.concat(this.front.allPolygons());
  31779. if (this.back)
  31780. polygons = polygons.concat(this.back.allPolygons());
  31781. return polygons;
  31782. };
  31783. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31784. // new polygons are filtered down to the bottom of the tree and become new
  31785. // nodes there. Each set of polygons is partitioned using the first polygon
  31786. // (no heuristic is used to pick a good split).
  31787. Node.prototype.build = function (polygons) {
  31788. if (!polygons.length)
  31789. return;
  31790. if (!this.plane)
  31791. this.plane = polygons[0].plane.clone();
  31792. var front = [], back = [];
  31793. for (var i = 0; i < polygons.length; i++) {
  31794. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31795. }
  31796. if (front.length) {
  31797. if (!this.front)
  31798. this.front = new Node();
  31799. this.front.build(front);
  31800. }
  31801. if (back.length) {
  31802. if (!this.back)
  31803. this.back = new Node();
  31804. this.back.build(back);
  31805. }
  31806. };
  31807. return Node;
  31808. })();
  31809. var CSG = (function () {
  31810. function CSG() {
  31811. this.polygons = new Array();
  31812. }
  31813. // Convert BABYLON.Mesh to BABYLON.CSG
  31814. CSG.FromMesh = function (mesh) {
  31815. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31816. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31817. if (mesh instanceof BABYLON.Mesh) {
  31818. mesh.computeWorldMatrix(true);
  31819. matrix = mesh.getWorldMatrix();
  31820. meshPosition = mesh.position.clone();
  31821. meshRotation = mesh.rotation.clone();
  31822. if (mesh.rotationQuaternion) {
  31823. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31824. }
  31825. meshScaling = mesh.scaling.clone();
  31826. }
  31827. else {
  31828. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31829. }
  31830. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31831. var subMeshes = mesh.subMeshes;
  31832. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31833. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31834. vertices = [];
  31835. for (var j = 0; j < 3; j++) {
  31836. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31837. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31838. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31839. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31840. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31841. vertex = new Vertex(position, normal, uv);
  31842. vertices.push(vertex);
  31843. }
  31844. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31845. // To handle the case of degenerated triangle
  31846. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31847. if (polygon.plane)
  31848. polygons.push(polygon);
  31849. }
  31850. }
  31851. var csg = CSG.FromPolygons(polygons);
  31852. csg.matrix = matrix;
  31853. csg.position = meshPosition;
  31854. csg.rotation = meshRotation;
  31855. csg.scaling = meshScaling;
  31856. csg.rotationQuaternion = meshRotationQuaternion;
  31857. currentCSGMeshId++;
  31858. return csg;
  31859. };
  31860. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31861. CSG.FromPolygons = function (polygons) {
  31862. var csg = new CSG();
  31863. csg.polygons = polygons;
  31864. return csg;
  31865. };
  31866. CSG.prototype.clone = function () {
  31867. var csg = new CSG();
  31868. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31869. csg.copyTransformAttributes(this);
  31870. return csg;
  31871. };
  31872. CSG.prototype.toPolygons = function () {
  31873. return this.polygons;
  31874. };
  31875. CSG.prototype.union = function (csg) {
  31876. var a = new Node(this.clone().polygons);
  31877. var b = new Node(csg.clone().polygons);
  31878. a.clipTo(b);
  31879. b.clipTo(a);
  31880. b.invert();
  31881. b.clipTo(a);
  31882. b.invert();
  31883. a.build(b.allPolygons());
  31884. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31885. };
  31886. CSG.prototype.unionInPlace = function (csg) {
  31887. var a = new Node(this.polygons);
  31888. var b = new Node(csg.polygons);
  31889. a.clipTo(b);
  31890. b.clipTo(a);
  31891. b.invert();
  31892. b.clipTo(a);
  31893. b.invert();
  31894. a.build(b.allPolygons());
  31895. this.polygons = a.allPolygons();
  31896. };
  31897. CSG.prototype.subtract = function (csg) {
  31898. var a = new Node(this.clone().polygons);
  31899. var b = new Node(csg.clone().polygons);
  31900. a.invert();
  31901. a.clipTo(b);
  31902. b.clipTo(a);
  31903. b.invert();
  31904. b.clipTo(a);
  31905. b.invert();
  31906. a.build(b.allPolygons());
  31907. a.invert();
  31908. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31909. };
  31910. CSG.prototype.subtractInPlace = function (csg) {
  31911. var a = new Node(this.polygons);
  31912. var b = new Node(csg.polygons);
  31913. a.invert();
  31914. a.clipTo(b);
  31915. b.clipTo(a);
  31916. b.invert();
  31917. b.clipTo(a);
  31918. b.invert();
  31919. a.build(b.allPolygons());
  31920. a.invert();
  31921. this.polygons = a.allPolygons();
  31922. };
  31923. CSG.prototype.intersect = function (csg) {
  31924. var a = new Node(this.clone().polygons);
  31925. var b = new Node(csg.clone().polygons);
  31926. a.invert();
  31927. b.clipTo(a);
  31928. b.invert();
  31929. a.clipTo(b);
  31930. b.clipTo(a);
  31931. a.build(b.allPolygons());
  31932. a.invert();
  31933. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31934. };
  31935. CSG.prototype.intersectInPlace = function (csg) {
  31936. var a = new Node(this.polygons);
  31937. var b = new Node(csg.polygons);
  31938. a.invert();
  31939. b.clipTo(a);
  31940. b.invert();
  31941. a.clipTo(b);
  31942. b.clipTo(a);
  31943. a.build(b.allPolygons());
  31944. a.invert();
  31945. this.polygons = a.allPolygons();
  31946. };
  31947. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31948. // not modified.
  31949. CSG.prototype.inverse = function () {
  31950. var csg = this.clone();
  31951. csg.inverseInPlace();
  31952. return csg;
  31953. };
  31954. CSG.prototype.inverseInPlace = function () {
  31955. this.polygons.map(function (p) { p.flip(); });
  31956. };
  31957. // This is used to keep meshes transformations so they can be restored
  31958. // when we build back a Babylon Mesh
  31959. // NB : All CSG operations are performed in world coordinates
  31960. CSG.prototype.copyTransformAttributes = function (csg) {
  31961. this.matrix = csg.matrix;
  31962. this.position = csg.position;
  31963. this.rotation = csg.rotation;
  31964. this.scaling = csg.scaling;
  31965. this.rotationQuaternion = csg.rotationQuaternion;
  31966. return this;
  31967. };
  31968. // Build Raw mesh from CSG
  31969. // Coordinates here are in world space
  31970. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31971. var matrix = this.matrix.clone();
  31972. matrix.invert();
  31973. 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;
  31974. if (keepSubMeshes) {
  31975. // Sort Polygons, since subMeshes are indices range
  31976. polygons.sort(function (a, b) {
  31977. if (a.shared.meshId === b.shared.meshId) {
  31978. return a.shared.subMeshId - b.shared.subMeshId;
  31979. }
  31980. else {
  31981. return a.shared.meshId - b.shared.meshId;
  31982. }
  31983. });
  31984. }
  31985. for (var i = 0, il = polygons.length; i < il; i++) {
  31986. polygon = polygons[i];
  31987. // Building SubMeshes
  31988. if (!subMesh_dict[polygon.shared.meshId]) {
  31989. subMesh_dict[polygon.shared.meshId] = {};
  31990. }
  31991. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31992. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31993. indexStart: +Infinity,
  31994. indexEnd: -Infinity,
  31995. materialIndex: polygon.shared.materialIndex
  31996. };
  31997. }
  31998. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31999. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32000. polygonIndices[0] = 0;
  32001. polygonIndices[1] = j - 1;
  32002. polygonIndices[2] = j;
  32003. for (var k = 0; k < 3; k++) {
  32004. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32005. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32006. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32007. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32008. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32009. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32010. // Check if 2 points can be merged
  32011. if (!(typeof vertex_idx !== 'undefined' &&
  32012. normals[vertex_idx * 3] === localNormal.x &&
  32013. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32014. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32015. uvs[vertex_idx * 2] === uv.x &&
  32016. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32017. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32018. uvs.push(uv.x, uv.y);
  32019. normals.push(normal.x, normal.y, normal.z);
  32020. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32021. }
  32022. indices.push(vertex_idx);
  32023. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32024. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32025. currentIndex++;
  32026. }
  32027. }
  32028. }
  32029. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32030. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32031. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32032. mesh.setIndices(indices);
  32033. if (keepSubMeshes) {
  32034. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32035. var materialIndexOffset = 0, materialMaxIndex;
  32036. mesh.subMeshes = new Array();
  32037. for (var m in subMesh_dict) {
  32038. materialMaxIndex = -1;
  32039. for (var sm in subMesh_dict[m]) {
  32040. subMesh_obj = subMesh_dict[m][sm];
  32041. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32042. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32043. }
  32044. materialIndexOffset += ++materialMaxIndex;
  32045. }
  32046. }
  32047. return mesh;
  32048. };
  32049. // Build Mesh from CSG taking material and transforms into account
  32050. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32051. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32052. mesh.material = material;
  32053. mesh.position.copyFrom(this.position);
  32054. mesh.rotation.copyFrom(this.rotation);
  32055. if (this.rotationQuaternion) {
  32056. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32057. }
  32058. mesh.scaling.copyFrom(this.scaling);
  32059. mesh.computeWorldMatrix(true);
  32060. return mesh;
  32061. };
  32062. return CSG;
  32063. })();
  32064. BABYLON.CSG = CSG;
  32065. })(BABYLON || (BABYLON = {}));
  32066. var BABYLON;
  32067. (function (BABYLON) {
  32068. var VRDistortionCorrectionPostProcess = (function (_super) {
  32069. __extends(VRDistortionCorrectionPostProcess, _super);
  32070. //ANY
  32071. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32072. var _this = this;
  32073. _super.call(this, name, "vrDistortionCorrection", [
  32074. 'LensCenter',
  32075. 'Scale',
  32076. 'ScaleIn',
  32077. 'HmdWarpParam'
  32078. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32079. this._isRightEye = isRightEye;
  32080. this._distortionFactors = vrMetrics.distortionK;
  32081. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32082. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32083. this.onSizeChanged = function () {
  32084. _this.aspectRatio = _this.width * .5 / _this.height;
  32085. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32086. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32087. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32088. };
  32089. this.onApply = function (effect) {
  32090. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32091. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32092. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32093. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32094. };
  32095. }
  32096. return VRDistortionCorrectionPostProcess;
  32097. })(BABYLON.PostProcess);
  32098. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32099. })(BABYLON || (BABYLON = {}));
  32100. // Mainly based on these 2 articles :
  32101. // 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
  32102. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32103. var BABYLON;
  32104. (function (BABYLON) {
  32105. (function (JoystickAxis) {
  32106. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32107. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32108. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32109. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32110. var JoystickAxis = BABYLON.JoystickAxis;
  32111. var VirtualJoystick = (function () {
  32112. function VirtualJoystick(leftJoystick) {
  32113. var _this = this;
  32114. if (leftJoystick) {
  32115. this._leftJoystick = true;
  32116. }
  32117. else {
  32118. this._leftJoystick = false;
  32119. }
  32120. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32121. VirtualJoystick._globalJoystickIndex++;
  32122. // By default left & right arrow keys are moving the X
  32123. // and up & down keys are moving the Y
  32124. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32125. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32126. this.reverseLeftRight = false;
  32127. this.reverseUpDown = false;
  32128. // collections of pointers
  32129. this._touches = new BABYLON.SmartCollection();
  32130. this.deltaPosition = BABYLON.Vector3.Zero();
  32131. this._joystickSensibility = 25;
  32132. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32133. this._rotationSpeed = 25;
  32134. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32135. this._rotateOnAxisRelativeToMesh = false;
  32136. this._onResize = function (evt) {
  32137. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32138. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32139. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32140. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32141. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32142. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32143. };
  32144. // injecting a canvas element on top of the canvas 3D game
  32145. if (!VirtualJoystick.vjCanvas) {
  32146. window.addEventListener("resize", this._onResize, false);
  32147. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32148. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32149. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32150. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32151. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32152. VirtualJoystick.vjCanvas.style.width = "100%";
  32153. VirtualJoystick.vjCanvas.style.height = "100%";
  32154. VirtualJoystick.vjCanvas.style.position = "absolute";
  32155. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32156. VirtualJoystick.vjCanvas.style.top = "0px";
  32157. VirtualJoystick.vjCanvas.style.left = "0px";
  32158. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32159. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32160. // Support for jQuery PEP polyfill
  32161. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32162. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32163. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32164. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32165. document.body.appendChild(VirtualJoystick.vjCanvas);
  32166. }
  32167. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32168. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32169. this.pressed = false;
  32170. // default joystick color
  32171. this._joystickColor = "cyan";
  32172. this._joystickPointerID = -1;
  32173. // current joystick position
  32174. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32175. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32176. // origin joystick position
  32177. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32178. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32179. this._onPointerDownHandlerRef = function (evt) {
  32180. _this._onPointerDown(evt);
  32181. };
  32182. this._onPointerMoveHandlerRef = function (evt) {
  32183. _this._onPointerMove(evt);
  32184. };
  32185. this._onPointerOutHandlerRef = function (evt) {
  32186. _this._onPointerUp(evt);
  32187. };
  32188. this._onPointerUpHandlerRef = function (evt) {
  32189. _this._onPointerUp(evt);
  32190. };
  32191. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32192. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32193. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32194. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32195. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32196. evt.preventDefault(); // Disables system menu
  32197. }, false);
  32198. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32199. }
  32200. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32201. this._joystickSensibility = newJoystickSensibility;
  32202. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32203. };
  32204. VirtualJoystick.prototype._onPointerDown = function (e) {
  32205. var positionOnScreenCondition;
  32206. e.preventDefault();
  32207. if (this._leftJoystick === true) {
  32208. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32209. }
  32210. else {
  32211. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32212. }
  32213. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32214. // First contact will be dedicated to the virtual joystick
  32215. this._joystickPointerID = e.pointerId;
  32216. this._joystickPointerStartPos.x = e.clientX;
  32217. this._joystickPointerStartPos.y = e.clientY;
  32218. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32219. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32220. this._deltaJoystickVector.x = 0;
  32221. this._deltaJoystickVector.y = 0;
  32222. this.pressed = true;
  32223. this._touches.add(e.pointerId.toString(), e);
  32224. }
  32225. else {
  32226. // You can only trigger the action buttons with a joystick declared
  32227. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32228. this._action();
  32229. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32230. }
  32231. }
  32232. };
  32233. VirtualJoystick.prototype._onPointerMove = function (e) {
  32234. // If the current pointer is the one associated to the joystick (first touch contact)
  32235. if (this._joystickPointerID == e.pointerId) {
  32236. this._joystickPointerPos.x = e.clientX;
  32237. this._joystickPointerPos.y = e.clientY;
  32238. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32239. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32240. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32241. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32242. switch (this._axisTargetedByLeftAndRight) {
  32243. case JoystickAxis.X:
  32244. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32245. break;
  32246. case JoystickAxis.Y:
  32247. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32248. break;
  32249. case JoystickAxis.Z:
  32250. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32251. break;
  32252. }
  32253. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32254. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32255. switch (this._axisTargetedByUpAndDown) {
  32256. case JoystickAxis.X:
  32257. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32258. break;
  32259. case JoystickAxis.Y:
  32260. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32261. break;
  32262. case JoystickAxis.Z:
  32263. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32264. break;
  32265. }
  32266. }
  32267. else {
  32268. if (this._touches.item(e.pointerId.toString())) {
  32269. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32270. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32271. }
  32272. }
  32273. };
  32274. VirtualJoystick.prototype._onPointerUp = function (e) {
  32275. if (this._joystickPointerID == e.pointerId) {
  32276. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32277. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32278. this._joystickPointerID = -1;
  32279. this.pressed = false;
  32280. }
  32281. else {
  32282. var touch = this._touches.item(e.pointerId.toString());
  32283. if (touch) {
  32284. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32285. }
  32286. }
  32287. this._deltaJoystickVector.x = 0;
  32288. this._deltaJoystickVector.y = 0;
  32289. this._touches.remove(e.pointerId.toString());
  32290. };
  32291. /**
  32292. * Change the color of the virtual joystick
  32293. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32294. */
  32295. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32296. this._joystickColor = newColor;
  32297. };
  32298. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32299. this._action = action;
  32300. };
  32301. // Define which axis you'd like to control for left & right
  32302. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32303. switch (axis) {
  32304. case JoystickAxis.X:
  32305. case JoystickAxis.Y:
  32306. case JoystickAxis.Z:
  32307. this._axisTargetedByLeftAndRight = axis;
  32308. break;
  32309. default:
  32310. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32311. break;
  32312. }
  32313. };
  32314. // Define which axis you'd like to control for up & down
  32315. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32316. switch (axis) {
  32317. case JoystickAxis.X:
  32318. case JoystickAxis.Y:
  32319. case JoystickAxis.Z:
  32320. this._axisTargetedByUpAndDown = axis;
  32321. break;
  32322. default:
  32323. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32324. break;
  32325. }
  32326. };
  32327. VirtualJoystick.prototype._clearCanvas = function () {
  32328. if (this._leftJoystick) {
  32329. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32330. }
  32331. else {
  32332. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32333. }
  32334. };
  32335. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32336. var _this = this;
  32337. if (this.pressed) {
  32338. this._touches.forEach(function (touch) {
  32339. if (touch.pointerId === _this._joystickPointerID) {
  32340. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32341. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32342. VirtualJoystick.vjCanvasContext.beginPath();
  32343. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32344. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32345. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32346. VirtualJoystick.vjCanvasContext.stroke();
  32347. VirtualJoystick.vjCanvasContext.closePath();
  32348. VirtualJoystick.vjCanvasContext.beginPath();
  32349. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32350. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32351. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32352. VirtualJoystick.vjCanvasContext.stroke();
  32353. VirtualJoystick.vjCanvasContext.closePath();
  32354. VirtualJoystick.vjCanvasContext.beginPath();
  32355. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32356. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32357. VirtualJoystick.vjCanvasContext.stroke();
  32358. VirtualJoystick.vjCanvasContext.closePath();
  32359. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32360. }
  32361. else {
  32362. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32363. VirtualJoystick.vjCanvasContext.beginPath();
  32364. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32365. VirtualJoystick.vjCanvasContext.beginPath();
  32366. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32367. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32368. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32369. VirtualJoystick.vjCanvasContext.stroke();
  32370. VirtualJoystick.vjCanvasContext.closePath();
  32371. touch.prevX = touch.x;
  32372. touch.prevY = touch.y;
  32373. }
  32374. ;
  32375. });
  32376. }
  32377. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32378. };
  32379. VirtualJoystick.prototype.releaseCanvas = function () {
  32380. if (VirtualJoystick.vjCanvas) {
  32381. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32382. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32383. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32384. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32385. window.removeEventListener("resize", this._onResize);
  32386. document.body.removeChild(VirtualJoystick.vjCanvas);
  32387. VirtualJoystick.vjCanvas = null;
  32388. }
  32389. };
  32390. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32391. VirtualJoystick._globalJoystickIndex = 0;
  32392. return VirtualJoystick;
  32393. })();
  32394. BABYLON.VirtualJoystick = VirtualJoystick;
  32395. })(BABYLON || (BABYLON = {}));
  32396. var BABYLON;
  32397. (function (BABYLON) {
  32398. // We're mainly based on the logic defined into the FreeCamera code
  32399. var VirtualJoysticksCamera = (function (_super) {
  32400. __extends(VirtualJoysticksCamera, _super);
  32401. function VirtualJoysticksCamera(name, position, scene) {
  32402. _super.call(this, name, position, scene);
  32403. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32404. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32405. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32406. this._leftjoystick.setJoystickSensibility(0.15);
  32407. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32408. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32409. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32410. this._rightjoystick.reverseUpDown = true;
  32411. this._rightjoystick.setJoystickSensibility(0.05);
  32412. this._rightjoystick.setJoystickColor("yellow");
  32413. }
  32414. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  32415. return this._leftjoystick;
  32416. };
  32417. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  32418. return this._rightjoystick;
  32419. };
  32420. VirtualJoysticksCamera.prototype._checkInputs = function () {
  32421. var speed = this._computeLocalCameraSpeed() * 50;
  32422. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32423. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  32424. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32425. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  32426. if (!this._leftjoystick.pressed) {
  32427. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  32428. }
  32429. if (!this._rightjoystick.pressed) {
  32430. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  32431. }
  32432. _super.prototype._checkInputs.call(this);
  32433. };
  32434. VirtualJoysticksCamera.prototype.dispose = function () {
  32435. this._leftjoystick.releaseCanvas();
  32436. _super.prototype.dispose.call(this);
  32437. };
  32438. return VirtualJoysticksCamera;
  32439. })(BABYLON.FreeCamera);
  32440. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  32441. })(BABYLON || (BABYLON = {}));
  32442. var BABYLON;
  32443. (function (BABYLON) {
  32444. var AnaglyphPostProcess = (function (_super) {
  32445. __extends(AnaglyphPostProcess, _super);
  32446. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32447. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  32448. }
  32449. return AnaglyphPostProcess;
  32450. })(BABYLON.PostProcess);
  32451. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  32452. })(BABYLON || (BABYLON = {}));
  32453. var BABYLON;
  32454. (function (BABYLON) {
  32455. var OutlineRenderer = (function () {
  32456. function OutlineRenderer(scene) {
  32457. this._scene = scene;
  32458. }
  32459. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  32460. var _this = this;
  32461. if (useOverlay === void 0) { useOverlay = false; }
  32462. var scene = this._scene;
  32463. var engine = this._scene.getEngine();
  32464. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32465. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  32466. return;
  32467. }
  32468. var mesh = subMesh.getRenderingMesh();
  32469. var material = subMesh.getMaterial();
  32470. engine.enableEffect(this._effect);
  32471. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  32472. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  32473. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32474. // Bones
  32475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32476. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32477. }
  32478. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  32479. // Alpha test
  32480. if (material && material.needAlphaTesting()) {
  32481. var alphaTexture = material.getAlphaTestTexture();
  32482. this._effect.setTexture("diffuseSampler", alphaTexture);
  32483. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32484. }
  32485. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  32486. };
  32487. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  32488. var defines = [];
  32489. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  32490. var mesh = subMesh.getMesh();
  32491. var material = subMesh.getMaterial();
  32492. // Alpha test
  32493. if (material && material.needAlphaTesting()) {
  32494. defines.push("#define ALPHATEST");
  32495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32496. attribs.push(BABYLON.VertexBuffer.UVKind);
  32497. defines.push("#define UV1");
  32498. }
  32499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32500. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32501. defines.push("#define UV2");
  32502. }
  32503. }
  32504. // Bones
  32505. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32506. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32507. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32508. if (mesh.numBoneInfluencers > 4) {
  32509. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32510. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32511. }
  32512. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32513. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32514. }
  32515. else {
  32516. defines.push("#define NUM_BONE_INFLUENCERS 0");
  32517. }
  32518. // Instances
  32519. if (useInstances) {
  32520. defines.push("#define INSTANCES");
  32521. attribs.push("world0");
  32522. attribs.push("world1");
  32523. attribs.push("world2");
  32524. attribs.push("world3");
  32525. }
  32526. // Get correct effect
  32527. var join = defines.join("\n");
  32528. if (this._cachedDefines !== join) {
  32529. this._cachedDefines = join;
  32530. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  32531. }
  32532. return this._effect.isReady();
  32533. };
  32534. return OutlineRenderer;
  32535. })();
  32536. BABYLON.OutlineRenderer = OutlineRenderer;
  32537. })(BABYLON || (BABYLON = {}));
  32538. var BABYLON;
  32539. (function (BABYLON) {
  32540. var MeshAssetTask = (function () {
  32541. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  32542. this.name = name;
  32543. this.meshesNames = meshesNames;
  32544. this.rootUrl = rootUrl;
  32545. this.sceneFilename = sceneFilename;
  32546. this.isCompleted = false;
  32547. }
  32548. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32549. var _this = this;
  32550. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32551. _this.loadedMeshes = meshes;
  32552. _this.loadedParticleSystems = particleSystems;
  32553. _this.loadedSkeletons = skeletons;
  32554. _this.isCompleted = true;
  32555. if (_this.onSuccess) {
  32556. _this.onSuccess(_this);
  32557. }
  32558. onSuccess();
  32559. }, null, function () {
  32560. if (_this.onError) {
  32561. _this.onError(_this);
  32562. }
  32563. onError();
  32564. });
  32565. };
  32566. return MeshAssetTask;
  32567. })();
  32568. BABYLON.MeshAssetTask = MeshAssetTask;
  32569. var TextFileAssetTask = (function () {
  32570. function TextFileAssetTask(name, url) {
  32571. this.name = name;
  32572. this.url = url;
  32573. this.isCompleted = false;
  32574. }
  32575. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32576. var _this = this;
  32577. BABYLON.Tools.LoadFile(this.url, function (data) {
  32578. _this.text = data;
  32579. _this.isCompleted = true;
  32580. if (_this.onSuccess) {
  32581. _this.onSuccess(_this);
  32582. }
  32583. onSuccess();
  32584. }, null, scene.database, false, function () {
  32585. if (_this.onError) {
  32586. _this.onError(_this);
  32587. }
  32588. onError();
  32589. });
  32590. };
  32591. return TextFileAssetTask;
  32592. })();
  32593. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32594. var BinaryFileAssetTask = (function () {
  32595. function BinaryFileAssetTask(name, url) {
  32596. this.name = name;
  32597. this.url = url;
  32598. this.isCompleted = false;
  32599. }
  32600. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32601. var _this = this;
  32602. BABYLON.Tools.LoadFile(this.url, function (data) {
  32603. _this.data = data;
  32604. _this.isCompleted = true;
  32605. if (_this.onSuccess) {
  32606. _this.onSuccess(_this);
  32607. }
  32608. onSuccess();
  32609. }, null, scene.database, true, function () {
  32610. if (_this.onError) {
  32611. _this.onError(_this);
  32612. }
  32613. onError();
  32614. });
  32615. };
  32616. return BinaryFileAssetTask;
  32617. })();
  32618. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32619. var ImageAssetTask = (function () {
  32620. function ImageAssetTask(name, url) {
  32621. this.name = name;
  32622. this.url = url;
  32623. this.isCompleted = false;
  32624. }
  32625. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32626. var _this = this;
  32627. var img = new Image();
  32628. img.onload = function () {
  32629. _this.image = img;
  32630. _this.isCompleted = true;
  32631. if (_this.onSuccess) {
  32632. _this.onSuccess(_this);
  32633. }
  32634. onSuccess();
  32635. };
  32636. img.onerror = function () {
  32637. if (_this.onError) {
  32638. _this.onError(_this);
  32639. }
  32640. onError();
  32641. };
  32642. img.src = this.url;
  32643. };
  32644. return ImageAssetTask;
  32645. })();
  32646. BABYLON.ImageAssetTask = ImageAssetTask;
  32647. var TextureAssetTask = (function () {
  32648. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32650. this.name = name;
  32651. this.url = url;
  32652. this.noMipmap = noMipmap;
  32653. this.invertY = invertY;
  32654. this.samplingMode = samplingMode;
  32655. this.isCompleted = false;
  32656. }
  32657. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32658. var _this = this;
  32659. var onload = function () {
  32660. _this.isCompleted = true;
  32661. if (_this.onSuccess) {
  32662. _this.onSuccess(_this);
  32663. }
  32664. onSuccess();
  32665. };
  32666. var onerror = function () {
  32667. if (_this.onError) {
  32668. _this.onError(_this);
  32669. }
  32670. onError();
  32671. };
  32672. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32673. };
  32674. return TextureAssetTask;
  32675. })();
  32676. BABYLON.TextureAssetTask = TextureAssetTask;
  32677. var AssetsManager = (function () {
  32678. function AssetsManager(scene) {
  32679. this._tasks = new Array();
  32680. this._waitingTasksCount = 0;
  32681. this.useDefaultLoadingScreen = true;
  32682. this._scene = scene;
  32683. }
  32684. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32685. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32686. this._tasks.push(task);
  32687. return task;
  32688. };
  32689. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32690. var task = new TextFileAssetTask(taskName, url);
  32691. this._tasks.push(task);
  32692. return task;
  32693. };
  32694. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32695. var task = new BinaryFileAssetTask(taskName, url);
  32696. this._tasks.push(task);
  32697. return task;
  32698. };
  32699. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32700. var task = new ImageAssetTask(taskName, url);
  32701. this._tasks.push(task);
  32702. return task;
  32703. };
  32704. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32706. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32707. this._tasks.push(task);
  32708. return task;
  32709. };
  32710. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32711. this._waitingTasksCount--;
  32712. if (this._waitingTasksCount === 0) {
  32713. if (this.onFinish) {
  32714. this.onFinish(this._tasks);
  32715. }
  32716. this._scene.getEngine().hideLoadingUI();
  32717. }
  32718. };
  32719. AssetsManager.prototype._runTask = function (task) {
  32720. var _this = this;
  32721. task.run(this._scene, function () {
  32722. if (_this.onTaskSuccess) {
  32723. _this.onTaskSuccess(task);
  32724. }
  32725. _this._decreaseWaitingTasksCount();
  32726. }, function () {
  32727. if (_this.onTaskError) {
  32728. _this.onTaskError(task);
  32729. }
  32730. _this._decreaseWaitingTasksCount();
  32731. });
  32732. };
  32733. AssetsManager.prototype.reset = function () {
  32734. this._tasks = new Array();
  32735. return this;
  32736. };
  32737. AssetsManager.prototype.load = function () {
  32738. this._waitingTasksCount = this._tasks.length;
  32739. if (this._waitingTasksCount === 0) {
  32740. if (this.onFinish) {
  32741. this.onFinish(this._tasks);
  32742. }
  32743. return this;
  32744. }
  32745. if (this.useDefaultLoadingScreen) {
  32746. this._scene.getEngine().displayLoadingUI();
  32747. }
  32748. for (var index = 0; index < this._tasks.length; index++) {
  32749. var task = this._tasks[index];
  32750. this._runTask(task);
  32751. }
  32752. return this;
  32753. };
  32754. return AssetsManager;
  32755. })();
  32756. BABYLON.AssetsManager = AssetsManager;
  32757. })(BABYLON || (BABYLON = {}));
  32758. var BABYLON;
  32759. (function (BABYLON) {
  32760. var VRDeviceOrientationFreeCamera = (function (_super) {
  32761. __extends(VRDeviceOrientationFreeCamera, _super);
  32762. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32763. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32764. _super.call(this, name, position, scene);
  32765. this._alpha = 0;
  32766. this._beta = 0;
  32767. this._gamma = 0;
  32768. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32769. metrics.compensateDistortion = compensateDistortion;
  32770. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32771. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32772. }
  32773. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32774. this._alpha = +evt.alpha | 0;
  32775. this._beta = +evt.beta | 0;
  32776. this._gamma = +evt.gamma | 0;
  32777. if (this._gamma < 0) {
  32778. this._gamma = 90 + this._gamma;
  32779. }
  32780. else {
  32781. // Incline it in the correct angle.
  32782. this._gamma = 270 - this._gamma;
  32783. }
  32784. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32785. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32786. this.rotation.z = this._beta / 180.0 * Math.PI;
  32787. };
  32788. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32789. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32790. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32791. };
  32792. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32793. _super.prototype.detachControl.call(this, element);
  32794. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32795. };
  32796. return VRDeviceOrientationFreeCamera;
  32797. })(BABYLON.FreeCamera);
  32798. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32799. })(BABYLON || (BABYLON = {}));
  32800. var BABYLON;
  32801. (function (BABYLON) {
  32802. var WebVRFreeCamera = (function (_super) {
  32803. __extends(WebVRFreeCamera, _super);
  32804. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32805. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32806. _super.call(this, name, position, scene);
  32807. this._hmdDevice = null;
  32808. this._sensorDevice = null;
  32809. this._cacheState = null;
  32810. this._cacheQuaternion = new BABYLON.Quaternion();
  32811. this._cacheRotation = BABYLON.Vector3.Zero();
  32812. this._vrEnabled = false;
  32813. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32814. metrics.compensateDistortion = compensateDistortion;
  32815. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32816. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32817. }
  32818. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32819. var size = devices.length;
  32820. var i = 0;
  32821. // Reset devices.
  32822. this._sensorDevice = null;
  32823. this._hmdDevice = null;
  32824. // Search for a HmdDevice.
  32825. while (i < size && this._hmdDevice === null) {
  32826. if (devices[i] instanceof HMDVRDevice) {
  32827. this._hmdDevice = devices[i];
  32828. }
  32829. i++;
  32830. }
  32831. i = 0;
  32832. while (i < size && this._sensorDevice === null) {
  32833. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32834. this._sensorDevice = devices[i];
  32835. }
  32836. i++;
  32837. }
  32838. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32839. };
  32840. WebVRFreeCamera.prototype._checkInputs = function () {
  32841. if (this._vrEnabled) {
  32842. this._cacheState = this._sensorDevice.getState();
  32843. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32844. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32845. this.rotation.x = -this._cacheRotation.z;
  32846. this.rotation.y = -this._cacheRotation.y;
  32847. this.rotation.z = this._cacheRotation.x;
  32848. }
  32849. _super.prototype._checkInputs.call(this);
  32850. };
  32851. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32852. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32853. if (navigator.getVRDevices) {
  32854. navigator.getVRDevices().then(this._getWebVRDevices);
  32855. }
  32856. else if (navigator.mozGetVRDevices) {
  32857. navigator.mozGetVRDevices(this._getWebVRDevices);
  32858. }
  32859. };
  32860. WebVRFreeCamera.prototype.detachControl = function (element) {
  32861. _super.prototype.detachControl.call(this, element);
  32862. this._vrEnabled = false;
  32863. };
  32864. return WebVRFreeCamera;
  32865. })(BABYLON.FreeCamera);
  32866. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32867. })(BABYLON || (BABYLON = {}));
  32868. var BABYLON;
  32869. (function (BABYLON) {
  32870. // Standard optimizations
  32871. var SceneOptimization = (function () {
  32872. function SceneOptimization(priority) {
  32873. if (priority === void 0) { priority = 0; }
  32874. this.priority = priority;
  32875. this.apply = function (scene) {
  32876. return true; // Return true if everything that can be done was applied
  32877. };
  32878. }
  32879. return SceneOptimization;
  32880. })();
  32881. BABYLON.SceneOptimization = SceneOptimization;
  32882. var TextureOptimization = (function (_super) {
  32883. __extends(TextureOptimization, _super);
  32884. function TextureOptimization(priority, maximumSize) {
  32885. var _this = this;
  32886. if (priority === void 0) { priority = 0; }
  32887. if (maximumSize === void 0) { maximumSize = 1024; }
  32888. _super.call(this, priority);
  32889. this.priority = priority;
  32890. this.maximumSize = maximumSize;
  32891. this.apply = function (scene) {
  32892. var allDone = true;
  32893. for (var index = 0; index < scene.textures.length; index++) {
  32894. var texture = scene.textures[index];
  32895. if (!texture.canRescale) {
  32896. continue;
  32897. }
  32898. var currentSize = texture.getSize();
  32899. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32900. if (maxDimension > _this.maximumSize) {
  32901. texture.scale(0.5);
  32902. allDone = false;
  32903. }
  32904. }
  32905. return allDone;
  32906. };
  32907. }
  32908. return TextureOptimization;
  32909. })(SceneOptimization);
  32910. BABYLON.TextureOptimization = TextureOptimization;
  32911. var HardwareScalingOptimization = (function (_super) {
  32912. __extends(HardwareScalingOptimization, _super);
  32913. function HardwareScalingOptimization(priority, maximumScale) {
  32914. var _this = this;
  32915. if (priority === void 0) { priority = 0; }
  32916. if (maximumScale === void 0) { maximumScale = 2; }
  32917. _super.call(this, priority);
  32918. this.priority = priority;
  32919. this.maximumScale = maximumScale;
  32920. this._currentScale = 1;
  32921. this.apply = function (scene) {
  32922. _this._currentScale++;
  32923. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32924. return _this._currentScale >= _this.maximumScale;
  32925. };
  32926. }
  32927. return HardwareScalingOptimization;
  32928. })(SceneOptimization);
  32929. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32930. var ShadowsOptimization = (function (_super) {
  32931. __extends(ShadowsOptimization, _super);
  32932. function ShadowsOptimization() {
  32933. _super.apply(this, arguments);
  32934. this.apply = function (scene) {
  32935. scene.shadowsEnabled = false;
  32936. return true;
  32937. };
  32938. }
  32939. return ShadowsOptimization;
  32940. })(SceneOptimization);
  32941. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32942. var PostProcessesOptimization = (function (_super) {
  32943. __extends(PostProcessesOptimization, _super);
  32944. function PostProcessesOptimization() {
  32945. _super.apply(this, arguments);
  32946. this.apply = function (scene) {
  32947. scene.postProcessesEnabled = false;
  32948. return true;
  32949. };
  32950. }
  32951. return PostProcessesOptimization;
  32952. })(SceneOptimization);
  32953. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32954. var LensFlaresOptimization = (function (_super) {
  32955. __extends(LensFlaresOptimization, _super);
  32956. function LensFlaresOptimization() {
  32957. _super.apply(this, arguments);
  32958. this.apply = function (scene) {
  32959. scene.lensFlaresEnabled = false;
  32960. return true;
  32961. };
  32962. }
  32963. return LensFlaresOptimization;
  32964. })(SceneOptimization);
  32965. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32966. var ParticlesOptimization = (function (_super) {
  32967. __extends(ParticlesOptimization, _super);
  32968. function ParticlesOptimization() {
  32969. _super.apply(this, arguments);
  32970. this.apply = function (scene) {
  32971. scene.particlesEnabled = false;
  32972. return true;
  32973. };
  32974. }
  32975. return ParticlesOptimization;
  32976. })(SceneOptimization);
  32977. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32978. var RenderTargetsOptimization = (function (_super) {
  32979. __extends(RenderTargetsOptimization, _super);
  32980. function RenderTargetsOptimization() {
  32981. _super.apply(this, arguments);
  32982. this.apply = function (scene) {
  32983. scene.renderTargetsEnabled = false;
  32984. return true;
  32985. };
  32986. }
  32987. return RenderTargetsOptimization;
  32988. })(SceneOptimization);
  32989. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32990. var MergeMeshesOptimization = (function (_super) {
  32991. __extends(MergeMeshesOptimization, _super);
  32992. function MergeMeshesOptimization() {
  32993. var _this = this;
  32994. _super.apply(this, arguments);
  32995. this._canBeMerged = function (abstractMesh) {
  32996. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32997. return false;
  32998. }
  32999. var mesh = abstractMesh;
  33000. if (!mesh.isVisible || !mesh.isEnabled()) {
  33001. return false;
  33002. }
  33003. if (mesh.instances.length > 0) {
  33004. return false;
  33005. }
  33006. if (mesh.skeleton || mesh.hasLODLevels) {
  33007. return false;
  33008. }
  33009. if (mesh.parent) {
  33010. return false;
  33011. }
  33012. return true;
  33013. };
  33014. this.apply = function (scene, updateSelectionTree) {
  33015. var globalPool = scene.meshes.slice(0);
  33016. var globalLength = globalPool.length;
  33017. for (var index = 0; index < globalLength; index++) {
  33018. var currentPool = new Array();
  33019. var current = globalPool[index];
  33020. // Checks
  33021. if (!_this._canBeMerged(current)) {
  33022. continue;
  33023. }
  33024. currentPool.push(current);
  33025. // Find compatible meshes
  33026. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33027. var otherMesh = globalPool[subIndex];
  33028. if (!_this._canBeMerged(otherMesh)) {
  33029. continue;
  33030. }
  33031. if (otherMesh.material !== current.material) {
  33032. continue;
  33033. }
  33034. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33035. continue;
  33036. }
  33037. currentPool.push(otherMesh);
  33038. globalLength--;
  33039. globalPool.splice(subIndex, 1);
  33040. subIndex--;
  33041. }
  33042. if (currentPool.length < 2) {
  33043. continue;
  33044. }
  33045. // Merge meshes
  33046. BABYLON.Mesh.MergeMeshes(currentPool);
  33047. }
  33048. if (updateSelectionTree != undefined) {
  33049. if (updateSelectionTree) {
  33050. scene.createOrUpdateSelectionOctree();
  33051. }
  33052. }
  33053. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33054. scene.createOrUpdateSelectionOctree();
  33055. }
  33056. return true;
  33057. };
  33058. }
  33059. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33060. get: function () {
  33061. return MergeMeshesOptimization._UpdateSelectionTree;
  33062. },
  33063. set: function (value) {
  33064. MergeMeshesOptimization._UpdateSelectionTree = value;
  33065. },
  33066. enumerable: true,
  33067. configurable: true
  33068. });
  33069. MergeMeshesOptimization._UpdateSelectionTree = false;
  33070. return MergeMeshesOptimization;
  33071. })(SceneOptimization);
  33072. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33073. // Options
  33074. var SceneOptimizerOptions = (function () {
  33075. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33076. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33077. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33078. this.targetFrameRate = targetFrameRate;
  33079. this.trackerDuration = trackerDuration;
  33080. this.optimizations = new Array();
  33081. }
  33082. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33083. var result = new SceneOptimizerOptions(targetFrameRate);
  33084. var priority = 0;
  33085. result.optimizations.push(new MergeMeshesOptimization(priority));
  33086. result.optimizations.push(new ShadowsOptimization(priority));
  33087. result.optimizations.push(new LensFlaresOptimization(priority));
  33088. // Next priority
  33089. priority++;
  33090. result.optimizations.push(new PostProcessesOptimization(priority));
  33091. result.optimizations.push(new ParticlesOptimization(priority));
  33092. // Next priority
  33093. priority++;
  33094. result.optimizations.push(new TextureOptimization(priority, 1024));
  33095. return result;
  33096. };
  33097. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33098. var result = new SceneOptimizerOptions(targetFrameRate);
  33099. var priority = 0;
  33100. result.optimizations.push(new MergeMeshesOptimization(priority));
  33101. result.optimizations.push(new ShadowsOptimization(priority));
  33102. result.optimizations.push(new LensFlaresOptimization(priority));
  33103. // Next priority
  33104. priority++;
  33105. result.optimizations.push(new PostProcessesOptimization(priority));
  33106. result.optimizations.push(new ParticlesOptimization(priority));
  33107. // Next priority
  33108. priority++;
  33109. result.optimizations.push(new TextureOptimization(priority, 512));
  33110. // Next priority
  33111. priority++;
  33112. result.optimizations.push(new RenderTargetsOptimization(priority));
  33113. // Next priority
  33114. priority++;
  33115. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33116. return result;
  33117. };
  33118. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33119. var result = new SceneOptimizerOptions(targetFrameRate);
  33120. var priority = 0;
  33121. result.optimizations.push(new MergeMeshesOptimization(priority));
  33122. result.optimizations.push(new ShadowsOptimization(priority));
  33123. result.optimizations.push(new LensFlaresOptimization(priority));
  33124. // Next priority
  33125. priority++;
  33126. result.optimizations.push(new PostProcessesOptimization(priority));
  33127. result.optimizations.push(new ParticlesOptimization(priority));
  33128. // Next priority
  33129. priority++;
  33130. result.optimizations.push(new TextureOptimization(priority, 256));
  33131. // Next priority
  33132. priority++;
  33133. result.optimizations.push(new RenderTargetsOptimization(priority));
  33134. // Next priority
  33135. priority++;
  33136. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33137. return result;
  33138. };
  33139. return SceneOptimizerOptions;
  33140. })();
  33141. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33142. // Scene optimizer tool
  33143. var SceneOptimizer = (function () {
  33144. function SceneOptimizer() {
  33145. }
  33146. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33147. // TODO: add an epsilon
  33148. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33149. if (onSuccess) {
  33150. onSuccess();
  33151. }
  33152. return;
  33153. }
  33154. // Apply current level of optimizations
  33155. var allDone = true;
  33156. var noOptimizationApplied = true;
  33157. for (var index = 0; index < options.optimizations.length; index++) {
  33158. var optimization = options.optimizations[index];
  33159. if (optimization.priority === currentPriorityLevel) {
  33160. noOptimizationApplied = false;
  33161. allDone = allDone && optimization.apply(scene);
  33162. }
  33163. }
  33164. // If no optimization was applied, this is a failure :(
  33165. if (noOptimizationApplied) {
  33166. if (onFailure) {
  33167. onFailure();
  33168. }
  33169. return;
  33170. }
  33171. // If all optimizations were done, move to next level
  33172. if (allDone) {
  33173. currentPriorityLevel++;
  33174. }
  33175. // Let's the system running for a specific amount of time before checking FPS
  33176. scene.executeWhenReady(function () {
  33177. setTimeout(function () {
  33178. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33179. }, options.trackerDuration);
  33180. });
  33181. };
  33182. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33183. if (!options) {
  33184. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33185. }
  33186. // Let's the system running for a specific amount of time before checking FPS
  33187. scene.executeWhenReady(function () {
  33188. setTimeout(function () {
  33189. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33190. }, options.trackerDuration);
  33191. });
  33192. };
  33193. return SceneOptimizer;
  33194. })();
  33195. BABYLON.SceneOptimizer = SceneOptimizer;
  33196. })(BABYLON || (BABYLON = {}));
  33197. var BABYLON;
  33198. (function (BABYLON) {
  33199. var Internals;
  33200. (function (Internals) {
  33201. var MeshLODLevel = (function () {
  33202. function MeshLODLevel(distance, mesh) {
  33203. this.distance = distance;
  33204. this.mesh = mesh;
  33205. }
  33206. return MeshLODLevel;
  33207. })();
  33208. Internals.MeshLODLevel = MeshLODLevel;
  33209. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33210. })(BABYLON || (BABYLON = {}));
  33211. var BABYLON;
  33212. (function (BABYLON) {
  33213. var RawTexture = (function (_super) {
  33214. __extends(RawTexture, _super);
  33215. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33216. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33217. if (invertY === void 0) { invertY = false; }
  33218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33219. _super.call(this, null, scene, !generateMipMaps, invertY);
  33220. this.format = format;
  33221. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33222. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33223. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33224. }
  33225. RawTexture.prototype.update = function (data) {
  33226. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33227. };
  33228. // Statics
  33229. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33230. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33231. if (invertY === void 0) { invertY = false; }
  33232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33233. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33234. };
  33235. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33236. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33237. if (invertY === void 0) { invertY = false; }
  33238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33239. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33240. };
  33241. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33242. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33243. if (invertY === void 0) { invertY = false; }
  33244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33245. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33246. };
  33247. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33248. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33249. if (invertY === void 0) { invertY = false; }
  33250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33251. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33252. };
  33253. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33254. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33255. if (invertY === void 0) { invertY = false; }
  33256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33257. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33258. };
  33259. return RawTexture;
  33260. })(BABYLON.Texture);
  33261. BABYLON.RawTexture = RawTexture;
  33262. })(BABYLON || (BABYLON = {}));
  33263. var BABYLON;
  33264. (function (BABYLON) {
  33265. var IndexedVector2 = (function (_super) {
  33266. __extends(IndexedVector2, _super);
  33267. function IndexedVector2(original, index) {
  33268. _super.call(this, original.x, original.y);
  33269. this.index = index;
  33270. }
  33271. return IndexedVector2;
  33272. })(BABYLON.Vector2);
  33273. var PolygonPoints = (function () {
  33274. function PolygonPoints() {
  33275. this.elements = new Array();
  33276. }
  33277. PolygonPoints.prototype.add = function (originalPoints) {
  33278. var _this = this;
  33279. var result = new Array();
  33280. originalPoints.forEach(function (point) {
  33281. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33282. var newPoint = new IndexedVector2(point, _this.elements.length);
  33283. result.push(newPoint);
  33284. _this.elements.push(newPoint);
  33285. }
  33286. });
  33287. return result;
  33288. };
  33289. PolygonPoints.prototype.computeBounds = function () {
  33290. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33291. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33292. this.elements.forEach(function (point) {
  33293. // x
  33294. if (point.x < lmin.x) {
  33295. lmin.x = point.x;
  33296. }
  33297. else if (point.x > lmax.x) {
  33298. lmax.x = point.x;
  33299. }
  33300. // y
  33301. if (point.y < lmin.y) {
  33302. lmin.y = point.y;
  33303. }
  33304. else if (point.y > lmax.y) {
  33305. lmax.y = point.y;
  33306. }
  33307. });
  33308. return {
  33309. min: lmin,
  33310. max: lmax,
  33311. width: lmax.x - lmin.x,
  33312. height: lmax.y - lmin.y
  33313. };
  33314. };
  33315. return PolygonPoints;
  33316. })();
  33317. var Polygon = (function () {
  33318. function Polygon() {
  33319. }
  33320. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33321. return [
  33322. new BABYLON.Vector2(xmin, ymin),
  33323. new BABYLON.Vector2(xmax, ymin),
  33324. new BABYLON.Vector2(xmax, ymax),
  33325. new BABYLON.Vector2(xmin, ymax)
  33326. ];
  33327. };
  33328. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33329. if (cx === void 0) { cx = 0; }
  33330. if (cy === void 0) { cy = 0; }
  33331. if (numberOfSides === void 0) { numberOfSides = 32; }
  33332. var result = new Array();
  33333. var angle = 0;
  33334. var increment = (Math.PI * 2) / numberOfSides;
  33335. for (var i = 0; i < numberOfSides; i++) {
  33336. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33337. angle -= increment;
  33338. }
  33339. return result;
  33340. };
  33341. Polygon.Parse = function (input) {
  33342. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33343. var i, result = [];
  33344. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33345. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33346. }
  33347. return result;
  33348. };
  33349. Polygon.StartingAt = function (x, y) {
  33350. return BABYLON.Path2.StartingAt(x, y);
  33351. };
  33352. return Polygon;
  33353. })();
  33354. BABYLON.Polygon = Polygon;
  33355. var PolygonMeshBuilder = (function () {
  33356. function PolygonMeshBuilder(name, contours, scene) {
  33357. this._points = new PolygonPoints();
  33358. this._outlinepoints = new PolygonPoints();
  33359. this._holes = [];
  33360. if (!("poly2tri" in window)) {
  33361. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33362. }
  33363. this._name = name;
  33364. this._scene = scene;
  33365. var points;
  33366. if (contours instanceof BABYLON.Path2) {
  33367. points = contours.getPoints();
  33368. }
  33369. else {
  33370. points = contours;
  33371. }
  33372. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33373. this._outlinepoints.add(points);
  33374. }
  33375. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33376. this._swctx.addHole(this._points.add(hole));
  33377. var holepoints = new PolygonPoints();
  33378. holepoints.add(hole);
  33379. this._holes.push(holepoints);
  33380. return this;
  33381. };
  33382. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33383. var _this = this;
  33384. if (updatable === void 0) { updatable = false; }
  33385. var result = new BABYLON.Mesh(this._name, this._scene);
  33386. var normals = [];
  33387. var positions = [];
  33388. var uvs = [];
  33389. var bounds = this._points.computeBounds();
  33390. this._points.elements.forEach(function (p) {
  33391. normals.push(0, 1.0, 0);
  33392. positions.push(p.x, 0, p.y);
  33393. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33394. });
  33395. var indices = [];
  33396. this._swctx.triangulate();
  33397. this._swctx.getTriangles().forEach(function (triangle) {
  33398. triangle.getPoints().forEach(function (point) {
  33399. indices.push(point.index);
  33400. });
  33401. });
  33402. if (depth > 0) {
  33403. var positionscount = (positions.length / 3); //get the current pointcount
  33404. this._points.elements.forEach(function (p) {
  33405. normals.push(0, -1.0, 0);
  33406. positions.push(p.x, -depth, p.y);
  33407. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33408. });
  33409. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33410. var p2;
  33411. var poscounter = 0;
  33412. this._swctx.getTriangles().forEach(function (triangle) {
  33413. triangle.getPoints().forEach(function (point) {
  33414. switch (poscounter) {
  33415. case 0:
  33416. p1 = point;
  33417. break;
  33418. case 1:
  33419. p2 = point;
  33420. break;
  33421. case 2:
  33422. indices.push(point.index + positionscount);
  33423. indices.push(p2.index + positionscount);
  33424. indices.push(p1.index + positionscount);
  33425. poscounter = -1;
  33426. break;
  33427. }
  33428. poscounter++;
  33429. //indices.push((<IndexedVector2>point).index + positionscount);
  33430. });
  33431. });
  33432. //Add the sides
  33433. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  33434. this._holes.forEach(function (hole) {
  33435. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  33436. });
  33437. }
  33438. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  33439. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  33440. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  33441. result.setIndices(indices);
  33442. return result;
  33443. };
  33444. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  33445. var StartIndex = positions.length / 3;
  33446. var ulength = 0;
  33447. for (var i = 0; i < points.elements.length; i++) {
  33448. var p = points.elements[i];
  33449. var p1;
  33450. if ((i + 1) > points.elements.length - 1) {
  33451. p1 = points.elements[0];
  33452. }
  33453. else {
  33454. p1 = points.elements[i + 1];
  33455. }
  33456. positions.push(p.x, 0, p.y);
  33457. positions.push(p.x, -depth, p.y);
  33458. positions.push(p1.x, 0, p1.y);
  33459. positions.push(p1.x, -depth, p1.y);
  33460. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  33461. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  33462. var v3 = v2.subtract(v1);
  33463. var v4 = new BABYLON.Vector3(0, 1, 0);
  33464. var vn = BABYLON.Vector3.Cross(v3, v4);
  33465. vn = vn.normalize();
  33466. uvs.push(ulength / bounds.width, 0);
  33467. uvs.push(ulength / bounds.width, 1);
  33468. ulength += v3.length();
  33469. uvs.push((ulength / bounds.width), 0);
  33470. uvs.push((ulength / bounds.width), 1);
  33471. if (!flip) {
  33472. normals.push(-vn.x, -vn.y, -vn.z);
  33473. normals.push(-vn.x, -vn.y, -vn.z);
  33474. normals.push(-vn.x, -vn.y, -vn.z);
  33475. normals.push(-vn.x, -vn.y, -vn.z);
  33476. indices.push(StartIndex);
  33477. indices.push(StartIndex + 1);
  33478. indices.push(StartIndex + 2);
  33479. indices.push(StartIndex + 1);
  33480. indices.push(StartIndex + 3);
  33481. indices.push(StartIndex + 2);
  33482. }
  33483. else {
  33484. normals.push(vn.x, vn.y, vn.z);
  33485. normals.push(vn.x, vn.y, vn.z);
  33486. normals.push(vn.x, vn.y, vn.z);
  33487. normals.push(vn.x, vn.y, vn.z);
  33488. indices.push(StartIndex);
  33489. indices.push(StartIndex + 2);
  33490. indices.push(StartIndex + 1);
  33491. indices.push(StartIndex + 1);
  33492. indices.push(StartIndex + 2);
  33493. indices.push(StartIndex + 3);
  33494. }
  33495. StartIndex += 4;
  33496. }
  33497. ;
  33498. };
  33499. return PolygonMeshBuilder;
  33500. })();
  33501. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  33502. })(BABYLON || (BABYLON = {}));
  33503. var BABYLON;
  33504. (function (BABYLON) {
  33505. var Octree = (function () {
  33506. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  33507. if (maxDepth === void 0) { maxDepth = 2; }
  33508. this.maxDepth = maxDepth;
  33509. this.dynamicContent = new Array();
  33510. this._maxBlockCapacity = maxBlockCapacity || 64;
  33511. this._selectionContent = new BABYLON.SmartArray(1024);
  33512. this._creationFunc = creationFunc;
  33513. }
  33514. // Methods
  33515. Octree.prototype.update = function (worldMin, worldMax, entries) {
  33516. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  33517. };
  33518. Octree.prototype.addMesh = function (entry) {
  33519. for (var index = 0; index < this.blocks.length; index++) {
  33520. var block = this.blocks[index];
  33521. block.addEntry(entry);
  33522. }
  33523. };
  33524. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  33525. this._selectionContent.reset();
  33526. for (var index = 0; index < this.blocks.length; index++) {
  33527. var block = this.blocks[index];
  33528. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  33529. }
  33530. if (allowDuplicate) {
  33531. this._selectionContent.concat(this.dynamicContent);
  33532. }
  33533. else {
  33534. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33535. }
  33536. return this._selectionContent;
  33537. };
  33538. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  33539. this._selectionContent.reset();
  33540. for (var index = 0; index < this.blocks.length; index++) {
  33541. var block = this.blocks[index];
  33542. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  33543. }
  33544. if (allowDuplicate) {
  33545. this._selectionContent.concat(this.dynamicContent);
  33546. }
  33547. else {
  33548. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33549. }
  33550. return this._selectionContent;
  33551. };
  33552. Octree.prototype.intersectsRay = function (ray) {
  33553. this._selectionContent.reset();
  33554. for (var index = 0; index < this.blocks.length; index++) {
  33555. var block = this.blocks[index];
  33556. block.intersectsRay(ray, this._selectionContent);
  33557. }
  33558. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33559. return this._selectionContent;
  33560. };
  33561. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33562. target.blocks = new Array();
  33563. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33564. // Segmenting space
  33565. for (var x = 0; x < 2; x++) {
  33566. for (var y = 0; y < 2; y++) {
  33567. for (var z = 0; z < 2; z++) {
  33568. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33569. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33570. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33571. block.addEntries(entries);
  33572. target.blocks.push(block);
  33573. }
  33574. }
  33575. }
  33576. };
  33577. Octree.CreationFuncForMeshes = function (entry, block) {
  33578. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33579. block.entries.push(entry);
  33580. }
  33581. };
  33582. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33583. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33584. block.entries.push(entry);
  33585. }
  33586. };
  33587. return Octree;
  33588. })();
  33589. BABYLON.Octree = Octree;
  33590. })(BABYLON || (BABYLON = {}));
  33591. var BABYLON;
  33592. (function (BABYLON) {
  33593. var OctreeBlock = (function () {
  33594. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33595. this.entries = new Array();
  33596. this._boundingVectors = new Array();
  33597. this._capacity = capacity;
  33598. this._depth = depth;
  33599. this._maxDepth = maxDepth;
  33600. this._creationFunc = creationFunc;
  33601. this._minPoint = minPoint;
  33602. this._maxPoint = maxPoint;
  33603. this._boundingVectors.push(minPoint.clone());
  33604. this._boundingVectors.push(maxPoint.clone());
  33605. this._boundingVectors.push(minPoint.clone());
  33606. this._boundingVectors[2].x = maxPoint.x;
  33607. this._boundingVectors.push(minPoint.clone());
  33608. this._boundingVectors[3].y = maxPoint.y;
  33609. this._boundingVectors.push(minPoint.clone());
  33610. this._boundingVectors[4].z = maxPoint.z;
  33611. this._boundingVectors.push(maxPoint.clone());
  33612. this._boundingVectors[5].z = minPoint.z;
  33613. this._boundingVectors.push(maxPoint.clone());
  33614. this._boundingVectors[6].x = minPoint.x;
  33615. this._boundingVectors.push(maxPoint.clone());
  33616. this._boundingVectors[7].y = minPoint.y;
  33617. }
  33618. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33619. // Property
  33620. get: function () {
  33621. return this._capacity;
  33622. },
  33623. enumerable: true,
  33624. configurable: true
  33625. });
  33626. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  33627. get: function () {
  33628. return this._minPoint;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33634. get: function () {
  33635. return this._maxPoint;
  33636. },
  33637. enumerable: true,
  33638. configurable: true
  33639. });
  33640. // Methods
  33641. OctreeBlock.prototype.addEntry = function (entry) {
  33642. if (this.blocks) {
  33643. for (var index = 0; index < this.blocks.length; index++) {
  33644. var block = this.blocks[index];
  33645. block.addEntry(entry);
  33646. }
  33647. return;
  33648. }
  33649. this._creationFunc(entry, this);
  33650. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33651. this.createInnerBlocks();
  33652. }
  33653. };
  33654. OctreeBlock.prototype.addEntries = function (entries) {
  33655. for (var index = 0; index < entries.length; index++) {
  33656. var mesh = entries[index];
  33657. this.addEntry(mesh);
  33658. }
  33659. };
  33660. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33661. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33662. if (this.blocks) {
  33663. for (var index = 0; index < this.blocks.length; index++) {
  33664. var block = this.blocks[index];
  33665. block.select(frustumPlanes, selection, allowDuplicate);
  33666. }
  33667. return;
  33668. }
  33669. if (allowDuplicate) {
  33670. selection.concat(this.entries);
  33671. }
  33672. else {
  33673. selection.concatWithNoDuplicate(this.entries);
  33674. }
  33675. }
  33676. };
  33677. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33678. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33679. if (this.blocks) {
  33680. for (var index = 0; index < this.blocks.length; index++) {
  33681. var block = this.blocks[index];
  33682. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33683. }
  33684. return;
  33685. }
  33686. if (allowDuplicate) {
  33687. selection.concat(this.entries);
  33688. }
  33689. else {
  33690. selection.concatWithNoDuplicate(this.entries);
  33691. }
  33692. }
  33693. };
  33694. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33695. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33696. if (this.blocks) {
  33697. for (var index = 0; index < this.blocks.length; index++) {
  33698. var block = this.blocks[index];
  33699. block.intersectsRay(ray, selection);
  33700. }
  33701. return;
  33702. }
  33703. selection.concatWithNoDuplicate(this.entries);
  33704. }
  33705. };
  33706. OctreeBlock.prototype.createInnerBlocks = function () {
  33707. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33708. };
  33709. return OctreeBlock;
  33710. })();
  33711. BABYLON.OctreeBlock = OctreeBlock;
  33712. })(BABYLON || (BABYLON = {}));
  33713. var BABYLON;
  33714. (function (BABYLON) {
  33715. var BlurPostProcess = (function (_super) {
  33716. __extends(BlurPostProcess, _super);
  33717. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33718. var _this = this;
  33719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33720. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33721. this.direction = direction;
  33722. this.blurWidth = blurWidth;
  33723. this.onApply = function (effect) {
  33724. effect.setFloat2("screenSize", _this.width, _this.height);
  33725. effect.setVector2("direction", _this.direction);
  33726. effect.setFloat("blurWidth", _this.blurWidth);
  33727. };
  33728. }
  33729. return BlurPostProcess;
  33730. })(BABYLON.PostProcess);
  33731. BABYLON.BlurPostProcess = BlurPostProcess;
  33732. })(BABYLON || (BABYLON = {}));
  33733. var BABYLON;
  33734. (function (BABYLON) {
  33735. var RefractionPostProcess = (function (_super) {
  33736. __extends(RefractionPostProcess, _super);
  33737. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33738. var _this = this;
  33739. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33740. this.color = color;
  33741. this.depth = depth;
  33742. this.colorLevel = colorLevel;
  33743. this.onActivate = function (cam) {
  33744. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33745. };
  33746. this.onApply = function (effect) {
  33747. effect.setColor3("baseColor", _this.color);
  33748. effect.setFloat("depth", _this.depth);
  33749. effect.setFloat("colorLevel", _this.colorLevel);
  33750. effect.setTexture("refractionSampler", _this._refRexture);
  33751. };
  33752. }
  33753. // Methods
  33754. RefractionPostProcess.prototype.dispose = function (camera) {
  33755. if (this._refRexture) {
  33756. this._refRexture.dispose();
  33757. }
  33758. _super.prototype.dispose.call(this, camera);
  33759. };
  33760. return RefractionPostProcess;
  33761. })(BABYLON.PostProcess);
  33762. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33763. })(BABYLON || (BABYLON = {}));
  33764. var BABYLON;
  33765. (function (BABYLON) {
  33766. var BlackAndWhitePostProcess = (function (_super) {
  33767. __extends(BlackAndWhitePostProcess, _super);
  33768. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33769. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33770. }
  33771. return BlackAndWhitePostProcess;
  33772. })(BABYLON.PostProcess);
  33773. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33774. })(BABYLON || (BABYLON = {}));
  33775. var BABYLON;
  33776. (function (BABYLON) {
  33777. var ConvolutionPostProcess = (function (_super) {
  33778. __extends(ConvolutionPostProcess, _super);
  33779. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33780. var _this = this;
  33781. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33782. this.kernel = kernel;
  33783. this.onApply = function (effect) {
  33784. effect.setFloat2("screenSize", _this.width, _this.height);
  33785. effect.setArray("kernel", _this.kernel);
  33786. };
  33787. }
  33788. // Statics
  33789. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33790. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33791. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33792. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33793. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33794. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33795. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33796. return ConvolutionPostProcess;
  33797. })(BABYLON.PostProcess);
  33798. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33799. })(BABYLON || (BABYLON = {}));
  33800. var BABYLON;
  33801. (function (BABYLON) {
  33802. var FilterPostProcess = (function (_super) {
  33803. __extends(FilterPostProcess, _super);
  33804. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33805. var _this = this;
  33806. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33807. this.kernelMatrix = kernelMatrix;
  33808. this.onApply = function (effect) {
  33809. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33810. };
  33811. }
  33812. return FilterPostProcess;
  33813. })(BABYLON.PostProcess);
  33814. BABYLON.FilterPostProcess = FilterPostProcess;
  33815. })(BABYLON || (BABYLON = {}));
  33816. var BABYLON;
  33817. (function (BABYLON) {
  33818. var FxaaPostProcess = (function (_super) {
  33819. __extends(FxaaPostProcess, _super);
  33820. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33821. var _this = this;
  33822. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33823. this.onSizeChanged = function () {
  33824. _this.texelWidth = 1.0 / _this.width;
  33825. _this.texelHeight = 1.0 / _this.height;
  33826. };
  33827. this.onApply = function (effect) {
  33828. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33829. };
  33830. }
  33831. return FxaaPostProcess;
  33832. })(BABYLON.PostProcess);
  33833. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33834. })(BABYLON || (BABYLON = {}));
  33835. var BABYLON;
  33836. (function (BABYLON) {
  33837. var StereoscopicInterlacePostProcess = (function (_super) {
  33838. __extends(StereoscopicInterlacePostProcess, _super);
  33839. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33840. var _this = this;
  33841. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33842. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33843. this.onSizeChanged = function () {
  33844. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33845. };
  33846. this.onApply = function (effect) {
  33847. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33848. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33849. };
  33850. }
  33851. return StereoscopicInterlacePostProcess;
  33852. })(BABYLON.PostProcess);
  33853. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33854. })(BABYLON || (BABYLON = {}));
  33855. var BABYLON;
  33856. (function (BABYLON) {
  33857. var LensFlare = (function () {
  33858. function LensFlare(size, position, color, imgUrl, system) {
  33859. this.size = size;
  33860. this.position = position;
  33861. this.dispose = function () {
  33862. if (this.texture) {
  33863. this.texture.dispose();
  33864. }
  33865. // Remove from scene
  33866. var index = this._system.lensFlares.indexOf(this);
  33867. this._system.lensFlares.splice(index, 1);
  33868. };
  33869. this.color = color || new BABYLON.Color3(1, 1, 1);
  33870. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33871. this._system = system;
  33872. system.lensFlares.push(this);
  33873. }
  33874. return LensFlare;
  33875. })();
  33876. BABYLON.LensFlare = LensFlare;
  33877. })(BABYLON || (BABYLON = {}));
  33878. var BABYLON;
  33879. (function (BABYLON) {
  33880. var LensFlareSystem = (function () {
  33881. function LensFlareSystem(name, emitter, scene) {
  33882. this.name = name;
  33883. this.lensFlares = new Array();
  33884. this.borderLimit = 300;
  33885. this.layerMask = 0x0FFFFFFF;
  33886. this._vertexDeclaration = [2];
  33887. this._vertexStrideSize = 2 * 4;
  33888. this._isEnabled = true;
  33889. this._scene = scene;
  33890. this._emitter = emitter;
  33891. scene.lensFlareSystems.push(this);
  33892. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33893. // VBO
  33894. var vertices = [];
  33895. vertices.push(1, 1);
  33896. vertices.push(-1, 1);
  33897. vertices.push(-1, -1);
  33898. vertices.push(1, -1);
  33899. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33900. // Indices
  33901. var indices = [];
  33902. indices.push(0);
  33903. indices.push(1);
  33904. indices.push(2);
  33905. indices.push(0);
  33906. indices.push(2);
  33907. indices.push(3);
  33908. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33909. // Effects
  33910. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33911. }
  33912. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33913. get: function () {
  33914. return this._isEnabled;
  33915. },
  33916. set: function (value) {
  33917. this._isEnabled = value;
  33918. },
  33919. enumerable: true,
  33920. configurable: true
  33921. });
  33922. LensFlareSystem.prototype.getScene = function () {
  33923. return this._scene;
  33924. };
  33925. LensFlareSystem.prototype.getEmitter = function () {
  33926. return this._emitter;
  33927. };
  33928. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33929. this._emitter = newEmitter;
  33930. };
  33931. LensFlareSystem.prototype.getEmitterPosition = function () {
  33932. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33933. };
  33934. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33935. var position = this.getEmitterPosition();
  33936. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33937. this._positionX = position.x;
  33938. this._positionY = position.y;
  33939. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33940. if (position.z > 0) {
  33941. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33942. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33943. return true;
  33944. }
  33945. }
  33946. return false;
  33947. };
  33948. LensFlareSystem.prototype._isVisible = function () {
  33949. if (!this._isEnabled) {
  33950. return false;
  33951. }
  33952. var emitterPosition = this.getEmitterPosition();
  33953. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33954. var distance = direction.length();
  33955. direction.normalize();
  33956. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33957. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33958. return !pickInfo.hit || pickInfo.distance > distance;
  33959. };
  33960. LensFlareSystem.prototype.render = function () {
  33961. if (!this._effect.isReady())
  33962. return false;
  33963. var engine = this._scene.getEngine();
  33964. var viewport = this._scene.activeCamera.viewport;
  33965. var globalViewport = viewport.toScreenGlobal(engine);
  33966. // Position
  33967. if (!this.computeEffectivePosition(globalViewport)) {
  33968. return false;
  33969. }
  33970. // Visibility
  33971. if (!this._isVisible()) {
  33972. return false;
  33973. }
  33974. // Intensity
  33975. var awayX;
  33976. var awayY;
  33977. if (this._positionX < this.borderLimit + globalViewport.x) {
  33978. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33979. }
  33980. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33981. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33982. }
  33983. else {
  33984. awayX = 0;
  33985. }
  33986. if (this._positionY < this.borderLimit + globalViewport.y) {
  33987. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33988. }
  33989. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33990. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33991. }
  33992. else {
  33993. awayY = 0;
  33994. }
  33995. var away = (awayX > awayY) ? awayX : awayY;
  33996. if (away > this.borderLimit) {
  33997. away = this.borderLimit;
  33998. }
  33999. var intensity = 1.0 - (away / this.borderLimit);
  34000. if (intensity < 0) {
  34001. return false;
  34002. }
  34003. if (intensity > 1.0) {
  34004. intensity = 1.0;
  34005. }
  34006. // Position
  34007. var centerX = globalViewport.x + globalViewport.width / 2;
  34008. var centerY = globalViewport.y + globalViewport.height / 2;
  34009. var distX = centerX - this._positionX;
  34010. var distY = centerY - this._positionY;
  34011. // Effects
  34012. engine.enableEffect(this._effect);
  34013. engine.setState(false);
  34014. engine.setDepthBuffer(false);
  34015. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34016. // VBOs
  34017. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34018. // Flares
  34019. for (var index = 0; index < this.lensFlares.length; index++) {
  34020. var flare = this.lensFlares[index];
  34021. var x = centerX - (distX * flare.position);
  34022. var y = centerY - (distY * flare.position);
  34023. var cw = flare.size;
  34024. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34025. var cx = 2 * (x / globalViewport.width) - 1.0;
  34026. var cy = 1.0 - 2 * (y / globalViewport.height);
  34027. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34028. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34029. // Texture
  34030. this._effect.setTexture("textureSampler", flare.texture);
  34031. // Color
  34032. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34033. // Draw order
  34034. engine.draw(true, 0, 6);
  34035. }
  34036. engine.setDepthBuffer(true);
  34037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34038. return true;
  34039. };
  34040. LensFlareSystem.prototype.dispose = function () {
  34041. if (this._vertexBuffer) {
  34042. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34043. this._vertexBuffer = null;
  34044. }
  34045. if (this._indexBuffer) {
  34046. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34047. this._indexBuffer = null;
  34048. }
  34049. while (this.lensFlares.length) {
  34050. this.lensFlares[0].dispose();
  34051. }
  34052. // Remove from scene
  34053. var index = this._scene.lensFlareSystems.indexOf(this);
  34054. this._scene.lensFlareSystems.splice(index, 1);
  34055. };
  34056. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34057. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34058. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34059. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34060. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34061. var parsedFlare = parsedLensFlareSystem.flares[index];
  34062. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34063. }
  34064. return lensFlareSystem;
  34065. };
  34066. LensFlareSystem.prototype.serialize = function () {
  34067. var serializationObject = {};
  34068. serializationObject.emitterId = this.getEmitter().id;
  34069. serializationObject.borderLimit = this.borderLimit;
  34070. serializationObject.flares = [];
  34071. for (var index = 0; index < this.lensFlares.length; index++) {
  34072. var flare = this.lensFlares[index];
  34073. serializationObject.flares.push({
  34074. size: flare.size,
  34075. position: flare.position,
  34076. color: flare.color.asArray(),
  34077. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34078. });
  34079. }
  34080. return serializationObject;
  34081. };
  34082. return LensFlareSystem;
  34083. })();
  34084. BABYLON.LensFlareSystem = LensFlareSystem;
  34085. })(BABYLON || (BABYLON = {}));
  34086. var BABYLON;
  34087. (function (BABYLON) {
  34088. // We're mainly based on the logic defined into the FreeCamera code
  34089. var DeviceOrientationCamera = (function (_super) {
  34090. __extends(DeviceOrientationCamera, _super);
  34091. function DeviceOrientationCamera(name, position, scene) {
  34092. var _this = this;
  34093. _super.call(this, name, position, scene);
  34094. this._offsetX = null;
  34095. this._offsetY = null;
  34096. this._orientationGamma = 0;
  34097. this._orientationBeta = 0;
  34098. this._initialOrientationGamma = 0;
  34099. this._initialOrientationBeta = 0;
  34100. this.angularSensibility = 10000.0;
  34101. this.moveSensibility = 50.0;
  34102. window.addEventListener("resize", function () {
  34103. _this._initialOrientationGamma = null;
  34104. }, false);
  34105. }
  34106. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34107. var _this = this;
  34108. if (this._attachedCanvas) {
  34109. return;
  34110. }
  34111. this._attachedCanvas = canvas;
  34112. if (!this._orientationChanged) {
  34113. this._orientationChanged = function (evt) {
  34114. if (!_this._initialOrientationGamma) {
  34115. _this._initialOrientationGamma = evt.gamma;
  34116. _this._initialOrientationBeta = evt.beta;
  34117. }
  34118. _this._orientationGamma = evt.gamma;
  34119. _this._orientationBeta = evt.beta;
  34120. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34121. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34122. };
  34123. }
  34124. window.addEventListener("deviceorientation", this._orientationChanged);
  34125. };
  34126. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34127. if (this._attachedCanvas !== canvas) {
  34128. return;
  34129. }
  34130. window.removeEventListener("deviceorientation", this._orientationChanged);
  34131. this._attachedCanvas = null;
  34132. this._orientationGamma = 0;
  34133. this._orientationBeta = 0;
  34134. this._initialOrientationGamma = 0;
  34135. this._initialOrientationBeta = 0;
  34136. };
  34137. DeviceOrientationCamera.prototype._checkInputs = function () {
  34138. if (!this._offsetX) {
  34139. return;
  34140. }
  34141. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34142. var speed = this._computeLocalCameraSpeed();
  34143. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34144. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34145. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34146. _super.prototype._checkInputs.call(this);
  34147. };
  34148. return DeviceOrientationCamera;
  34149. })(BABYLON.FreeCamera);
  34150. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34151. })(BABYLON || (BABYLON = {}));
  34152. var BABYLON;
  34153. (function (BABYLON) {
  34154. var Analyser = (function () {
  34155. function Analyser(scene) {
  34156. this.SMOOTHING = 0.75;
  34157. this.FFT_SIZE = 512;
  34158. this.BARGRAPHAMPLITUDE = 256;
  34159. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34160. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34161. this._scene = scene;
  34162. this._audioEngine = BABYLON.Engine.audioEngine;
  34163. if (this._audioEngine.canUseWebAudio) {
  34164. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34165. this._webAudioAnalyser.minDecibels = -140;
  34166. this._webAudioAnalyser.maxDecibels = 0;
  34167. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34168. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34169. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34170. }
  34171. }
  34172. Analyser.prototype.getFrequencyBinCount = function () {
  34173. if (this._audioEngine.canUseWebAudio) {
  34174. return this._webAudioAnalyser.frequencyBinCount;
  34175. }
  34176. else {
  34177. return 0;
  34178. }
  34179. };
  34180. Analyser.prototype.getByteFrequencyData = function () {
  34181. if (this._audioEngine.canUseWebAudio) {
  34182. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34183. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34184. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34185. }
  34186. return this._byteFreqs;
  34187. };
  34188. Analyser.prototype.getByteTimeDomainData = function () {
  34189. if (this._audioEngine.canUseWebAudio) {
  34190. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34191. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34192. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34193. }
  34194. return this._byteTime;
  34195. };
  34196. Analyser.prototype.getFloatFrequencyData = function () {
  34197. if (this._audioEngine.canUseWebAudio) {
  34198. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34199. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34200. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34201. }
  34202. return this._floatFreqs;
  34203. };
  34204. Analyser.prototype.drawDebugCanvas = function () {
  34205. var _this = this;
  34206. if (this._audioEngine.canUseWebAudio) {
  34207. if (!this._debugCanvas) {
  34208. this._debugCanvas = document.createElement("canvas");
  34209. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34210. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34211. this._debugCanvas.style.position = "absolute";
  34212. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34213. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34214. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34215. document.body.appendChild(this._debugCanvas);
  34216. this._registerFunc = function () {
  34217. _this.drawDebugCanvas();
  34218. };
  34219. this._scene.registerBeforeRender(this._registerFunc);
  34220. }
  34221. if (this._registerFunc) {
  34222. var workingArray = this.getByteFrequencyData();
  34223. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34224. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34225. // Draw the frequency domain chart.
  34226. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34227. var value = workingArray[i];
  34228. var percent = value / this.BARGRAPHAMPLITUDE;
  34229. var height = this.DEBUGCANVASSIZE.height * percent;
  34230. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34231. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34232. var hue = i / this.getFrequencyBinCount() * 360;
  34233. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34234. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34235. }
  34236. }
  34237. }
  34238. };
  34239. Analyser.prototype.stopDebugCanvas = function () {
  34240. if (this._debugCanvas) {
  34241. this._scene.unregisterBeforeRender(this._registerFunc);
  34242. this._registerFunc = null;
  34243. document.body.removeChild(this._debugCanvas);
  34244. this._debugCanvas = null;
  34245. this._debugCanvasContext = null;
  34246. }
  34247. };
  34248. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34249. if (this._audioEngine.canUseWebAudio) {
  34250. inputAudioNode.connect(this._webAudioAnalyser);
  34251. this._webAudioAnalyser.connect(outputAudioNode);
  34252. }
  34253. };
  34254. Analyser.prototype.dispose = function () {
  34255. if (this._audioEngine.canUseWebAudio) {
  34256. this._webAudioAnalyser.disconnect();
  34257. }
  34258. };
  34259. return Analyser;
  34260. })();
  34261. BABYLON.Analyser = Analyser;
  34262. })(BABYLON || (BABYLON = {}));
  34263. var BABYLON;
  34264. (function (BABYLON) {
  34265. var AudioEngine = (function () {
  34266. function AudioEngine() {
  34267. this._audioContext = null;
  34268. this._audioContextInitialized = false;
  34269. this.canUseWebAudio = false;
  34270. this.WarnedWebAudioUnsupported = false;
  34271. this.unlocked = false;
  34272. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34273. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34274. this.canUseWebAudio = true;
  34275. }
  34276. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34277. this._unlockiOSaudio();
  34278. }
  34279. else {
  34280. this.unlocked = true;
  34281. }
  34282. }
  34283. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34284. get: function () {
  34285. if (!this._audioContextInitialized) {
  34286. this._initializeAudioContext();
  34287. }
  34288. return this._audioContext;
  34289. },
  34290. enumerable: true,
  34291. configurable: true
  34292. });
  34293. AudioEngine.prototype._unlockiOSaudio = function () {
  34294. var _this = this;
  34295. var unlockaudio = function () {
  34296. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34297. var source = _this.audioContext.createBufferSource();
  34298. source.buffer = buffer;
  34299. source.connect(_this.audioContext.destination);
  34300. source.start(0);
  34301. setTimeout(function () {
  34302. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34303. _this.unlocked = true;
  34304. window.removeEventListener('touchend', unlockaudio, false);
  34305. if (_this.onAudioUnlocked) {
  34306. _this.onAudioUnlocked();
  34307. }
  34308. }
  34309. }, 0);
  34310. };
  34311. window.addEventListener('touchend', unlockaudio, false);
  34312. };
  34313. AudioEngine.prototype._initializeAudioContext = function () {
  34314. try {
  34315. if (this.canUseWebAudio) {
  34316. this._audioContext = new AudioContext();
  34317. // create a global volume gain node
  34318. this.masterGain = this._audioContext.createGain();
  34319. this.masterGain.gain.value = 1;
  34320. this.masterGain.connect(this._audioContext.destination);
  34321. this._audioContextInitialized = true;
  34322. }
  34323. }
  34324. catch (e) {
  34325. this.canUseWebAudio = false;
  34326. BABYLON.Tools.Error("Web Audio: " + e.message);
  34327. }
  34328. };
  34329. AudioEngine.prototype.dispose = function () {
  34330. if (this.canUseWebAudio && this._audioContextInitialized) {
  34331. if (this._connectedAnalyser) {
  34332. this._connectedAnalyser.stopDebugCanvas();
  34333. this._connectedAnalyser.dispose();
  34334. this.masterGain.disconnect();
  34335. this.masterGain.connect(this._audioContext.destination);
  34336. this._connectedAnalyser = null;
  34337. }
  34338. this.masterGain.gain.value = 1;
  34339. }
  34340. this.WarnedWebAudioUnsupported = false;
  34341. };
  34342. AudioEngine.prototype.getGlobalVolume = function () {
  34343. if (this.canUseWebAudio && this._audioContextInitialized) {
  34344. return this.masterGain.gain.value;
  34345. }
  34346. else {
  34347. return -1;
  34348. }
  34349. };
  34350. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34351. if (this.canUseWebAudio && this._audioContextInitialized) {
  34352. this.masterGain.gain.value = newVolume;
  34353. }
  34354. };
  34355. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34356. if (this._connectedAnalyser) {
  34357. this._connectedAnalyser.stopDebugCanvas();
  34358. }
  34359. if (this.canUseWebAudio && this._audioContextInitialized) {
  34360. this._connectedAnalyser = analyser;
  34361. this.masterGain.disconnect();
  34362. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34363. }
  34364. };
  34365. return AudioEngine;
  34366. })();
  34367. BABYLON.AudioEngine = AudioEngine;
  34368. })(BABYLON || (BABYLON = {}));
  34369. var BABYLON;
  34370. (function (BABYLON) {
  34371. var Sound = (function () {
  34372. /**
  34373. * Create a sound and attach it to a scene
  34374. * @param name Name of your sound
  34375. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34376. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34377. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34378. */
  34379. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34380. var _this = this;
  34381. this.autoplay = false;
  34382. this.loop = false;
  34383. this.useCustomAttenuation = false;
  34384. this.spatialSound = false;
  34385. this.refDistance = 1;
  34386. this.rolloffFactor = 1;
  34387. this.maxDistance = 100;
  34388. this.distanceModel = "linear";
  34389. this._panningModel = "equalpower";
  34390. this._playbackRate = 1;
  34391. this._streaming = false;
  34392. this._startTime = 0;
  34393. this._startOffset = 0;
  34394. this._position = BABYLON.Vector3.Zero();
  34395. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34396. this._volume = 1;
  34397. this._isLoaded = false;
  34398. this._isReadyToPlay = false;
  34399. this.isPlaying = false;
  34400. this.isPaused = false;
  34401. this._isDirectional = false;
  34402. // Used if you'd like to create a directional sound.
  34403. // If not set, the sound will be omnidirectional
  34404. this._coneInnerAngle = 360;
  34405. this._coneOuterAngle = 360;
  34406. this._coneOuterGain = 0;
  34407. this._isOutputConnected = false;
  34408. this.name = name;
  34409. this._scene = scene;
  34410. this._readyToPlayCallback = readyToPlayCallback;
  34411. // Default custom attenuation function is a linear attenuation
  34412. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34413. if (currentDistance < maxDistance) {
  34414. return currentVolume * (1 - currentDistance / maxDistance);
  34415. }
  34416. else {
  34417. return 0;
  34418. }
  34419. };
  34420. if (options) {
  34421. this.autoplay = options.autoplay || false;
  34422. this.loop = options.loop || false;
  34423. // if volume === 0, we need another way to check this option
  34424. if (options.volume !== undefined) {
  34425. this._volume = options.volume;
  34426. }
  34427. this.spatialSound = options.spatialSound || false;
  34428. this.maxDistance = options.maxDistance || 100;
  34429. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34430. this.rolloffFactor = options.rolloffFactor || 1;
  34431. this.refDistance = options.refDistance || 1;
  34432. this.distanceModel = options.distanceModel || "linear";
  34433. this._playbackRate = options.playbackRate || 1;
  34434. this._streaming = options.streaming || false;
  34435. }
  34436. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34437. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34438. this._soundGain.gain.value = this._volume;
  34439. this._inputAudioNode = this._soundGain;
  34440. this._ouputAudioNode = this._soundGain;
  34441. if (this.spatialSound) {
  34442. this._createSpatialParameters();
  34443. }
  34444. this._scene.mainSoundTrack.AddSound(this);
  34445. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34446. if (urlOrArrayBuffer) {
  34447. // If it's an URL
  34448. if (typeof (urlOrArrayBuffer) === "string") {
  34449. // Loading sound using XHR2
  34450. if (!this._streaming) {
  34451. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34452. }
  34453. else {
  34454. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34455. this._htmlAudioElement.controls = false;
  34456. this._htmlAudioElement.loop = this.loop;
  34457. this._htmlAudioElement.crossOrigin = "anonymous";
  34458. this._htmlAudioElement.preload = "auto";
  34459. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34460. _this._isReadyToPlay = true;
  34461. if (_this.autoplay) {
  34462. _this.play();
  34463. }
  34464. if (_this._readyToPlayCallback) {
  34465. _this._readyToPlayCallback();
  34466. }
  34467. });
  34468. document.body.appendChild(this._htmlAudioElement);
  34469. }
  34470. }
  34471. else {
  34472. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34473. if (urlOrArrayBuffer.byteLength > 0) {
  34474. this._soundLoaded(urlOrArrayBuffer);
  34475. }
  34476. }
  34477. else {
  34478. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34479. }
  34480. }
  34481. }
  34482. }
  34483. else {
  34484. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34485. this._scene.mainSoundTrack.AddSound(this);
  34486. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34487. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34488. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34489. }
  34490. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34491. if (this._readyToPlayCallback) {
  34492. window.setTimeout(function () {
  34493. _this._readyToPlayCallback();
  34494. }, 1000);
  34495. }
  34496. }
  34497. }
  34498. Sound.prototype.dispose = function () {
  34499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34500. if (this.isPlaying) {
  34501. this.stop();
  34502. }
  34503. this._isReadyToPlay = false;
  34504. if (this.soundTrackId === -1) {
  34505. this._scene.mainSoundTrack.RemoveSound(this);
  34506. }
  34507. else {
  34508. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34509. }
  34510. if (this._soundGain) {
  34511. this._soundGain.disconnect();
  34512. this._soundGain = null;
  34513. }
  34514. if (this._soundPanner) {
  34515. this._soundPanner.disconnect();
  34516. this._soundPanner = null;
  34517. }
  34518. if (this._soundSource) {
  34519. this._soundSource.disconnect();
  34520. this._soundSource = null;
  34521. }
  34522. this._audioBuffer = null;
  34523. if (this._htmlAudioElement) {
  34524. this._htmlAudioElement.pause();
  34525. this._htmlAudioElement.src = "";
  34526. document.body.removeChild(this._htmlAudioElement);
  34527. }
  34528. if (this._connectedMesh) {
  34529. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34530. this._connectedMesh = null;
  34531. }
  34532. }
  34533. };
  34534. Sound.prototype._soundLoaded = function (audioData) {
  34535. var _this = this;
  34536. this._isLoaded = true;
  34537. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34538. _this._audioBuffer = buffer;
  34539. _this._isReadyToPlay = true;
  34540. if (_this.autoplay) {
  34541. _this.play();
  34542. }
  34543. if (_this._readyToPlayCallback) {
  34544. _this._readyToPlayCallback();
  34545. }
  34546. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34547. };
  34548. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34549. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34550. this._audioBuffer = audioBuffer;
  34551. this._isReadyToPlay = true;
  34552. }
  34553. };
  34554. Sound.prototype.updateOptions = function (options) {
  34555. if (options) {
  34556. this.loop = options.loop || this.loop;
  34557. this.maxDistance = options.maxDistance || this.maxDistance;
  34558. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34559. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34560. this.refDistance = options.refDistance || this.refDistance;
  34561. this.distanceModel = options.distanceModel || this.distanceModel;
  34562. this._playbackRate = options.playbackRate || this._playbackRate;
  34563. this._updateSpatialParameters();
  34564. if (this.isPlaying) {
  34565. if (this._streaming) {
  34566. this._htmlAudioElement.playbackRate = this._playbackRate;
  34567. }
  34568. else {
  34569. this._soundSource.playbackRate.value = this._playbackRate;
  34570. }
  34571. }
  34572. }
  34573. };
  34574. Sound.prototype._createSpatialParameters = function () {
  34575. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34576. if (this._scene.headphone) {
  34577. this._panningModel = "HRTF";
  34578. }
  34579. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34580. this._updateSpatialParameters();
  34581. this._soundPanner.connect(this._ouputAudioNode);
  34582. this._inputAudioNode = this._soundPanner;
  34583. }
  34584. };
  34585. Sound.prototype._updateSpatialParameters = function () {
  34586. if (this.spatialSound) {
  34587. if (this.useCustomAttenuation) {
  34588. // Tricks to disable in a way embedded Web Audio attenuation
  34589. this._soundPanner.distanceModel = "linear";
  34590. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34591. this._soundPanner.refDistance = 1;
  34592. this._soundPanner.rolloffFactor = 1;
  34593. this._soundPanner.panningModel = this._panningModel;
  34594. }
  34595. else {
  34596. this._soundPanner.distanceModel = this.distanceModel;
  34597. this._soundPanner.maxDistance = this.maxDistance;
  34598. this._soundPanner.refDistance = this.refDistance;
  34599. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34600. this._soundPanner.panningModel = this._panningModel;
  34601. }
  34602. }
  34603. };
  34604. Sound.prototype.switchPanningModelToHRTF = function () {
  34605. this._panningModel = "HRTF";
  34606. this._switchPanningModel();
  34607. };
  34608. Sound.prototype.switchPanningModelToEqualPower = function () {
  34609. this._panningModel = "equalpower";
  34610. this._switchPanningModel();
  34611. };
  34612. Sound.prototype._switchPanningModel = function () {
  34613. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34614. this._soundPanner.panningModel = this._panningModel;
  34615. }
  34616. };
  34617. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34618. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34619. if (this._isOutputConnected) {
  34620. this._ouputAudioNode.disconnect();
  34621. }
  34622. this._ouputAudioNode.connect(soundTrackAudioNode);
  34623. this._isOutputConnected = true;
  34624. }
  34625. };
  34626. /**
  34627. * Transform this sound into a directional source
  34628. * @param coneInnerAngle Size of the inner cone in degree
  34629. * @param coneOuterAngle Size of the outer cone in degree
  34630. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34631. */
  34632. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34633. if (coneOuterAngle < coneInnerAngle) {
  34634. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34635. return;
  34636. }
  34637. this._coneInnerAngle = coneInnerAngle;
  34638. this._coneOuterAngle = coneOuterAngle;
  34639. this._coneOuterGain = coneOuterGain;
  34640. this._isDirectional = true;
  34641. if (this.isPlaying && this.loop) {
  34642. this.stop();
  34643. this.play();
  34644. }
  34645. };
  34646. Sound.prototype.setPosition = function (newPosition) {
  34647. this._position = newPosition;
  34648. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34649. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34650. }
  34651. };
  34652. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34653. this._localDirection = newLocalDirection;
  34654. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34655. this._updateDirection();
  34656. }
  34657. };
  34658. Sound.prototype._updateDirection = function () {
  34659. var mat = this._connectedMesh.getWorldMatrix();
  34660. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34661. direction.normalize();
  34662. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34663. };
  34664. Sound.prototype.updateDistanceFromListener = function () {
  34665. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34666. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34667. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34668. }
  34669. };
  34670. Sound.prototype.setAttenuationFunction = function (callback) {
  34671. this._customAttenuationFunction = callback;
  34672. };
  34673. /**
  34674. * Play the sound
  34675. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34676. */
  34677. Sound.prototype.play = function (time) {
  34678. var _this = this;
  34679. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34680. try {
  34681. if (this._startOffset < 0) {
  34682. time = -this._startOffset;
  34683. this._startOffset = 0;
  34684. }
  34685. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34686. if (!this._soundSource || !this._streamingSource) {
  34687. if (this.spatialSound) {
  34688. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34689. if (this._isDirectional) {
  34690. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34691. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34692. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34693. if (this._connectedMesh) {
  34694. this._updateDirection();
  34695. }
  34696. else {
  34697. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34698. }
  34699. }
  34700. }
  34701. }
  34702. if (this._streaming) {
  34703. if (!this._streamingSource) {
  34704. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34705. this._htmlAudioElement.onended = function () { _this._onended(); };
  34706. this._htmlAudioElement.playbackRate = this._playbackRate;
  34707. }
  34708. this._streamingSource.disconnect();
  34709. this._streamingSource.connect(this._inputAudioNode);
  34710. this._htmlAudioElement.play();
  34711. }
  34712. else {
  34713. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34714. this._soundSource.buffer = this._audioBuffer;
  34715. this._soundSource.connect(this._inputAudioNode);
  34716. this._soundSource.loop = this.loop;
  34717. this._soundSource.playbackRate.value = this._playbackRate;
  34718. this._soundSource.onended = function () { _this._onended(); };
  34719. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34720. }
  34721. this._startTime = startTime;
  34722. this.isPlaying = true;
  34723. this.isPaused = false;
  34724. }
  34725. catch (ex) {
  34726. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34727. }
  34728. }
  34729. };
  34730. Sound.prototype._onended = function () {
  34731. this.isPlaying = false;
  34732. if (this.onended) {
  34733. this.onended();
  34734. }
  34735. };
  34736. /**
  34737. * Stop the sound
  34738. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34739. */
  34740. Sound.prototype.stop = function (time) {
  34741. if (this.isPlaying) {
  34742. if (this._streaming) {
  34743. this._htmlAudioElement.pause();
  34744. // Test needed for Firefox or it will generate an Invalid State Error
  34745. if (this._htmlAudioElement.currentTime > 0) {
  34746. this._htmlAudioElement.currentTime = 0;
  34747. }
  34748. }
  34749. else {
  34750. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34751. this._soundSource.stop(stopTime);
  34752. if (!this.isPaused) {
  34753. this._startOffset = 0;
  34754. }
  34755. }
  34756. this.isPlaying = false;
  34757. }
  34758. };
  34759. Sound.prototype.pause = function () {
  34760. if (this.isPlaying) {
  34761. this.isPaused = true;
  34762. if (this._streaming) {
  34763. this._htmlAudioElement.pause();
  34764. }
  34765. else {
  34766. this.stop(0);
  34767. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34768. }
  34769. }
  34770. };
  34771. Sound.prototype.setVolume = function (newVolume, time) {
  34772. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34773. if (time) {
  34774. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34775. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34776. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34777. }
  34778. else {
  34779. this._soundGain.gain.value = newVolume;
  34780. }
  34781. }
  34782. this._volume = newVolume;
  34783. };
  34784. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34785. this._playbackRate = newPlaybackRate;
  34786. if (this.isPlaying) {
  34787. if (this._streaming) {
  34788. this._htmlAudioElement.playbackRate = this._playbackRate;
  34789. }
  34790. else {
  34791. this._soundSource.playbackRate.value = this._playbackRate;
  34792. }
  34793. }
  34794. };
  34795. Sound.prototype.getVolume = function () {
  34796. return this._volume;
  34797. };
  34798. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34799. var _this = this;
  34800. if (this._connectedMesh) {
  34801. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34802. this._registerFunc = null;
  34803. }
  34804. this._connectedMesh = meshToConnectTo;
  34805. if (!this.spatialSound) {
  34806. this.spatialSound = true;
  34807. this._createSpatialParameters();
  34808. if (this.isPlaying && this.loop) {
  34809. this.stop();
  34810. this.play();
  34811. }
  34812. }
  34813. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34814. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34815. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34816. };
  34817. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34818. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34819. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34820. this._updateDirection();
  34821. }
  34822. };
  34823. Sound.prototype.clone = function () {
  34824. var _this = this;
  34825. if (!this._streaming) {
  34826. var setBufferAndRun = function () {
  34827. if (_this._isReadyToPlay) {
  34828. clonedSound._audioBuffer = _this.getAudioBuffer();
  34829. clonedSound._isReadyToPlay = true;
  34830. if (clonedSound.autoplay) {
  34831. clonedSound.play();
  34832. }
  34833. }
  34834. else {
  34835. window.setTimeout(setBufferAndRun, 300);
  34836. }
  34837. };
  34838. var currentOptions = {
  34839. autoplay: this.autoplay, loop: this.loop,
  34840. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34841. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34842. refDistance: this.refDistance, distanceModel: this.distanceModel
  34843. };
  34844. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34845. if (this.useCustomAttenuation) {
  34846. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34847. }
  34848. clonedSound.setPosition(this._position);
  34849. clonedSound.setPlaybackRate(this._playbackRate);
  34850. setBufferAndRun();
  34851. return clonedSound;
  34852. }
  34853. else {
  34854. return null;
  34855. }
  34856. };
  34857. Sound.prototype.getAudioBuffer = function () {
  34858. return this._audioBuffer;
  34859. };
  34860. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34861. var soundName = parsedSound.name;
  34862. var soundUrl;
  34863. if (parsedSound.url) {
  34864. soundUrl = rootUrl + parsedSound.url;
  34865. }
  34866. else {
  34867. soundUrl = rootUrl + soundName;
  34868. }
  34869. var options = {
  34870. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34871. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34872. rolloffFactor: parsedSound.rolloffFactor,
  34873. refDistance: parsedSound.refDistance,
  34874. distanceModel: parsedSound.distanceModel,
  34875. playbackRate: parsedSound.playbackRate
  34876. };
  34877. var newSound;
  34878. if (!sourceSound) {
  34879. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34880. scene._addPendingData(newSound);
  34881. }
  34882. else {
  34883. var setBufferAndRun = function () {
  34884. if (sourceSound._isReadyToPlay) {
  34885. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34886. newSound._isReadyToPlay = true;
  34887. if (newSound.autoplay) {
  34888. newSound.play();
  34889. }
  34890. }
  34891. else {
  34892. window.setTimeout(setBufferAndRun, 300);
  34893. }
  34894. };
  34895. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34896. setBufferAndRun();
  34897. }
  34898. if (parsedSound.position) {
  34899. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34900. newSound.setPosition(soundPosition);
  34901. }
  34902. if (parsedSound.isDirectional) {
  34903. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34904. if (parsedSound.localDirectionToMesh) {
  34905. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34906. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34907. }
  34908. }
  34909. if (parsedSound.connectedMeshId) {
  34910. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34911. if (connectedMesh) {
  34912. newSound.attachToMesh(connectedMesh);
  34913. }
  34914. }
  34915. return newSound;
  34916. };
  34917. return Sound;
  34918. })();
  34919. BABYLON.Sound = Sound;
  34920. })(BABYLON || (BABYLON = {}));
  34921. var BABYLON;
  34922. (function (BABYLON) {
  34923. var SoundTrack = (function () {
  34924. function SoundTrack(scene, options) {
  34925. this.id = -1;
  34926. this._isMainTrack = false;
  34927. this._isInitialized = false;
  34928. this._scene = scene;
  34929. this.soundCollection = new Array();
  34930. this._options = options;
  34931. if (!this._isMainTrack) {
  34932. this._scene.soundTracks.push(this);
  34933. this.id = this._scene.soundTracks.length - 1;
  34934. }
  34935. }
  34936. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34937. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34938. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34939. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34940. if (this._options) {
  34941. if (this._options.volume) {
  34942. this._outputAudioNode.gain.value = this._options.volume;
  34943. }
  34944. if (this._options.mainTrack) {
  34945. this._isMainTrack = this._options.mainTrack;
  34946. }
  34947. }
  34948. this._isInitialized = true;
  34949. }
  34950. };
  34951. SoundTrack.prototype.dispose = function () {
  34952. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34953. if (this._connectedAnalyser) {
  34954. this._connectedAnalyser.stopDebugCanvas();
  34955. }
  34956. while (this.soundCollection.length) {
  34957. this.soundCollection[0].dispose();
  34958. }
  34959. if (this._outputAudioNode) {
  34960. this._outputAudioNode.disconnect();
  34961. }
  34962. this._outputAudioNode = null;
  34963. }
  34964. };
  34965. SoundTrack.prototype.AddSound = function (sound) {
  34966. if (!this._isInitialized) {
  34967. this._initializeSoundTrackAudioGraph();
  34968. }
  34969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34970. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34971. }
  34972. if (sound.soundTrackId) {
  34973. if (sound.soundTrackId === -1) {
  34974. this._scene.mainSoundTrack.RemoveSound(sound);
  34975. }
  34976. else {
  34977. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34978. }
  34979. }
  34980. this.soundCollection.push(sound);
  34981. sound.soundTrackId = this.id;
  34982. };
  34983. SoundTrack.prototype.RemoveSound = function (sound) {
  34984. var index = this.soundCollection.indexOf(sound);
  34985. if (index !== -1) {
  34986. this.soundCollection.splice(index, 1);
  34987. }
  34988. };
  34989. SoundTrack.prototype.setVolume = function (newVolume) {
  34990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34991. this._outputAudioNode.gain.value = newVolume;
  34992. }
  34993. };
  34994. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34996. for (var i = 0; i < this.soundCollection.length; i++) {
  34997. this.soundCollection[i].switchPanningModelToHRTF();
  34998. }
  34999. }
  35000. };
  35001. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35002. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35003. for (var i = 0; i < this.soundCollection.length; i++) {
  35004. this.soundCollection[i].switchPanningModelToEqualPower();
  35005. }
  35006. }
  35007. };
  35008. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35009. if (this._connectedAnalyser) {
  35010. this._connectedAnalyser.stopDebugCanvas();
  35011. }
  35012. this._connectedAnalyser = analyser;
  35013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35014. this._outputAudioNode.disconnect();
  35015. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35016. }
  35017. };
  35018. return SoundTrack;
  35019. })();
  35020. BABYLON.SoundTrack = SoundTrack;
  35021. })(BABYLON || (BABYLON = {}));
  35022. var BABYLON;
  35023. (function (BABYLON) {
  35024. var DepthRenderer = (function () {
  35025. function DepthRenderer(scene, type) {
  35026. var _this = this;
  35027. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35028. this._viewMatrix = BABYLON.Matrix.Zero();
  35029. this._projectionMatrix = BABYLON.Matrix.Zero();
  35030. this._transformMatrix = BABYLON.Matrix.Zero();
  35031. this._worldViewProjection = BABYLON.Matrix.Zero();
  35032. this._scene = scene;
  35033. var engine = scene.getEngine();
  35034. // Render target
  35035. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35036. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35037. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35038. this._depthMap.refreshRate = 1;
  35039. this._depthMap.renderParticles = false;
  35040. this._depthMap.renderList = null;
  35041. // set default depth value to 1.0 (far away)
  35042. this._depthMap.onClear = function (engine) {
  35043. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35044. };
  35045. // Custom render function
  35046. var renderSubMesh = function (subMesh) {
  35047. var mesh = subMesh.getRenderingMesh();
  35048. var scene = _this._scene;
  35049. var engine = scene.getEngine();
  35050. // Culling
  35051. engine.setState(subMesh.getMaterial().backFaceCulling);
  35052. // Managing instances
  35053. var batch = mesh._getInstancesRenderList(subMesh._id);
  35054. if (batch.mustReturn) {
  35055. return;
  35056. }
  35057. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35058. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35059. engine.enableEffect(_this._effect);
  35060. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35061. var material = subMesh.getMaterial();
  35062. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35063. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35064. // Alpha test
  35065. if (material && material.needAlphaTesting()) {
  35066. var alphaTexture = material.getAlphaTestTexture();
  35067. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35068. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35069. }
  35070. // Bones
  35071. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35072. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35073. }
  35074. // Draw
  35075. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35076. }
  35077. };
  35078. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35079. var index;
  35080. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35081. renderSubMesh(opaqueSubMeshes.data[index]);
  35082. }
  35083. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35084. renderSubMesh(alphaTestSubMeshes.data[index]);
  35085. }
  35086. };
  35087. }
  35088. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35089. var defines = [];
  35090. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35091. var mesh = subMesh.getMesh();
  35092. var scene = mesh.getScene();
  35093. var material = subMesh.getMaterial();
  35094. // Alpha test
  35095. if (material && material.needAlphaTesting()) {
  35096. defines.push("#define ALPHATEST");
  35097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35098. attribs.push(BABYLON.VertexBuffer.UVKind);
  35099. defines.push("#define UV1");
  35100. }
  35101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35102. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35103. defines.push("#define UV2");
  35104. }
  35105. }
  35106. // Bones
  35107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35110. if (mesh.numBoneInfluencers > 4) {
  35111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35113. }
  35114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35115. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35116. }
  35117. else {
  35118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35119. }
  35120. // Instances
  35121. if (useInstances) {
  35122. defines.push("#define INSTANCES");
  35123. attribs.push("world0");
  35124. attribs.push("world1");
  35125. attribs.push("world2");
  35126. attribs.push("world3");
  35127. }
  35128. // Get correct effect
  35129. var join = defines.join("\n");
  35130. if (this._cachedDefines !== join) {
  35131. this._cachedDefines = join;
  35132. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35133. }
  35134. return this._effect.isReady();
  35135. };
  35136. DepthRenderer.prototype.getDepthMap = function () {
  35137. return this._depthMap;
  35138. };
  35139. // Methods
  35140. DepthRenderer.prototype.dispose = function () {
  35141. this._depthMap.dispose();
  35142. };
  35143. return DepthRenderer;
  35144. })();
  35145. BABYLON.DepthRenderer = DepthRenderer;
  35146. })(BABYLON || (BABYLON = {}));
  35147. var BABYLON;
  35148. (function (BABYLON) {
  35149. var SSAORenderingPipeline = (function (_super) {
  35150. __extends(SSAORenderingPipeline, _super);
  35151. /**
  35152. * @constructor
  35153. * @param {string} name - The rendering pipeline name
  35154. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35155. * @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 }
  35156. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35157. */
  35158. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35159. var _this = this;
  35160. _super.call(this, scene.getEngine(), name);
  35161. // Members
  35162. /**
  35163. * The PassPostProcess id in the pipeline that contains the original scene color
  35164. * @type {string}
  35165. */
  35166. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35167. /**
  35168. * The SSAO PostProcess id in the pipeline
  35169. * @type {string}
  35170. */
  35171. this.SSAORenderEffect = "SSAORenderEffect";
  35172. /**
  35173. * The horizontal blur PostProcess id in the pipeline
  35174. * @type {string}
  35175. */
  35176. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35177. /**
  35178. * The vertical blur PostProcess id in the pipeline
  35179. * @type {string}
  35180. */
  35181. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35182. /**
  35183. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35184. * @type {string}
  35185. */
  35186. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35187. /**
  35188. * The output strength of the SSAO post-process. Default value is 1.0.
  35189. * @type {number}
  35190. */
  35191. this.totalStrength = 1.0;
  35192. /**
  35193. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35194. * @type {number}
  35195. */
  35196. this.radius = 0.0001;
  35197. /**
  35198. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35199. * Must not be equal to fallOff and superior to fallOff.
  35200. * Default value is 0.975
  35201. * @type {number}
  35202. */
  35203. this.area = 0.0075;
  35204. /**
  35205. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35206. * Must not be equal to area and inferior to area.
  35207. * Default value is 0.0
  35208. * @type {number}
  35209. */
  35210. this.fallOff = 0.000001;
  35211. /**
  35212. * The base color of the SSAO post-process
  35213. * The final result is "base + ssao" between [0, 1]
  35214. * @type {number}
  35215. */
  35216. this.base = 0.5;
  35217. this._firstUpdate = true;
  35218. this._scene = scene;
  35219. // Set up assets
  35220. this._createRandomTexture();
  35221. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35222. var ssaoRatio = ratio.ssaoRatio || ratio;
  35223. var combineRatio = ratio.combineRatio || ratio;
  35224. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35225. this._createSSAOPostProcess(ssaoRatio);
  35226. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35227. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35228. this._createSSAOCombinePostProcess(combineRatio);
  35229. // Set up pipeline
  35230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35235. // Finish
  35236. scene.postProcessRenderPipelineManager.addPipeline(this);
  35237. if (cameras)
  35238. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35239. }
  35240. // Public Methods
  35241. /**
  35242. * Returns the horizontal blur PostProcess
  35243. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35244. */
  35245. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35246. return this._blurHPostProcess;
  35247. };
  35248. /**
  35249. * Returns the vertical blur PostProcess
  35250. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35251. */
  35252. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35253. return this._blurVPostProcess;
  35254. };
  35255. /**
  35256. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35257. */
  35258. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35259. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35260. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35261. this._originalColorPostProcess = undefined;
  35262. this._ssaoPostProcess = undefined;
  35263. this._blurHPostProcess = undefined;
  35264. this._blurVPostProcess = undefined;
  35265. this._ssaoCombinePostProcess = undefined;
  35266. this._randomTexture.dispose();
  35267. if (disableDepthRender)
  35268. this._scene.disableDepthRenderer();
  35269. };
  35270. // Private Methods
  35271. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35272. var _this = this;
  35273. var numSamples = 16;
  35274. var sampleSphere = [
  35275. 0.5381, 0.1856, -0.4319,
  35276. 0.1379, 0.2486, 0.4430,
  35277. 0.3371, 0.5679, -0.0057,
  35278. -0.6999, -0.0451, -0.0019,
  35279. 0.0689, -0.1598, -0.8547,
  35280. 0.0560, 0.0069, -0.1843,
  35281. -0.0146, 0.1402, 0.0762,
  35282. 0.0100, -0.1924, -0.0344,
  35283. -0.3577, -0.5301, -0.4358,
  35284. -0.3169, 0.1063, 0.0158,
  35285. 0.0103, -0.5869, 0.0046,
  35286. -0.0897, -0.4940, 0.3287,
  35287. 0.7119, -0.0154, -0.0918,
  35288. -0.0533, 0.0596, -0.5411,
  35289. 0.0352, -0.0631, 0.5460,
  35290. -0.4776, 0.2847, -0.0271
  35291. ];
  35292. var samplesFactor = 1.0 / numSamples;
  35293. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35294. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35295. "area", "fallOff", "base"
  35296. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35297. this._ssaoPostProcess.onApply = function (effect) {
  35298. if (_this._firstUpdate) {
  35299. effect.setArray3("sampleSphere", sampleSphere);
  35300. effect.setFloat("samplesFactor", samplesFactor);
  35301. effect.setFloat("randTextureTiles", 4.0);
  35302. _this._firstUpdate = false;
  35303. }
  35304. effect.setFloat("totalStrength", _this.totalStrength);
  35305. effect.setFloat("radius", _this.radius);
  35306. effect.setFloat("area", _this.area);
  35307. effect.setFloat("fallOff", _this.fallOff);
  35308. effect.setFloat("base", _this.base);
  35309. effect.setTexture("textureSampler", _this._depthTexture);
  35310. effect.setTexture("randomSampler", _this._randomTexture);
  35311. };
  35312. };
  35313. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35314. var _this = this;
  35315. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35316. this._ssaoCombinePostProcess.onApply = function (effect) {
  35317. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35318. };
  35319. };
  35320. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35321. var size = 512;
  35322. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35323. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35324. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35325. var context = this._randomTexture.getContext();
  35326. var rand = function (min, max) {
  35327. return Math.random() * (max - min) + min;
  35328. };
  35329. var randVector = BABYLON.Vector3.Zero();
  35330. for (var x = 0; x < size; x++) {
  35331. for (var y = 0; y < size; y++) {
  35332. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35333. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35334. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35335. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35336. context.fillRect(x, y, 1, 1);
  35337. }
  35338. }
  35339. this._randomTexture.update(false);
  35340. };
  35341. return SSAORenderingPipeline;
  35342. })(BABYLON.PostProcessRenderPipeline);
  35343. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35344. })(BABYLON || (BABYLON = {}));
  35345. var BABYLON;
  35346. (function (BABYLON) {
  35347. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35348. var VolumetricLightScatteringPostProcess = (function (_super) {
  35349. __extends(VolumetricLightScatteringPostProcess, _super);
  35350. /**
  35351. * @constructor
  35352. * @param {string} name - The post-process name
  35353. * @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)
  35354. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35355. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35356. * @param {number} samples - The post-process quality, default 100
  35357. * @param {number} samplingMode - The post-process filtering mode
  35358. * @param {BABYLON.Engine} engine - The babylon engine
  35359. * @param {boolean} reusable - If the post-process is reusable
  35360. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35361. */
  35362. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35363. var _this = this;
  35364. if (samples === void 0) { samples = 100; }
  35365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35366. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35367. this._screenCoordinates = BABYLON.Vector2.Zero();
  35368. /**
  35369. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35370. * @type {boolean}
  35371. */
  35372. this.useCustomMeshPosition = false;
  35373. /**
  35374. * If the post-process should inverse the light scattering direction
  35375. * @type {boolean}
  35376. */
  35377. this.invert = true;
  35378. /**
  35379. * Set to true to use the diffuseColor instead of the diffuseTexture
  35380. * @type {boolean}
  35381. */
  35382. this.useDiffuseColor = false;
  35383. /**
  35384. * Array containing the excluded meshes not rendered in the internal pass
  35385. */
  35386. this.excludedMeshes = new Array();
  35387. /**
  35388. * Controls the overall intensity of the post-process
  35389. * @type {number}
  35390. */
  35391. this.exposure = 0.3;
  35392. /**
  35393. * Dissipates each sample's contribution in range [0, 1]
  35394. * @type {number}
  35395. */
  35396. this.decay = 0.96815;
  35397. /**
  35398. * Controls the overall intensity of each sample
  35399. * @type {number}
  35400. */
  35401. this.weight = 0.58767;
  35402. /**
  35403. * Controls the density of each sample
  35404. * @type {number}
  35405. */
  35406. this.density = 0.926;
  35407. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35408. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35409. // Configure mesh
  35410. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35411. // Configure
  35412. this._createPass(scene, ratio.passRatio || ratio);
  35413. this.onActivate = function (camera) {
  35414. if (!_this.isSupported) {
  35415. _this.dispose(camera);
  35416. }
  35417. _this.onActivate = null;
  35418. };
  35419. this.onApply = function (effect) {
  35420. _this._updateMeshScreenCoordinates(scene);
  35421. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35422. effect.setFloat("exposure", _this.exposure);
  35423. effect.setFloat("decay", _this.decay);
  35424. effect.setFloat("weight", _this.weight);
  35425. effect.setFloat("density", _this.density);
  35426. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35427. };
  35428. }
  35429. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35430. var mesh = subMesh.getMesh();
  35431. var defines = [];
  35432. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35433. var material = subMesh.getMaterial();
  35434. var needUV = false;
  35435. // Render this.mesh as default
  35436. if (mesh === this.mesh) {
  35437. if (this.useDiffuseColor) {
  35438. defines.push("#define DIFFUSE_COLOR_RENDER");
  35439. }
  35440. else if (material) {
  35441. if (material.diffuseTexture !== undefined) {
  35442. defines.push("#define BASIC_RENDER");
  35443. }
  35444. else {
  35445. defines.push("#define DIFFUSE_COLOR_RENDER");
  35446. }
  35447. }
  35448. defines.push("#define NEED_UV");
  35449. needUV = true;
  35450. }
  35451. // Alpha test
  35452. if (material) {
  35453. if (material.needAlphaTesting()) {
  35454. defines.push("#define ALPHATEST");
  35455. }
  35456. if (material.opacityTexture !== undefined) {
  35457. defines.push("#define OPACITY");
  35458. if (material.opacityTexture.getAlphaFromRGB) {
  35459. defines.push("#define OPACITYRGB");
  35460. }
  35461. if (!needUV) {
  35462. defines.push("#define NEED_UV");
  35463. }
  35464. }
  35465. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35466. attribs.push(BABYLON.VertexBuffer.UVKind);
  35467. defines.push("#define UV1");
  35468. }
  35469. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35470. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35471. defines.push("#define UV2");
  35472. }
  35473. }
  35474. // Bones
  35475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35478. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35479. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35480. }
  35481. else {
  35482. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35483. }
  35484. // Instances
  35485. if (useInstances) {
  35486. defines.push("#define INSTANCES");
  35487. attribs.push("world0");
  35488. attribs.push("world1");
  35489. attribs.push("world2");
  35490. attribs.push("world3");
  35491. }
  35492. // Get correct effect
  35493. var join = defines.join("\n");
  35494. if (this._cachedDefines !== join) {
  35495. this._cachedDefines = join;
  35496. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35497. }
  35498. return this._volumetricLightScatteringPass.isReady();
  35499. };
  35500. /**
  35501. * Sets the new light position for light scattering effect
  35502. * @param {BABYLON.Vector3} The new custom light position
  35503. */
  35504. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35505. this._customMeshPosition = position;
  35506. };
  35507. /**
  35508. * Returns the light position for light scattering effect
  35509. * @return {BABYLON.Vector3} The custom light position
  35510. */
  35511. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35512. return this._customMeshPosition;
  35513. };
  35514. /**
  35515. * Disposes the internal assets and detaches the post-process from the camera
  35516. */
  35517. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35518. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35519. if (rttIndex !== -1) {
  35520. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35521. }
  35522. this._volumetricLightScatteringRTT.dispose();
  35523. _super.prototype.dispose.call(this, camera);
  35524. };
  35525. /**
  35526. * Returns the render target texture used by the post-process
  35527. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35528. */
  35529. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35530. return this._volumetricLightScatteringRTT;
  35531. };
  35532. // Private methods
  35533. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35534. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35535. return true;
  35536. }
  35537. return false;
  35538. };
  35539. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35540. var _this = this;
  35541. var engine = scene.getEngine();
  35542. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35543. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35544. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35545. this._volumetricLightScatteringRTT.renderList = null;
  35546. this._volumetricLightScatteringRTT.renderParticles = false;
  35547. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35548. // Custom render function for submeshes
  35549. var renderSubMesh = function (subMesh) {
  35550. var mesh = subMesh.getRenderingMesh();
  35551. if (_this._meshExcluded(mesh)) {
  35552. return;
  35553. }
  35554. var scene = mesh.getScene();
  35555. var engine = scene.getEngine();
  35556. // Culling
  35557. engine.setState(subMesh.getMaterial().backFaceCulling);
  35558. // Managing instances
  35559. var batch = mesh._getInstancesRenderList(subMesh._id);
  35560. if (batch.mustReturn) {
  35561. return;
  35562. }
  35563. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35564. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35565. engine.enableEffect(_this._volumetricLightScatteringPass);
  35566. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35567. var material = subMesh.getMaterial();
  35568. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35569. // Alpha test
  35570. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35571. var alphaTexture = material.getAlphaTestTexture();
  35572. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35573. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35574. }
  35575. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35576. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35577. if (alphaTexture) {
  35578. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35579. }
  35580. }
  35581. if (material.opacityTexture !== undefined) {
  35582. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35583. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35584. }
  35585. }
  35586. // Bones
  35587. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35588. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35589. }
  35590. // Draw
  35591. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35592. }
  35593. };
  35594. // Render target texture callbacks
  35595. var savedSceneClearColor;
  35596. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35597. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35598. savedSceneClearColor = scene.clearColor;
  35599. scene.clearColor = sceneClearColor;
  35600. };
  35601. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35602. scene.clearColor = savedSceneClearColor;
  35603. };
  35604. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35605. var engine = scene.getEngine();
  35606. var index;
  35607. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35608. renderSubMesh(opaqueSubMeshes.data[index]);
  35609. }
  35610. engine.setAlphaTesting(true);
  35611. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35612. renderSubMesh(alphaTestSubMeshes.data[index]);
  35613. }
  35614. engine.setAlphaTesting(false);
  35615. if (transparentSubMeshes.length) {
  35616. // Sort sub meshes
  35617. for (index = 0; index < transparentSubMeshes.length; index++) {
  35618. var submesh = transparentSubMeshes.data[index];
  35619. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35620. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35621. }
  35622. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35623. sortedArray.sort(function (a, b) {
  35624. // Alpha index first
  35625. if (a._alphaIndex > b._alphaIndex) {
  35626. return 1;
  35627. }
  35628. if (a._alphaIndex < b._alphaIndex) {
  35629. return -1;
  35630. }
  35631. // Then distance to camera
  35632. if (a._distanceToCamera < b._distanceToCamera) {
  35633. return 1;
  35634. }
  35635. if (a._distanceToCamera > b._distanceToCamera) {
  35636. return -1;
  35637. }
  35638. return 0;
  35639. });
  35640. // Render sub meshes
  35641. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35642. for (index = 0; index < sortedArray.length; index++) {
  35643. renderSubMesh(sortedArray[index]);
  35644. }
  35645. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35646. }
  35647. };
  35648. };
  35649. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35650. var transform = scene.getTransformMatrix();
  35651. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35652. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35653. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35654. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35655. if (this.invert)
  35656. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35657. };
  35658. // Static methods
  35659. /**
  35660. * Creates a default mesh for the Volumeric Light Scattering post-process
  35661. * @param {string} The mesh name
  35662. * @param {BABYLON.Scene} The scene where to create the mesh
  35663. * @return {BABYLON.Mesh} the default mesh
  35664. */
  35665. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35666. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35667. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35668. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35669. return mesh;
  35670. };
  35671. return VolumetricLightScatteringPostProcess;
  35672. })(BABYLON.PostProcess);
  35673. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35674. })(BABYLON || (BABYLON = {}));
  35675. // BABYLON.JS Chromatic Aberration GLSL Shader
  35676. // Author: Olivier Guyot
  35677. // Separates very slightly R, G and B colors on the edges of the screen
  35678. // Inspired by Francois Tarlier & Martins Upitis
  35679. var BABYLON;
  35680. (function (BABYLON) {
  35681. var LensRenderingPipeline = (function (_super) {
  35682. __extends(LensRenderingPipeline, _super);
  35683. /**
  35684. * @constructor
  35685. *
  35686. * Effect parameters are as follow:
  35687. * {
  35688. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35689. * edge_blur: number; // from 0 to x (1 for realism)
  35690. * distortion: number; // from 0 to x (1 for realism)
  35691. * grain_amount: number; // from 0 to 1
  35692. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35693. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35694. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35695. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35696. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35697. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35698. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35699. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35700. * }
  35701. * Note: if an effect parameter is unset, effect is disabled
  35702. *
  35703. * @param {string} name - The rendering pipeline name
  35704. * @param {object} parameters - An object containing all parameters (see above)
  35705. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35706. * @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)
  35707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35708. */
  35709. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35710. var _this = this;
  35711. if (ratio === void 0) { ratio = 1.0; }
  35712. _super.call(this, scene.getEngine(), name);
  35713. // Lens effects can be of the following:
  35714. // - chromatic aberration (slight shift of RGB colors)
  35715. // - blur on the edge of the lens
  35716. // - lens distortion
  35717. // - depth-of-field blur & highlights enhancing
  35718. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35719. // - grain effect (noise or custom texture)
  35720. // Two additional texture samplers are needed:
  35721. // - depth map (for depth-of-field)
  35722. // - grain texture
  35723. /**
  35724. * The chromatic aberration PostProcess id in the pipeline
  35725. * @type {string}
  35726. */
  35727. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35728. /**
  35729. * The highlights enhancing PostProcess id in the pipeline
  35730. * @type {string}
  35731. */
  35732. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35733. /**
  35734. * The depth-of-field PostProcess id in the pipeline
  35735. * @type {string}
  35736. */
  35737. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35738. this._scene = scene;
  35739. // Fetch texture samplers
  35740. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35741. if (parameters.grain_texture) {
  35742. this._grainTexture = parameters.grain_texture;
  35743. }
  35744. else {
  35745. this._createGrainTexture();
  35746. }
  35747. // save parameters
  35748. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35749. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35750. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35751. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35752. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35753. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35754. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35755. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35756. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35757. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35758. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35759. // Create effects
  35760. this._createChromaticAberrationPostProcess(ratio);
  35761. this._createHighlightsPostProcess(ratio);
  35762. this._createDepthOfFieldPostProcess(ratio / 4);
  35763. // Set up pipeline
  35764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35765. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35767. if (this._highlightsGain === -1) {
  35768. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35769. }
  35770. // Finish
  35771. scene.postProcessRenderPipelineManager.addPipeline(this);
  35772. if (cameras) {
  35773. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35774. }
  35775. }
  35776. // public methods (self explanatory)
  35777. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35778. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35779. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35780. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35781. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35782. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35783. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35784. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35785. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35786. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35787. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35788. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35789. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35790. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35791. };
  35792. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35793. this._highlightsPostProcess.updateEffect();
  35794. };
  35795. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35796. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35797. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35798. this._highlightsGain = amount;
  35799. };
  35800. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35801. if (this._highlightsGain === -1) {
  35802. this._highlightsGain = 1.0;
  35803. }
  35804. this._highlightsThreshold = amount;
  35805. };
  35806. LensRenderingPipeline.prototype.disableHighlights = function () {
  35807. this._highlightsGain = -1;
  35808. };
  35809. /**
  35810. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35811. */
  35812. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35813. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35814. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35815. this._chromaticAberrationPostProcess = undefined;
  35816. this._highlightsPostProcess = undefined;
  35817. this._depthOfFieldPostProcess = undefined;
  35818. this._grainTexture.dispose();
  35819. if (disableDepthRender)
  35820. this._scene.disableDepthRenderer();
  35821. };
  35822. // colors shifting and distortion
  35823. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35824. var _this = this;
  35825. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35826. [], // samplers
  35827. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35828. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35829. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35830. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35831. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35832. };
  35833. };
  35834. // highlights enhancing
  35835. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35836. var _this = this;
  35837. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35838. [], // samplers
  35839. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35840. this._highlightsPostProcess.onApply = function (effect) {
  35841. effect.setFloat('gain', _this._highlightsGain);
  35842. effect.setFloat('threshold', _this._highlightsThreshold);
  35843. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35844. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35845. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35846. };
  35847. };
  35848. // colors shifting and distortion
  35849. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35850. var _this = this;
  35851. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35852. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35853. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35854. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35855. this._depthOfFieldPostProcess.onApply = function (effect) {
  35856. effect.setTexture("depthSampler", _this._depthTexture);
  35857. effect.setTexture("grainSampler", _this._grainTexture);
  35858. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35859. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35860. effect.setFloat('grain_amount', _this._grainAmount);
  35861. effect.setBool('blur_noise', _this._blurNoise);
  35862. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35863. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35864. effect.setFloat('distortion', _this._distortion);
  35865. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35866. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35867. effect.setFloat('aperture', _this._dofAperture);
  35868. effect.setFloat('darken', _this._dofDarken);
  35869. effect.setFloat('edge_blur', _this._edgeBlur);
  35870. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35871. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35872. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35873. };
  35874. };
  35875. // creates a black and white random noise texture, 512x512
  35876. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35877. var size = 512;
  35878. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35879. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35880. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35881. var context = this._grainTexture.getContext();
  35882. var rand = function (min, max) {
  35883. return Math.random() * (max - min) + min;
  35884. };
  35885. var value;
  35886. for (var x = 0; x < size; x++) {
  35887. for (var y = 0; y < size; y++) {
  35888. value = Math.floor(rand(0.42, 0.58) * 255);
  35889. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35890. context.fillRect(x, y, 1, 1);
  35891. }
  35892. }
  35893. this._grainTexture.update(false);
  35894. };
  35895. return LensRenderingPipeline;
  35896. })(BABYLON.PostProcessRenderPipeline);
  35897. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35898. })(BABYLON || (BABYLON = {}));
  35899. //
  35900. // This post-process allows the modification of rendered colors by using
  35901. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35902. //
  35903. // The object needs to be provided an url to a texture containing the color
  35904. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35905. // Use an image editing software to tweak the LUT to match your needs.
  35906. //
  35907. // For an example of a color LUT, see here:
  35908. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35909. // For explanations on color grading, see here:
  35910. // http://udn.epicgames.com/Three/ColorGrading.html
  35911. //
  35912. var BABYLON;
  35913. (function (BABYLON) {
  35914. var ColorCorrectionPostProcess = (function (_super) {
  35915. __extends(ColorCorrectionPostProcess, _super);
  35916. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35917. var _this = this;
  35918. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35919. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35920. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35921. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35922. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35923. this.onApply = function (effect) {
  35924. effect.setTexture("colorTable", _this._colorTableTexture);
  35925. };
  35926. }
  35927. return ColorCorrectionPostProcess;
  35928. })(BABYLON.PostProcess);
  35929. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35930. })(BABYLON || (BABYLON = {}));
  35931. var BABYLON;
  35932. (function (BABYLON) {
  35933. var HDRRenderingPipeline = (function (_super) {
  35934. __extends(HDRRenderingPipeline, _super);
  35935. /**
  35936. * @constructor
  35937. * @param {string} name - The rendering pipeline name
  35938. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35939. * @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)
  35940. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35941. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35942. */
  35943. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35944. var _this = this;
  35945. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35946. _super.call(this, scene.getEngine(), name);
  35947. /**
  35948. * Public members
  35949. */
  35950. // Gaussian Blur
  35951. /**
  35952. * Gaussian blur coefficient
  35953. * @type {number}
  35954. */
  35955. this.gaussCoeff = 0.3;
  35956. /**
  35957. * Gaussian blur mean
  35958. * @type {number}
  35959. */
  35960. this.gaussMean = 1.0;
  35961. /**
  35962. * Gaussian blur standard deviation
  35963. * @type {number}
  35964. */
  35965. this.gaussStandDev = 0.8;
  35966. /**
  35967. * Gaussian blur multiplier. Multiplies the blur effect
  35968. * @type {number}
  35969. */
  35970. this.gaussMultiplier = 4.0;
  35971. // HDR
  35972. /**
  35973. * Exposure, controls the overall intensity of the pipeline
  35974. * @type {number}
  35975. */
  35976. this.exposure = 1.0;
  35977. /**
  35978. * Minimum luminance that the post-process can output. Luminance is >= 0
  35979. * @type {number}
  35980. */
  35981. this.minimumLuminance = 1.0;
  35982. /**
  35983. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35984. * @type {number}
  35985. */
  35986. this.maximumLuminance = 1e20;
  35987. /**
  35988. * Increase rate for luminance: eye adaptation speed to dark
  35989. * @type {number}
  35990. */
  35991. this.luminanceIncreaserate = 0.5;
  35992. /**
  35993. * Decrease rate for luminance: eye adaptation speed to bright
  35994. * @type {number}
  35995. */
  35996. this.luminanceDecreaseRate = 0.5;
  35997. // Bright pass
  35998. /**
  35999. * Minimum luminance needed to compute HDR
  36000. * @type {number}
  36001. */
  36002. this.brightThreshold = 0.8;
  36003. this._needUpdate = true;
  36004. this._scene = scene;
  36005. // Bright pass
  36006. this._createBrightPassPostProcess(scene, ratio);
  36007. // Down sample X4
  36008. this._createDownSampleX4PostProcess(scene, ratio);
  36009. // Create gaussian blur post-processes
  36010. this._createGaussianBlurPostProcess(scene, ratio);
  36011. // Texture adder
  36012. this._createTextureAdderPostProcess(scene, ratio);
  36013. // Luminance generator
  36014. this._createLuminanceGeneratorPostProcess(scene);
  36015. // HDR
  36016. this._createHDRPostProcess(scene, ratio);
  36017. // Pass postprocess
  36018. if (originalPostProcess === null) {
  36019. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36020. }
  36021. else {
  36022. this._originalPostProcess = originalPostProcess;
  36023. }
  36024. // Configure pipeline
  36025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36031. var addDownSamplerPostProcess = function (id) {
  36032. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36033. };
  36034. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36035. addDownSamplerPostProcess(i);
  36036. }
  36037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36038. // Finish
  36039. scene.postProcessRenderPipelineManager.addPipeline(this);
  36040. if (cameras !== null) {
  36041. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36042. }
  36043. this.update();
  36044. }
  36045. /**
  36046. * Tells the pipeline to update its post-processes
  36047. */
  36048. HDRRenderingPipeline.prototype.update = function () {
  36049. this._needUpdate = true;
  36050. };
  36051. /**
  36052. * Returns the current calculated luminance
  36053. */
  36054. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36055. return this._hdrCurrentLuminance;
  36056. };
  36057. /**
  36058. * Returns the currently drawn luminance
  36059. */
  36060. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36061. return this._hdrOutputLuminance;
  36062. };
  36063. /**
  36064. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36065. */
  36066. HDRRenderingPipeline.prototype.dispose = function () {
  36067. this._originalPostProcess = undefined;
  36068. this._brightPassPostProcess = undefined;
  36069. this._downSampleX4PostProcess = undefined;
  36070. this._guassianBlurHPostProcess = undefined;
  36071. this._guassianBlurVPostProcess = undefined;
  36072. this._textureAdderPostProcess = undefined;
  36073. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36074. this._downSamplePostProcesses[i] = undefined;
  36075. }
  36076. this._hdrPostProcess = undefined;
  36077. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36078. };
  36079. /**
  36080. * Creates the HDR post-process and computes the luminance adaptation
  36081. */
  36082. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36083. var _this = this;
  36084. var hdrLastLuminance = 0.0;
  36085. this._hdrOutputLuminance = -1.0;
  36086. this._hdrCurrentLuminance = 1.0;
  36087. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36088. this._hdrPostProcess.onApply = function (effect) {
  36089. if (_this._hdrOutputLuminance < 0.0) {
  36090. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36091. }
  36092. else {
  36093. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36094. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36095. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36096. }
  36097. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36098. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36099. }
  36100. else {
  36101. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36102. }
  36103. }
  36104. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36105. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36106. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36107. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36108. effect.setFloat("exposure", _this.exposure);
  36109. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36110. _this._needUpdate = false;
  36111. };
  36112. };
  36113. /**
  36114. * Texture Adder post-process
  36115. */
  36116. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36117. var _this = this;
  36118. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36119. this._textureAdderPostProcess.onApply = function (effect) {
  36120. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36121. };
  36122. };
  36123. /**
  36124. * Down sample X4 post-process
  36125. */
  36126. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36127. var _this = this;
  36128. var downSampleX4Offsets = new Array(32);
  36129. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36130. this._downSampleX4PostProcess.onApply = function (effect) {
  36131. if (_this._needUpdate) {
  36132. var id = 0;
  36133. for (var i = -2; i < 2; i++) {
  36134. for (var j = -2; j < 2; j++) {
  36135. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36136. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36137. id += 2;
  36138. }
  36139. }
  36140. }
  36141. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36142. };
  36143. };
  36144. /**
  36145. * Bright pass post-process
  36146. */
  36147. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36148. var _this = this;
  36149. var brightOffsets = new Array(8);
  36150. var brightPassCallback = function (effect) {
  36151. if (_this._needUpdate) {
  36152. var sU = (1.0 / _this._brightPassPostProcess.width);
  36153. var sV = (1.0 / _this._brightPassPostProcess.height);
  36154. brightOffsets[0] = -0.5 * sU;
  36155. brightOffsets[1] = 0.5 * sV;
  36156. brightOffsets[2] = 0.5 * sU;
  36157. brightOffsets[3] = 0.5 * sV;
  36158. brightOffsets[4] = -0.5 * sU;
  36159. brightOffsets[5] = -0.5 * sV;
  36160. brightOffsets[6] = 0.5 * sU;
  36161. brightOffsets[7] = -0.5 * sV;
  36162. }
  36163. effect.setArray2("dsOffsets", brightOffsets);
  36164. effect.setFloat("brightThreshold", _this.brightThreshold);
  36165. };
  36166. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36167. this._brightPassPostProcess.onApply = brightPassCallback;
  36168. };
  36169. /**
  36170. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36171. */
  36172. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36173. var _this = this;
  36174. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36175. var luminanceOffsets = new Array(8);
  36176. var downSampleOffsets = new Array(18);
  36177. var halfDestPixelSize;
  36178. this._downSamplePostProcesses = new Array(lumSteps);
  36179. // Utils for luminance
  36180. var luminanceUpdateSourceOffsets = function (width, height) {
  36181. var sU = (1.0 / width);
  36182. var sV = (1.0 / height);
  36183. luminanceOffsets[0] = -0.5 * sU;
  36184. luminanceOffsets[1] = 0.5 * sV;
  36185. luminanceOffsets[2] = 0.5 * sU;
  36186. luminanceOffsets[3] = 0.5 * sV;
  36187. luminanceOffsets[4] = -0.5 * sU;
  36188. luminanceOffsets[5] = -0.5 * sV;
  36189. luminanceOffsets[6] = 0.5 * sU;
  36190. luminanceOffsets[7] = -0.5 * sV;
  36191. };
  36192. var luminanceUpdateDestOffsets = function (width, height) {
  36193. var id = 0;
  36194. for (var x = -1; x < 2; x++) {
  36195. for (var y = -1; y < 2; y++) {
  36196. downSampleOffsets[id] = (x) / width;
  36197. downSampleOffsets[id + 1] = (y) / height;
  36198. id += 2;
  36199. }
  36200. }
  36201. };
  36202. // Luminance callback
  36203. var luminanceCallback = function (effect) {
  36204. if (_this._needUpdate) {
  36205. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36206. }
  36207. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36208. effect.setArray2("lumOffsets", luminanceOffsets);
  36209. };
  36210. // Down sample callbacks
  36211. var downSampleCallback = function (indice) {
  36212. var i = indice;
  36213. return function (effect) {
  36214. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36215. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36216. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36217. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36218. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36219. effect.setArray2("dsOffsets", downSampleOffsets);
  36220. };
  36221. };
  36222. var downSampleAfterRenderCallback = function (effect) {
  36223. // Unpack result
  36224. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36225. 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);
  36226. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36227. };
  36228. // Create luminance post-process
  36229. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36230. 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);
  36231. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36232. // Create down sample post-processes
  36233. for (var i = lumSteps - 2; i >= 0; i--) {
  36234. var length = Math.pow(3, i);
  36235. ratio = { width: length, height: length };
  36236. var defines = "#define DOWN_SAMPLE\n";
  36237. if (i === 0) {
  36238. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36239. }
  36240. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36241. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36242. if (i === 0) {
  36243. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36244. }
  36245. }
  36246. };
  36247. /**
  36248. * Gaussian blur post-processes. Horizontal and Vertical
  36249. */
  36250. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36251. var _this = this;
  36252. var blurOffsetsW = new Array(9);
  36253. var blurOffsetsH = new Array(9);
  36254. var blurWeights = new Array(9);
  36255. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36256. // Utils for gaussian blur
  36257. var calculateBlurOffsets = function (height) {
  36258. var lastOutputDimensions = {
  36259. width: scene.getEngine().getRenderWidth(),
  36260. height: scene.getEngine().getRenderHeight()
  36261. };
  36262. for (var i = 0; i < 9; i++) {
  36263. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36264. if (height) {
  36265. blurOffsetsH[i] = value;
  36266. }
  36267. else {
  36268. blurOffsetsW[i] = value;
  36269. }
  36270. }
  36271. };
  36272. var calculateWeights = function () {
  36273. var x = 0.0;
  36274. for (var i = 0; i < 9; i++) {
  36275. x = (i - 4.0) / 4.0;
  36276. 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));
  36277. }
  36278. };
  36279. // Callback
  36280. var gaussianBlurCallback = function (height) {
  36281. return function (effect) {
  36282. if (_this._needUpdate) {
  36283. calculateWeights();
  36284. calculateBlurOffsets(height);
  36285. }
  36286. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36287. effect.setArray("blurWeights", blurWeights);
  36288. effect.setFloat("multiplier", _this.gaussMultiplier);
  36289. };
  36290. };
  36291. // Create horizontal gaussian blur post-processes
  36292. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36293. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36294. // Create vertical gaussian blur post-process
  36295. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36296. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36297. };
  36298. // Luminance generator
  36299. HDRRenderingPipeline.LUM_STEPS = 6;
  36300. return HDRRenderingPipeline;
  36301. })(BABYLON.PostProcessRenderPipeline);
  36302. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36303. })(BABYLON || (BABYLON = {}));
  36304. var BABYLON;
  36305. (function (BABYLON) {
  36306. var FaceAdjacencies = (function () {
  36307. function FaceAdjacencies() {
  36308. this.edges = new Array();
  36309. this.edgesConnectedCount = 0;
  36310. }
  36311. return FaceAdjacencies;
  36312. })();
  36313. var EdgesRenderer = (function () {
  36314. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36315. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36316. if (epsilon === void 0) { epsilon = 0.95; }
  36317. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36318. this.edgesWidthScalerForOrthographic = 1000.0;
  36319. this.edgesWidthScalerForPerspective = 50.0;
  36320. this._linesPositions = new Array();
  36321. this._linesNormals = new Array();
  36322. this._linesIndices = new Array();
  36323. this._buffers = new Array();
  36324. this._checkVerticesInsteadOfIndices = false;
  36325. this._source = source;
  36326. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36327. this._epsilon = epsilon;
  36328. this._prepareRessources();
  36329. this._generateEdgesLines();
  36330. }
  36331. EdgesRenderer.prototype._prepareRessources = function () {
  36332. if (this._lineShader) {
  36333. return;
  36334. }
  36335. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36336. attributes: ["position", "normal"],
  36337. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36338. });
  36339. this._lineShader.disableDepthWrite = true;
  36340. this._lineShader.backFaceCulling = false;
  36341. };
  36342. EdgesRenderer.prototype.dispose = function () {
  36343. this._vb0.dispose();
  36344. this._vb1.dispose();
  36345. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36346. this._lineShader.dispose();
  36347. };
  36348. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36349. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36350. return 0;
  36351. }
  36352. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36353. return 1;
  36354. }
  36355. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36356. return 2;
  36357. }
  36358. return -1;
  36359. };
  36360. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36361. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36362. return 0;
  36363. }
  36364. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36365. return 1;
  36366. }
  36367. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36368. return 2;
  36369. }
  36370. return -1;
  36371. };
  36372. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36373. var needToCreateLine;
  36374. if (edge === undefined) {
  36375. needToCreateLine = true;
  36376. }
  36377. else {
  36378. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36379. needToCreateLine = dotProduct < this._epsilon;
  36380. }
  36381. if (needToCreateLine) {
  36382. var offset = this._linesPositions.length / 3;
  36383. var normal = p0.subtract(p1);
  36384. normal.normalize();
  36385. // Positions
  36386. this._linesPositions.push(p0.x);
  36387. this._linesPositions.push(p0.y);
  36388. this._linesPositions.push(p0.z);
  36389. this._linesPositions.push(p0.x);
  36390. this._linesPositions.push(p0.y);
  36391. this._linesPositions.push(p0.z);
  36392. this._linesPositions.push(p1.x);
  36393. this._linesPositions.push(p1.y);
  36394. this._linesPositions.push(p1.z);
  36395. this._linesPositions.push(p1.x);
  36396. this._linesPositions.push(p1.y);
  36397. this._linesPositions.push(p1.z);
  36398. // Normals
  36399. this._linesNormals.push(p1.x);
  36400. this._linesNormals.push(p1.y);
  36401. this._linesNormals.push(p1.z);
  36402. this._linesNormals.push(-1);
  36403. this._linesNormals.push(p1.x);
  36404. this._linesNormals.push(p1.y);
  36405. this._linesNormals.push(p1.z);
  36406. this._linesNormals.push(1);
  36407. this._linesNormals.push(p0.x);
  36408. this._linesNormals.push(p0.y);
  36409. this._linesNormals.push(p0.z);
  36410. this._linesNormals.push(-1);
  36411. this._linesNormals.push(p0.x);
  36412. this._linesNormals.push(p0.y);
  36413. this._linesNormals.push(p0.z);
  36414. this._linesNormals.push(1);
  36415. // Indices
  36416. this._linesIndices.push(offset);
  36417. this._linesIndices.push(offset + 1);
  36418. this._linesIndices.push(offset + 2);
  36419. this._linesIndices.push(offset);
  36420. this._linesIndices.push(offset + 2);
  36421. this._linesIndices.push(offset + 3);
  36422. }
  36423. };
  36424. EdgesRenderer.prototype._generateEdgesLines = function () {
  36425. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36426. var indices = this._source.getIndices();
  36427. // First let's find adjacencies
  36428. var adjacencies = new Array();
  36429. var faceNormals = new Array();
  36430. var index;
  36431. var faceAdjacencies;
  36432. // Prepare faces
  36433. for (index = 0; index < indices.length; index += 3) {
  36434. faceAdjacencies = new FaceAdjacencies();
  36435. var p0Index = indices[index];
  36436. var p1Index = indices[index + 1];
  36437. var p2Index = indices[index + 2];
  36438. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36439. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36440. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36441. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36442. faceNormal.normalize();
  36443. faceNormals.push(faceNormal);
  36444. adjacencies.push(faceAdjacencies);
  36445. }
  36446. // Scan
  36447. for (index = 0; index < adjacencies.length; index++) {
  36448. faceAdjacencies = adjacencies[index];
  36449. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36450. var otherFaceAdjacencies = adjacencies[otherIndex];
  36451. if (faceAdjacencies.edgesConnectedCount === 3) {
  36452. break;
  36453. }
  36454. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36455. continue;
  36456. }
  36457. var otherP0 = indices[otherIndex * 3];
  36458. var otherP1 = indices[otherIndex * 3 + 1];
  36459. var otherP2 = indices[otherIndex * 3 + 2];
  36460. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36461. var otherEdgeIndex;
  36462. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36463. continue;
  36464. }
  36465. switch (edgeIndex) {
  36466. case 0:
  36467. if (this._checkVerticesInsteadOfIndices) {
  36468. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36469. }
  36470. else {
  36471. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36472. }
  36473. break;
  36474. case 1:
  36475. if (this._checkVerticesInsteadOfIndices) {
  36476. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36477. }
  36478. else {
  36479. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36480. }
  36481. break;
  36482. case 2:
  36483. if (this._checkVerticesInsteadOfIndices) {
  36484. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36485. }
  36486. else {
  36487. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36488. }
  36489. break;
  36490. }
  36491. if (otherEdgeIndex === -1) {
  36492. continue;
  36493. }
  36494. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36495. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36496. faceAdjacencies.edgesConnectedCount++;
  36497. otherFaceAdjacencies.edgesConnectedCount++;
  36498. if (faceAdjacencies.edgesConnectedCount === 3) {
  36499. break;
  36500. }
  36501. }
  36502. }
  36503. }
  36504. // Create lines
  36505. for (index = 0; index < adjacencies.length; index++) {
  36506. // 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
  36507. var current = adjacencies[index];
  36508. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36509. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36510. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36511. }
  36512. // Merge into a single mesh
  36513. var engine = this._source.getScene().getEngine();
  36514. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36515. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36516. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36517. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36518. this._ib = engine.createIndexBuffer(this._linesIndices);
  36519. this._indicesCount = this._linesIndices.length;
  36520. };
  36521. EdgesRenderer.prototype.render = function () {
  36522. if (!this._lineShader.isReady()) {
  36523. return;
  36524. }
  36525. var scene = this._source.getScene();
  36526. var engine = scene.getEngine();
  36527. this._lineShader._preBind();
  36528. // VBOs
  36529. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36530. scene.resetCachedMaterial();
  36531. this._lineShader.setColor4("color", this._source.edgesColor);
  36532. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36533. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36534. }
  36535. else {
  36536. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36537. }
  36538. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36539. this._lineShader.bind(this._source.getWorldMatrix());
  36540. // Draw order
  36541. engine.draw(true, 0, this._indicesCount);
  36542. this._lineShader.unbind();
  36543. engine.setDepthWrite(true);
  36544. };
  36545. return EdgesRenderer;
  36546. })();
  36547. BABYLON.EdgesRenderer = EdgesRenderer;
  36548. })(BABYLON || (BABYLON = {}));
  36549. var BABYLON;
  36550. (function (BABYLON) {
  36551. (function (TonemappingOperator) {
  36552. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36553. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36554. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36555. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36556. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36557. var TonemappingOperator = BABYLON.TonemappingOperator;
  36558. ;
  36559. var TonemapPostProcess = (function (_super) {
  36560. __extends(TonemapPostProcess, _super);
  36561. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36562. var _this = this;
  36563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36564. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36565. this._operator = operator;
  36566. this.exposureAdjustment = exposureAdjustment;
  36567. var params = ["_ExposureAdjustment"];
  36568. var defines = "#define ";
  36569. if (operator === TonemappingOperator.Hable)
  36570. defines += "HABLE_TONEMAPPING";
  36571. else if (operator === TonemappingOperator.Reinhard)
  36572. defines += "REINHARD_TONEMAPPING";
  36573. else if (operator === TonemappingOperator.HejiDawson)
  36574. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36575. else if (operator === TonemappingOperator.Photographic)
  36576. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36577. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36578. this.onApply = function (effect) {
  36579. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  36580. };
  36581. }
  36582. return TonemapPostProcess;
  36583. })(BABYLON.PostProcess);
  36584. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36585. })(BABYLON || (BABYLON = {}));
  36586. var BABYLON;
  36587. (function (BABYLON) {
  36588. var ReflectionProbe = (function () {
  36589. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36590. var _this = this;
  36591. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36592. this.name = name;
  36593. this._viewMatrix = BABYLON.Matrix.Identity();
  36594. this._target = BABYLON.Vector3.Zero();
  36595. this._add = BABYLON.Vector3.Zero();
  36596. this.position = BABYLON.Vector3.Zero();
  36597. this._scene = scene;
  36598. this._scene.reflectionProbes.push(this);
  36599. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36600. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36601. switch (faceIndex) {
  36602. case 0:
  36603. _this._add.copyFromFloats(1, 0, 0);
  36604. break;
  36605. case 1:
  36606. _this._add.copyFromFloats(-1, 0, 0);
  36607. break;
  36608. case 2:
  36609. _this._add.copyFromFloats(0, -1, 0);
  36610. break;
  36611. case 3:
  36612. _this._add.copyFromFloats(0, 1, 0);
  36613. break;
  36614. case 4:
  36615. _this._add.copyFromFloats(0, 0, 1);
  36616. break;
  36617. case 5:
  36618. _this._add.copyFromFloats(0, 0, -1);
  36619. break;
  36620. }
  36621. if (_this._attachedMesh) {
  36622. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36623. }
  36624. _this.position.addToRef(_this._add, _this._target);
  36625. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36626. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36627. };
  36628. this._renderTargetTexture.onAfterUnbind = function () {
  36629. scene.updateTransformMatrix(true);
  36630. };
  36631. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36632. }
  36633. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36634. get: function () {
  36635. return this._renderTargetTexture.refreshRate;
  36636. },
  36637. set: function (value) {
  36638. this._renderTargetTexture.refreshRate = value;
  36639. },
  36640. enumerable: true,
  36641. configurable: true
  36642. });
  36643. ReflectionProbe.prototype.getScene = function () {
  36644. return this._scene;
  36645. };
  36646. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36647. get: function () {
  36648. return this._renderTargetTexture;
  36649. },
  36650. enumerable: true,
  36651. configurable: true
  36652. });
  36653. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36654. get: function () {
  36655. return this._renderTargetTexture.renderList;
  36656. },
  36657. enumerable: true,
  36658. configurable: true
  36659. });
  36660. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36661. this._attachedMesh = mesh;
  36662. };
  36663. ReflectionProbe.prototype.dispose = function () {
  36664. var index = this._scene.reflectionProbes.indexOf(this);
  36665. if (index !== -1) {
  36666. // Remove from the scene if found
  36667. this._scene.reflectionProbes.splice(index, 1);
  36668. }
  36669. if (this._renderTargetTexture) {
  36670. this._renderTargetTexture.dispose();
  36671. this._renderTargetTexture = null;
  36672. }
  36673. };
  36674. return ReflectionProbe;
  36675. })();
  36676. BABYLON.ReflectionProbe = ReflectionProbe;
  36677. })(BABYLON || (BABYLON = {}));
  36678. var BABYLON;
  36679. (function (BABYLON) {
  36680. var SolidParticle = (function () {
  36681. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36682. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36683. this.position = BABYLON.Vector3.Zero(); // position
  36684. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36685. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36686. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36687. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36688. this.alive = true; // alive
  36689. this.idx = particleIndex;
  36690. this._pos = positionIndex;
  36691. this._model = model;
  36692. this.shapeId = shapeId;
  36693. this.idxInShape = idxInShape;
  36694. }
  36695. return SolidParticle;
  36696. })();
  36697. BABYLON.SolidParticle = SolidParticle;
  36698. var ModelShape = (function () {
  36699. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36700. this.shapeID = id;
  36701. this._shape = shape;
  36702. this._shapeUV = shapeUV;
  36703. this._positionFunction = posFunction;
  36704. this._vertexFunction = vtxFunction;
  36705. }
  36706. return ModelShape;
  36707. })();
  36708. BABYLON.ModelShape = ModelShape;
  36709. })(BABYLON || (BABYLON = {}));
  36710. var BABYLON;
  36711. (function (BABYLON) {
  36712. /**
  36713. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36714. */
  36715. var SolidParticleSystem = (function () {
  36716. /**
  36717. * Creates a SPS (Solid Particle System) object.
  36718. * @param name the SPS name, this will be the underlying mesh name
  36719. * @param scene the scene in which the SPS is added
  36720. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  36721. */
  36722. function SolidParticleSystem(name, scene, options) {
  36723. // public members
  36724. /**
  36725. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36726. * Example : var p = SPS.particles[i];
  36727. */
  36728. this.particles = new Array();
  36729. /**
  36730. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36731. */
  36732. this.nbParticles = 0;
  36733. /**
  36734. * If the particles must ever face the camera (default false). Useful for planar particles.
  36735. */
  36736. this.billboard = false;
  36737. /**
  36738. * This a counter ofr your own usage. It's not set by any SPS functions.
  36739. */
  36740. this.counter = 0;
  36741. /**
  36742. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36743. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  36744. */
  36745. this.vars = {};
  36746. this._positions = new Array();
  36747. this._indices = new Array();
  36748. this._normals = new Array();
  36749. this._colors = new Array();
  36750. this._uvs = new Array();
  36751. this._index = 0; // indices index
  36752. this._updatable = true;
  36753. this._pickable = false;
  36754. this._isVisibilityBoxLocked = false;
  36755. this._alwaysVisible = false;
  36756. this._shapeCounter = 0;
  36757. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36758. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36759. this._computeParticleColor = true;
  36760. this._computeParticleTexture = true;
  36761. this._computeParticleRotation = true;
  36762. this._computeParticleVertex = false;
  36763. this._computeBoundingBox = false;
  36764. this._cam_axisZ = BABYLON.Vector3.Zero();
  36765. this._cam_axisY = BABYLON.Vector3.Zero();
  36766. this._cam_axisX = BABYLON.Vector3.Zero();
  36767. this._axisX = BABYLON.Axis.X;
  36768. this._axisY = BABYLON.Axis.Y;
  36769. this._axisZ = BABYLON.Axis.Z;
  36770. this._fakeCamPos = BABYLON.Vector3.Zero();
  36771. this._rotMatrix = new BABYLON.Matrix();
  36772. this._invertMatrix = new BABYLON.Matrix();
  36773. this._rotated = BABYLON.Vector3.Zero();
  36774. this._quaternion = new BABYLON.Quaternion();
  36775. this._vertex = BABYLON.Vector3.Zero();
  36776. this._normal = BABYLON.Vector3.Zero();
  36777. this._yaw = 0.0;
  36778. this._pitch = 0.0;
  36779. this._roll = 0.0;
  36780. this._halfroll = 0.0;
  36781. this._halfpitch = 0.0;
  36782. this._halfyaw = 0.0;
  36783. this._sinRoll = 0.0;
  36784. this._cosRoll = 0.0;
  36785. this._sinPitch = 0.0;
  36786. this._cosPitch = 0.0;
  36787. this._sinYaw = 0.0;
  36788. this._cosYaw = 0.0;
  36789. this._w = 0.0;
  36790. this._minimum = BABYLON.Tmp.Vector3[0];
  36791. this._maximum = BABYLON.Tmp.Vector3[1];
  36792. this.name = name;
  36793. this._scene = scene;
  36794. this._camera = scene.activeCamera;
  36795. this._pickable = options ? options.isPickable : false;
  36796. if (options && options.updatable) {
  36797. this._updatable = options.updatable;
  36798. }
  36799. else {
  36800. this._updatable = true;
  36801. }
  36802. if (this._pickable) {
  36803. this.pickedParticles = [];
  36804. }
  36805. }
  36806. /**
  36807. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36808. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36809. */
  36810. SolidParticleSystem.prototype.buildMesh = function () {
  36811. if (this.nbParticles === 0) {
  36812. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36813. this.addShape(triangle, 1);
  36814. triangle.dispose();
  36815. }
  36816. this._positions32 = new Float32Array(this._positions);
  36817. this._uvs32 = new Float32Array(this._uvs);
  36818. this._colors32 = new Float32Array(this._colors);
  36819. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36820. this._normals32 = new Float32Array(this._normals);
  36821. this._fixedNormal32 = new Float32Array(this._normals);
  36822. var vertexData = new BABYLON.VertexData();
  36823. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36824. vertexData.indices = this._indices;
  36825. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36826. if (this._uvs32) {
  36827. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36828. ;
  36829. }
  36830. if (this._colors32) {
  36831. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36832. }
  36833. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36834. vertexData.applyToMesh(mesh, this._updatable);
  36835. this.mesh = mesh;
  36836. this.mesh.isPickable = this._pickable;
  36837. // free memory
  36838. this._positions = null;
  36839. this._normals = null;
  36840. this._uvs = null;
  36841. this._colors = null;
  36842. if (!this._updatable) {
  36843. this.particles.length = 0;
  36844. }
  36845. return mesh;
  36846. };
  36847. /**
  36848. * Digests the mesh and generates as many solid particles in the system as wanted.
  36849. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36850. * Thus the particles generated from digest() have their property "positiion" yet set.
  36851. * @param mesh the mesh to be digested
  36852. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  36853. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  36854. */
  36855. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36856. var size = (options && options.facetNb) || 1;
  36857. var number = (options && options.number);
  36858. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36859. var meshInd = mesh.getIndices();
  36860. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36861. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36862. var f = 0; // facet counter
  36863. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36864. // compute size from number
  36865. if (number) {
  36866. number = (number > totalFacets) ? totalFacets : number;
  36867. size = Math.round(totalFacets / number);
  36868. }
  36869. else {
  36870. size = (size > totalFacets) ? totalFacets : size;
  36871. }
  36872. var facetPos = []; // submesh positions
  36873. var facetInd = []; // submesh indices
  36874. var facetUV = []; // submesh UV
  36875. var facetCol = []; // submesh colors
  36876. var barycenter = BABYLON.Tmp.Vector3[0];
  36877. while (f < totalFacets) {
  36878. if (f > totalFacets - size) {
  36879. size = totalFacets - f;
  36880. }
  36881. // reset temp arrays
  36882. facetPos.length = 0;
  36883. facetInd.length = 0;
  36884. facetUV.length = 0;
  36885. facetCol.length = 0;
  36886. // iterate over "size" facets
  36887. var fi = 0;
  36888. for (var j = f * 3; j < (f + size) * 3; j++) {
  36889. facetInd.push(fi);
  36890. var i = meshInd[j];
  36891. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36892. if (meshUV) {
  36893. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36894. }
  36895. if (meshCol) {
  36896. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36897. }
  36898. fi++;
  36899. }
  36900. // create a model shape for each single particle
  36901. var idx = this.nbParticles;
  36902. var shape = this._posToShape(facetPos);
  36903. var shapeUV = this._uvsToShapeUV(facetUV);
  36904. // compute the barycenter of the shape
  36905. var v;
  36906. for (v = 0; v < shape.length; v++) {
  36907. barycenter.addInPlace(shape[v]);
  36908. }
  36909. barycenter.scaleInPlace(1 / shape.length);
  36910. // shift the shape from its barycenter to the origin
  36911. for (v = 0; v < shape.length; v++) {
  36912. shape[v].subtractInPlace(barycenter);
  36913. }
  36914. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36915. // add the particle in the SPS
  36916. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  36917. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  36918. // initialize the particle position
  36919. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36920. this._index += shape.length;
  36921. idx++;
  36922. this.nbParticles++;
  36923. this._shapeCounter++;
  36924. f += size;
  36925. }
  36926. };
  36927. //reset copy
  36928. SolidParticleSystem.prototype._resetCopy = function () {
  36929. this._copy.position.x = 0;
  36930. this._copy.position.y = 0;
  36931. this._copy.position.z = 0;
  36932. this._copy.rotation.x = 0;
  36933. this._copy.rotation.y = 0;
  36934. this._copy.rotation.z = 0;
  36935. this._copy.quaternion = null;
  36936. this._copy.scale.x = 1;
  36937. this._copy.scale.y = 1;
  36938. this._copy.scale.z = 1;
  36939. this._copy.uvs.x = 0;
  36940. this._copy.uvs.y = 0;
  36941. this._copy.uvs.z = 1;
  36942. this._copy.uvs.w = 1;
  36943. this._copy.color = null;
  36944. };
  36945. // _meshBuilder : inserts the shape model in the global SPS mesh
  36946. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36947. var i;
  36948. var u = 0;
  36949. var c = 0;
  36950. this._resetCopy();
  36951. if (options && options.positionFunction) {
  36952. options.positionFunction(this._copy, idx, idxInShape);
  36953. }
  36954. if (this._copy.quaternion) {
  36955. this._quaternion.x = this._copy.quaternion.x;
  36956. this._quaternion.y = this._copy.quaternion.y;
  36957. this._quaternion.z = this._copy.quaternion.z;
  36958. this._quaternion.w = this._copy.quaternion.w;
  36959. }
  36960. else {
  36961. this._yaw = this._copy.rotation.y;
  36962. this._pitch = this._copy.rotation.x;
  36963. this._roll = this._copy.rotation.z;
  36964. this._quaternionRotationYPR();
  36965. }
  36966. this._quaternionToRotationMatrix();
  36967. for (i = 0; i < shape.length; i++) {
  36968. this._vertex.x = shape[i].x;
  36969. this._vertex.y = shape[i].y;
  36970. this._vertex.z = shape[i].z;
  36971. if (options && options.vertexFunction) {
  36972. options.vertexFunction(this._copy, this._vertex, i);
  36973. }
  36974. this._vertex.x *= this._copy.scale.x;
  36975. this._vertex.y *= this._copy.scale.y;
  36976. this._vertex.z *= this._copy.scale.z;
  36977. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36978. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36979. if (meshUV) {
  36980. 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);
  36981. u += 2;
  36982. }
  36983. if (this._copy.color) {
  36984. this._color = this._copy.color;
  36985. }
  36986. else if (meshCol && meshCol[c]) {
  36987. this._color.r = meshCol[c];
  36988. this._color.g = meshCol[c + 1];
  36989. this._color.b = meshCol[c + 2];
  36990. this._color.a = meshCol[c + 3];
  36991. }
  36992. else {
  36993. this._color.r = 1;
  36994. this._color.g = 1;
  36995. this._color.b = 1;
  36996. this._color.a = 1;
  36997. }
  36998. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36999. c += 4;
  37000. }
  37001. for (i = 0; i < meshInd.length; i++) {
  37002. indices.push(p + meshInd[i]);
  37003. }
  37004. if (this._pickable) {
  37005. var nbfaces = meshInd.length / 3;
  37006. for (i = 0; i < nbfaces; i++) {
  37007. this.pickedParticles.push({ idx: idx, faceId: i });
  37008. }
  37009. }
  37010. };
  37011. // returns a shape array from positions array
  37012. SolidParticleSystem.prototype._posToShape = function (positions) {
  37013. var shape = [];
  37014. for (var i = 0; i < positions.length; i += 3) {
  37015. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37016. }
  37017. return shape;
  37018. };
  37019. // returns a shapeUV array from a Vector4 uvs
  37020. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37021. var shapeUV = [];
  37022. if (uvs) {
  37023. for (var i = 0; i < uvs.length; i++)
  37024. shapeUV.push(uvs[i]);
  37025. }
  37026. return shapeUV;
  37027. };
  37028. // adds a new particle object in the particles array
  37029. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37030. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37031. };
  37032. /**
  37033. * Adds some particles to the SPS from the model shape.
  37034. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37035. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37036. * @param nb the number of particles to be created from this model
  37037. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37038. */
  37039. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37040. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37041. var meshInd = mesh.getIndices();
  37042. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37043. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37044. var shape = this._posToShape(meshPos);
  37045. var shapeUV = this._uvsToShapeUV(meshUV);
  37046. var posfunc = options ? options.positionFunction : null;
  37047. var vtxfunc = options ? options.vertexFunction : null;
  37048. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37049. // particles
  37050. var idx = this.nbParticles;
  37051. for (var i = 0; i < nb; i++) {
  37052. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37053. if (this._updatable) {
  37054. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37055. }
  37056. this._index += shape.length;
  37057. idx++;
  37058. }
  37059. this.nbParticles += nb;
  37060. this._shapeCounter++;
  37061. return this._shapeCounter - 1;
  37062. };
  37063. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37064. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37065. this._resetCopy();
  37066. if (particle._model._positionFunction) {
  37067. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37068. }
  37069. if (this._copy.quaternion) {
  37070. this._quaternion.x = this._copy.quaternion.x;
  37071. this._quaternion.y = this._copy.quaternion.y;
  37072. this._quaternion.z = this._copy.quaternion.z;
  37073. this._quaternion.w = this._copy.quaternion.w;
  37074. }
  37075. else {
  37076. this._yaw = this._copy.rotation.y;
  37077. this._pitch = this._copy.rotation.x;
  37078. this._roll = this._copy.rotation.z;
  37079. this._quaternionRotationYPR();
  37080. }
  37081. this._quaternionToRotationMatrix();
  37082. this._shape = particle._model._shape;
  37083. for (var pt = 0; pt < this._shape.length; pt++) {
  37084. this._vertex.x = this._shape[pt].x;
  37085. this._vertex.y = this._shape[pt].y;
  37086. this._vertex.z = this._shape[pt].z;
  37087. if (particle._model._vertexFunction) {
  37088. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37089. }
  37090. this._vertex.x *= this._copy.scale.x;
  37091. this._vertex.y *= this._copy.scale.y;
  37092. this._vertex.z *= this._copy.scale.z;
  37093. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37094. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37095. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37096. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37097. }
  37098. particle.position.x = 0;
  37099. particle.position.y = 0;
  37100. particle.position.z = 0;
  37101. particle.rotation.x = 0;
  37102. particle.rotation.y = 0;
  37103. particle.rotation.z = 0;
  37104. particle.quaternion = null;
  37105. particle.scale.x = 1;
  37106. particle.scale.y = 1;
  37107. particle.scale.z = 1;
  37108. };
  37109. /**
  37110. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37111. */
  37112. SolidParticleSystem.prototype.rebuildMesh = function () {
  37113. for (var p = 0; p < this.particles.length; p++) {
  37114. this._rebuildParticle(this.particles[p]);
  37115. }
  37116. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37117. };
  37118. /**
  37119. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37120. * This method calls updateParticle() for each particles of the SPS.
  37121. * For an animated SPS, it is usually called within the render loop.
  37122. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37123. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37124. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37125. */
  37126. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37127. if (start === void 0) { start = 0; }
  37128. if (end === void 0) { end = this.nbParticles - 1; }
  37129. if (update === void 0) { update = true; }
  37130. if (!this._updatable) {
  37131. return;
  37132. }
  37133. // custom beforeUpdate
  37134. this.beforeUpdateParticles(start, end, update);
  37135. this._cam_axisX.x = 1;
  37136. this._cam_axisX.y = 0;
  37137. this._cam_axisX.z = 0;
  37138. this._cam_axisY.x = 0;
  37139. this._cam_axisY.y = 1;
  37140. this._cam_axisY.z = 0;
  37141. this._cam_axisZ.x = 0;
  37142. this._cam_axisZ.y = 0;
  37143. this._cam_axisZ.z = 1;
  37144. // if the particles will always face the camera
  37145. if (this.billboard) {
  37146. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37147. this._yaw = this.mesh.rotation.y;
  37148. this._pitch = this.mesh.rotation.x;
  37149. this._roll = this.mesh.rotation.z;
  37150. this._quaternionRotationYPR();
  37151. this._quaternionToRotationMatrix();
  37152. this._rotMatrix.invertToRef(this._invertMatrix);
  37153. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37154. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37155. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37156. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37157. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37158. this._cam_axisY.normalize();
  37159. this._cam_axisX.normalize();
  37160. this._cam_axisZ.normalize();
  37161. }
  37162. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37163. var idx = 0;
  37164. var index = 0;
  37165. var colidx = 0;
  37166. var colorIndex = 0;
  37167. var uvidx = 0;
  37168. var uvIndex = 0;
  37169. if (this._computeBoundingBox) {
  37170. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37171. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37172. }
  37173. // particle loop
  37174. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37175. for (var p = start; p <= end; p++) {
  37176. this._particle = this.particles[p];
  37177. this._shape = this._particle._model._shape;
  37178. this._shapeUV = this._particle._model._shapeUV;
  37179. // call to custom user function to update the particle properties
  37180. this.updateParticle(this._particle);
  37181. // particle rotation matrix
  37182. if (this.billboard) {
  37183. this._particle.rotation.x = 0.0;
  37184. this._particle.rotation.y = 0.0;
  37185. }
  37186. if (this._computeParticleRotation) {
  37187. if (this._particle.quaternion) {
  37188. this._quaternion.x = this._particle.quaternion.x;
  37189. this._quaternion.y = this._particle.quaternion.y;
  37190. this._quaternion.z = this._particle.quaternion.z;
  37191. this._quaternion.w = this._particle.quaternion.w;
  37192. }
  37193. else {
  37194. this._yaw = this._particle.rotation.y;
  37195. this._pitch = this._particle.rotation.x;
  37196. this._roll = this._particle.rotation.z;
  37197. this._quaternionRotationYPR();
  37198. }
  37199. this._quaternionToRotationMatrix();
  37200. }
  37201. for (var pt = 0; pt < this._shape.length; pt++) {
  37202. idx = index + pt * 3;
  37203. colidx = colorIndex + pt * 4;
  37204. uvidx = uvIndex + pt * 2;
  37205. this._vertex.x = this._shape[pt].x;
  37206. this._vertex.y = this._shape[pt].y;
  37207. this._vertex.z = this._shape[pt].z;
  37208. if (this._computeParticleVertex) {
  37209. this.updateParticleVertex(this._particle, this._vertex, pt);
  37210. }
  37211. // positions
  37212. this._vertex.x *= this._particle.scale.x;
  37213. this._vertex.y *= this._particle.scale.y;
  37214. this._vertex.z *= this._particle.scale.z;
  37215. 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];
  37216. 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;
  37217. 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;
  37218. 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;
  37219. 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;
  37220. 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;
  37221. 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;
  37222. if (this._computeBoundingBox) {
  37223. if (this._positions32[idx] < this._minimum.x) {
  37224. this._minimum.x = this._positions32[idx];
  37225. }
  37226. if (this._positions32[idx] > this._maximum.x) {
  37227. this._maximum.x = this._positions32[idx];
  37228. }
  37229. if (this._positions32[idx + 1] < this._minimum.y) {
  37230. this._minimum.y = this._positions32[idx + 1];
  37231. }
  37232. if (this._positions32[idx + 1] > this._maximum.y) {
  37233. this._maximum.y = this._positions32[idx + 1];
  37234. }
  37235. if (this._positions32[idx + 2] < this._minimum.z) {
  37236. this._minimum.z = this._positions32[idx + 2];
  37237. }
  37238. if (this._positions32[idx + 2] > this._maximum.z) {
  37239. this._maximum.z = this._positions32[idx + 2];
  37240. }
  37241. }
  37242. // normals : if the particles can't be morphed then just rotate the normals
  37243. if (!this._computeParticleVertex && !this.billboard) {
  37244. this._normal.x = this._fixedNormal32[idx];
  37245. this._normal.y = this._fixedNormal32[idx + 1];
  37246. this._normal.z = this._fixedNormal32[idx + 2];
  37247. 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];
  37248. 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;
  37249. 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;
  37250. 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;
  37251. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37252. 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;
  37253. 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;
  37254. }
  37255. if (this._computeParticleColor) {
  37256. this._colors32[colidx] = this._particle.color.r;
  37257. this._colors32[colidx + 1] = this._particle.color.g;
  37258. this._colors32[colidx + 2] = this._particle.color.b;
  37259. this._colors32[colidx + 3] = this._particle.color.a;
  37260. }
  37261. if (this._computeParticleTexture) {
  37262. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37263. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37264. }
  37265. }
  37266. index = idx + 3;
  37267. colorIndex = colidx + 4;
  37268. uvIndex = uvidx + 2;
  37269. }
  37270. if (update) {
  37271. if (this._computeParticleColor) {
  37272. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37273. }
  37274. if (this._computeParticleTexture) {
  37275. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37276. }
  37277. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37278. if (!this.mesh.areNormalsFrozen) {
  37279. if (this._computeParticleVertex || this.billboard) {
  37280. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37281. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37282. for (var i = 0; i < this._normals32.length; i++) {
  37283. this._fixedNormal32[i] = this._normals32[i];
  37284. }
  37285. }
  37286. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37287. }
  37288. }
  37289. if (this._computeBoundingBox) {
  37290. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37291. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37292. }
  37293. this.afterUpdateParticles(start, end, update);
  37294. };
  37295. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37296. this._halfroll = this._roll * 0.5;
  37297. this._halfpitch = this._pitch * 0.5;
  37298. this._halfyaw = this._yaw * 0.5;
  37299. this._sinRoll = Math.sin(this._halfroll);
  37300. this._cosRoll = Math.cos(this._halfroll);
  37301. this._sinPitch = Math.sin(this._halfpitch);
  37302. this._cosPitch = Math.cos(this._halfpitch);
  37303. this._sinYaw = Math.sin(this._halfyaw);
  37304. this._cosYaw = Math.cos(this._halfyaw);
  37305. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37306. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37307. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37308. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37309. };
  37310. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37311. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37312. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37313. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37314. this._rotMatrix.m[3] = 0;
  37315. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37316. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37317. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37318. this._rotMatrix.m[7] = 0;
  37319. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37320. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37321. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37322. this._rotMatrix.m[11] = 0;
  37323. this._rotMatrix.m[12] = 0;
  37324. this._rotMatrix.m[13] = 0;
  37325. this._rotMatrix.m[14] = 0;
  37326. this._rotMatrix.m[15] = 1.0;
  37327. };
  37328. /**
  37329. * Disposes the SPS
  37330. */
  37331. SolidParticleSystem.prototype.dispose = function () {
  37332. this.mesh.dispose();
  37333. this.vars = null;
  37334. // drop references to internal big arrays for the GC
  37335. this._positions = null;
  37336. this._indices = null;
  37337. this._normals = null;
  37338. this._uvs = null;
  37339. this._colors = null;
  37340. this._positions32 = null;
  37341. this._normals32 = null;
  37342. this._fixedNormal32 = null;
  37343. this._uvs32 = null;
  37344. this._colors32 = null;
  37345. this.pickedParticles = null;
  37346. };
  37347. /**
  37348. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37349. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37350. */
  37351. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37352. if (!this._isVisibilityBoxLocked) {
  37353. this.mesh.refreshBoundingInfo();
  37354. }
  37355. };
  37356. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37357. * @param size the size (float) of the visibility box
  37358. * note : this doesn't lock the SPS mesh bounding box.
  37359. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37360. */
  37361. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37362. var vis = size / 2;
  37363. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37364. };
  37365. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37366. // getter and setter
  37367. /**
  37368. * True if the SPS is set as always visible
  37369. */
  37370. get: function () {
  37371. return this._alwaysVisible;
  37372. },
  37373. /**
  37374. * Sets the SPS as always visible or not
  37375. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37376. */
  37377. set: function (val) {
  37378. this._alwaysVisible = val;
  37379. this.mesh.alwaysSelectAsActiveMesh = val;
  37380. },
  37381. enumerable: true,
  37382. configurable: true
  37383. });
  37384. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37385. /**
  37386. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37387. */
  37388. get: function () {
  37389. return this._isVisibilityBoxLocked;
  37390. },
  37391. /**
  37392. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37393. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37394. */
  37395. set: function (val) {
  37396. this._isVisibilityBoxLocked = val;
  37397. this.mesh.getBoundingInfo().isLocked = val;
  37398. },
  37399. enumerable: true,
  37400. configurable: true
  37401. });
  37402. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37403. // getters
  37404. get: function () {
  37405. return this._computeParticleRotation;
  37406. },
  37407. // Optimizer setters
  37408. /**
  37409. * Tells to setParticles() to compute the particle rotations or not.
  37410. * Default value : true. The SPS is faster when it's set to false.
  37411. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37412. */
  37413. set: function (val) {
  37414. this._computeParticleRotation = val;
  37415. },
  37416. enumerable: true,
  37417. configurable: true
  37418. });
  37419. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37420. get: function () {
  37421. return this._computeParticleColor;
  37422. },
  37423. /**
  37424. * Tells to setParticles() to compute the particle colors or not.
  37425. * Default value : true. The SPS is faster when it's set to false.
  37426. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37427. */
  37428. set: function (val) {
  37429. this._computeParticleColor = val;
  37430. },
  37431. enumerable: true,
  37432. configurable: true
  37433. });
  37434. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37435. get: function () {
  37436. return this._computeParticleTexture;
  37437. },
  37438. /**
  37439. * Tells to setParticles() to compute the particle textures or not.
  37440. * Default value : true. The SPS is faster when it's set to false.
  37441. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37442. */
  37443. set: function (val) {
  37444. this._computeParticleTexture = val;
  37445. },
  37446. enumerable: true,
  37447. configurable: true
  37448. });
  37449. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37450. get: function () {
  37451. return this._computeParticleVertex;
  37452. },
  37453. /**
  37454. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  37455. * Default value : false. The SPS is faster when it's set to false.
  37456. * Note : the particle custom vertex positions aren't stored values.
  37457. */
  37458. set: function (val) {
  37459. this._computeParticleVertex = val;
  37460. },
  37461. enumerable: true,
  37462. configurable: true
  37463. });
  37464. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37465. get: function () {
  37466. return this._computeBoundingBox;
  37467. },
  37468. /**
  37469. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  37470. */
  37471. set: function (val) {
  37472. this._computeBoundingBox = val;
  37473. },
  37474. enumerable: true,
  37475. configurable: true
  37476. });
  37477. // =======================================================================
  37478. // Particle behavior logic
  37479. // these following methods may be overwritten by the user to fit his needs
  37480. /**
  37481. * This function does nothing. It may be overwritten to set all the particles first values.
  37482. * The SPS doesn't call this function, you may have to call it by your own.
  37483. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37484. */
  37485. SolidParticleSystem.prototype.initParticles = function () {
  37486. };
  37487. /**
  37488. * This function does nothing. It may be overwritten to recycle a particle.
  37489. * The SPS doesn't call this function, you may have to call it by your own.
  37490. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37491. */
  37492. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37493. return particle;
  37494. };
  37495. /**
  37496. * Updates a particle : this function should be overwritten by the user.
  37497. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37498. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37499. * ex : just set a particle position or velocity and recycle conditions
  37500. */
  37501. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37502. return particle;
  37503. };
  37504. /**
  37505. * Updates a vertex of a particle : it can be overwritten by the user.
  37506. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37507. * @param particle the current particle
  37508. * @param vertex the current index of the current particle
  37509. * @param pt the index of the current vertex in the particle shape
  37510. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37511. * ex : just set a vertex particle position
  37512. */
  37513. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37514. return vertex;
  37515. };
  37516. /**
  37517. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37518. * This does nothing and may be overwritten by the user.
  37519. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37520. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37521. * @param update the boolean update value actually passed to setParticles()
  37522. */
  37523. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37524. };
  37525. /**
  37526. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37527. * This will be passed three parameters.
  37528. * This does nothing and may be overwritten by the user.
  37529. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37530. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37531. * @param update the boolean update value actually passed to setParticles()
  37532. */
  37533. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37534. };
  37535. return SolidParticleSystem;
  37536. })();
  37537. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37538. })(BABYLON || (BABYLON = {}));
  37539. var BABYLON;
  37540. (function (BABYLON) {
  37541. // We're mainly based on the logic defined into the FreeCamera code
  37542. var UniversalCamera = (function (_super) {
  37543. __extends(UniversalCamera, _super);
  37544. function UniversalCamera(name, position, scene) {
  37545. var _this = this;
  37546. _super.call(this, name, position, scene);
  37547. this.gamepadAngularSensibility = 200;
  37548. this.gamepadMoveSensibility = 40;
  37549. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  37550. }
  37551. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  37552. // Only the first gamepad can control the camera
  37553. if (gamepad.index === 0) {
  37554. this.gamepad = gamepad;
  37555. }
  37556. };
  37557. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  37558. _super.prototype.attachControl.call(this, canvas, false);
  37559. };
  37560. UniversalCamera.prototype.detachControl = function (canvas) {
  37561. _super.prototype.detachControl.call(this, canvas);
  37562. };
  37563. UniversalCamera.prototype._checkInputs = function () {
  37564. if (this.gamepad) {
  37565. var LSValues = this.gamepad.leftStick;
  37566. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  37567. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  37568. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  37569. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  37570. var RSValues = this.gamepad.rightStick;
  37571. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  37572. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  37573. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  37574. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  37575. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  37576. var speed = this._computeLocalCameraSpeed() * 50.0;
  37577. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  37578. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  37579. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  37580. }
  37581. _super.prototype._checkInputs.call(this);
  37582. };
  37583. UniversalCamera.prototype.dispose = function () {
  37584. this._gamepads.dispose();
  37585. _super.prototype.dispose.call(this);
  37586. };
  37587. return UniversalCamera;
  37588. })(BABYLON.TouchCamera);
  37589. BABYLON.UniversalCamera = UniversalCamera;
  37590. })(BABYLON || (BABYLON = {}));
  37591. var BABYLON;
  37592. (function (BABYLON) {
  37593. var Gamepads = (function () {
  37594. function Gamepads(ongamedpadconnected) {
  37595. var _this = this;
  37596. this.babylonGamepads = [];
  37597. this.oneGamepadConnected = false;
  37598. this.isMonitoring = false;
  37599. this.gamepadEventSupported = 'GamepadEvent' in window;
  37600. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37601. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37602. this._callbackGamepadConnected = ongamedpadconnected;
  37603. if (this.gamepadSupportAvailable) {
  37604. // Checking if the gamepad connected event is supported (like in Firefox)
  37605. if (this.gamepadEventSupported) {
  37606. window.addEventListener('gamepadconnected', function (evt) {
  37607. _this._onGamepadConnected(evt);
  37608. }, false);
  37609. window.addEventListener('gamepaddisconnected', function (evt) {
  37610. _this._onGamepadDisconnected(evt);
  37611. }, false);
  37612. }
  37613. else {
  37614. this._startMonitoringGamepads();
  37615. }
  37616. }
  37617. }
  37618. Gamepads.prototype.dispose = function () {
  37619. if (Gamepads.gamepadDOMInfo) {
  37620. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37621. }
  37622. };
  37623. Gamepads.prototype._onGamepadConnected = function (evt) {
  37624. var newGamepad = this._addNewGamepad(evt.gamepad);
  37625. if (this._callbackGamepadConnected)
  37626. this._callbackGamepadConnected(newGamepad);
  37627. this._startMonitoringGamepads();
  37628. };
  37629. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37630. if (!this.oneGamepadConnected) {
  37631. this.oneGamepadConnected = true;
  37632. if (Gamepads.gamepadDOMInfo) {
  37633. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37634. Gamepads.gamepadDOMInfo = null;
  37635. }
  37636. }
  37637. var newGamepad;
  37638. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37639. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37640. }
  37641. else {
  37642. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37643. }
  37644. this.babylonGamepads.push(newGamepad);
  37645. return newGamepad;
  37646. };
  37647. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37648. // Remove the gamepad from the list of gamepads to monitor.
  37649. for (var i in this.babylonGamepads) {
  37650. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37651. this.babylonGamepads.splice(i, 1);
  37652. break;
  37653. }
  37654. }
  37655. // If no gamepads are left, stop the polling loop.
  37656. if (this.babylonGamepads.length == 0) {
  37657. this._stopMonitoringGamepads();
  37658. }
  37659. };
  37660. Gamepads.prototype._startMonitoringGamepads = function () {
  37661. if (!this.isMonitoring) {
  37662. this.isMonitoring = true;
  37663. this._checkGamepadsStatus();
  37664. }
  37665. };
  37666. Gamepads.prototype._stopMonitoringGamepads = function () {
  37667. this.isMonitoring = false;
  37668. };
  37669. Gamepads.prototype._checkGamepadsStatus = function () {
  37670. var _this = this;
  37671. // updating gamepad objects
  37672. this._updateGamepadObjects();
  37673. for (var i in this.babylonGamepads) {
  37674. this.babylonGamepads[i].update();
  37675. }
  37676. if (this.isMonitoring) {
  37677. if (window.requestAnimationFrame) {
  37678. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37679. }
  37680. else if (window.mozRequestAnimationFrame) {
  37681. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37682. }
  37683. else if (window.webkitRequestAnimationFrame) {
  37684. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37685. }
  37686. }
  37687. };
  37688. // This function is called only on Chrome, which does not yet support
  37689. // connection/disconnection events, but requires you to monitor
  37690. // an array for changes.
  37691. Gamepads.prototype._updateGamepadObjects = function () {
  37692. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37693. for (var i = 0; i < gamepads.length; i++) {
  37694. if (gamepads[i]) {
  37695. if (!(gamepads[i].index in this.babylonGamepads)) {
  37696. var newGamepad = this._addNewGamepad(gamepads[i]);
  37697. if (this._callbackGamepadConnected) {
  37698. this._callbackGamepadConnected(newGamepad);
  37699. }
  37700. }
  37701. else {
  37702. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37703. }
  37704. }
  37705. }
  37706. };
  37707. return Gamepads;
  37708. })();
  37709. BABYLON.Gamepads = Gamepads;
  37710. var StickValues = (function () {
  37711. function StickValues(x, y) {
  37712. this.x = x;
  37713. this.y = y;
  37714. }
  37715. return StickValues;
  37716. })();
  37717. BABYLON.StickValues = StickValues;
  37718. var Gamepad = (function () {
  37719. function Gamepad(id, index, browserGamepad) {
  37720. this.id = id;
  37721. this.index = index;
  37722. this.browserGamepad = browserGamepad;
  37723. if (this.browserGamepad.axes.length >= 2) {
  37724. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37725. }
  37726. if (this.browserGamepad.axes.length >= 4) {
  37727. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37728. }
  37729. }
  37730. Gamepad.prototype.onleftstickchanged = function (callback) {
  37731. this._onleftstickchanged = callback;
  37732. };
  37733. Gamepad.prototype.onrightstickchanged = function (callback) {
  37734. this._onrightstickchanged = callback;
  37735. };
  37736. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37737. get: function () {
  37738. return this._leftStick;
  37739. },
  37740. set: function (newValues) {
  37741. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37742. this._onleftstickchanged(newValues);
  37743. }
  37744. this._leftStick = newValues;
  37745. },
  37746. enumerable: true,
  37747. configurable: true
  37748. });
  37749. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37750. get: function () {
  37751. return this._rightStick;
  37752. },
  37753. set: function (newValues) {
  37754. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37755. this._onrightstickchanged(newValues);
  37756. }
  37757. this._rightStick = newValues;
  37758. },
  37759. enumerable: true,
  37760. configurable: true
  37761. });
  37762. Gamepad.prototype.update = function () {
  37763. if (this._leftStick) {
  37764. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37765. }
  37766. if (this._rightStick) {
  37767. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37768. }
  37769. };
  37770. return Gamepad;
  37771. })();
  37772. BABYLON.Gamepad = Gamepad;
  37773. var GenericPad = (function (_super) {
  37774. __extends(GenericPad, _super);
  37775. function GenericPad(id, index, gamepad) {
  37776. _super.call(this, id, index, gamepad);
  37777. this.id = id;
  37778. this.index = index;
  37779. this.gamepad = gamepad;
  37780. this._buttons = new Array(gamepad.buttons.length);
  37781. }
  37782. GenericPad.prototype.onbuttondown = function (callback) {
  37783. this._onbuttondown = callback;
  37784. };
  37785. GenericPad.prototype.onbuttonup = function (callback) {
  37786. this._onbuttonup = callback;
  37787. };
  37788. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37789. if (newValue !== currentValue) {
  37790. if (this._onbuttondown && newValue === 1) {
  37791. this._onbuttondown(buttonIndex);
  37792. }
  37793. if (this._onbuttonup && newValue === 0) {
  37794. this._onbuttonup(buttonIndex);
  37795. }
  37796. }
  37797. return newValue;
  37798. };
  37799. GenericPad.prototype.update = function () {
  37800. _super.prototype.update.call(this);
  37801. for (var index = 0; index < this._buttons.length; index++) {
  37802. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37803. }
  37804. };
  37805. return GenericPad;
  37806. })(Gamepad);
  37807. BABYLON.GenericPad = GenericPad;
  37808. (function (Xbox360Button) {
  37809. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37810. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37811. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37812. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37813. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37814. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37815. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37816. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37817. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37818. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37819. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37820. var Xbox360Button = BABYLON.Xbox360Button;
  37821. (function (Xbox360Dpad) {
  37822. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37823. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37824. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37825. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37826. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37827. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37828. var Xbox360Pad = (function (_super) {
  37829. __extends(Xbox360Pad, _super);
  37830. function Xbox360Pad() {
  37831. _super.apply(this, arguments);
  37832. this._leftTrigger = 0;
  37833. this._rightTrigger = 0;
  37834. this._buttonA = 0;
  37835. this._buttonB = 0;
  37836. this._buttonX = 0;
  37837. this._buttonY = 0;
  37838. this._buttonBack = 0;
  37839. this._buttonStart = 0;
  37840. this._buttonLB = 0;
  37841. this._buttonRB = 0;
  37842. this._buttonLeftStick = 0;
  37843. this._buttonRightStick = 0;
  37844. this._dPadUp = 0;
  37845. this._dPadDown = 0;
  37846. this._dPadLeft = 0;
  37847. this._dPadRight = 0;
  37848. }
  37849. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37850. this._onlefttriggerchanged = callback;
  37851. };
  37852. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37853. this._onrighttriggerchanged = callback;
  37854. };
  37855. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37856. get: function () {
  37857. return this._leftTrigger;
  37858. },
  37859. set: function (newValue) {
  37860. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37861. this._onlefttriggerchanged(newValue);
  37862. }
  37863. this._leftTrigger = newValue;
  37864. },
  37865. enumerable: true,
  37866. configurable: true
  37867. });
  37868. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37869. get: function () {
  37870. return this._rightTrigger;
  37871. },
  37872. set: function (newValue) {
  37873. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37874. this._onrighttriggerchanged(newValue);
  37875. }
  37876. this._rightTrigger = newValue;
  37877. },
  37878. enumerable: true,
  37879. configurable: true
  37880. });
  37881. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37882. this._onbuttondown = callback;
  37883. };
  37884. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37885. this._onbuttonup = callback;
  37886. };
  37887. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37888. this._ondpaddown = callback;
  37889. };
  37890. Xbox360Pad.prototype.ondpadup = function (callback) {
  37891. this._ondpadup = callback;
  37892. };
  37893. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37894. if (newValue !== currentValue) {
  37895. if (this._onbuttondown && newValue === 1) {
  37896. this._onbuttondown(buttonType);
  37897. }
  37898. if (this._onbuttonup && newValue === 0) {
  37899. this._onbuttonup(buttonType);
  37900. }
  37901. }
  37902. return newValue;
  37903. };
  37904. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37905. if (newValue !== currentValue) {
  37906. if (this._ondpaddown && newValue === 1) {
  37907. this._ondpaddown(buttonType);
  37908. }
  37909. if (this._ondpadup && newValue === 0) {
  37910. this._ondpadup(buttonType);
  37911. }
  37912. }
  37913. return newValue;
  37914. };
  37915. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37916. get: function () {
  37917. return this._buttonA;
  37918. },
  37919. set: function (value) {
  37920. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37926. get: function () {
  37927. return this._buttonB;
  37928. },
  37929. set: function (value) {
  37930. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37931. },
  37932. enumerable: true,
  37933. configurable: true
  37934. });
  37935. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37936. get: function () {
  37937. return this._buttonX;
  37938. },
  37939. set: function (value) {
  37940. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37941. },
  37942. enumerable: true,
  37943. configurable: true
  37944. });
  37945. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37946. get: function () {
  37947. return this._buttonY;
  37948. },
  37949. set: function (value) {
  37950. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37951. },
  37952. enumerable: true,
  37953. configurable: true
  37954. });
  37955. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37956. get: function () {
  37957. return this._buttonStart;
  37958. },
  37959. set: function (value) {
  37960. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37961. },
  37962. enumerable: true,
  37963. configurable: true
  37964. });
  37965. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37966. get: function () {
  37967. return this._buttonBack;
  37968. },
  37969. set: function (value) {
  37970. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37971. },
  37972. enumerable: true,
  37973. configurable: true
  37974. });
  37975. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37976. get: function () {
  37977. return this._buttonLB;
  37978. },
  37979. set: function (value) {
  37980. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37981. },
  37982. enumerable: true,
  37983. configurable: true
  37984. });
  37985. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37986. get: function () {
  37987. return this._buttonRB;
  37988. },
  37989. set: function (value) {
  37990. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  37996. get: function () {
  37997. return this._buttonLeftStick;
  37998. },
  37999. set: function (value) {
  38000. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38001. },
  38002. enumerable: true,
  38003. configurable: true
  38004. });
  38005. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38006. get: function () {
  38007. return this._buttonRightStick;
  38008. },
  38009. set: function (value) {
  38010. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38011. },
  38012. enumerable: true,
  38013. configurable: true
  38014. });
  38015. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38016. get: function () {
  38017. return this._dPadUp;
  38018. },
  38019. set: function (value) {
  38020. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38021. },
  38022. enumerable: true,
  38023. configurable: true
  38024. });
  38025. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38026. get: function () {
  38027. return this._dPadDown;
  38028. },
  38029. set: function (value) {
  38030. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38031. },
  38032. enumerable: true,
  38033. configurable: true
  38034. });
  38035. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38036. get: function () {
  38037. return this._dPadLeft;
  38038. },
  38039. set: function (value) {
  38040. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38041. },
  38042. enumerable: true,
  38043. configurable: true
  38044. });
  38045. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38046. get: function () {
  38047. return this._dPadRight;
  38048. },
  38049. set: function (value) {
  38050. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38051. },
  38052. enumerable: true,
  38053. configurable: true
  38054. });
  38055. Xbox360Pad.prototype.update = function () {
  38056. _super.prototype.update.call(this);
  38057. this.buttonA = this.browserGamepad.buttons[0].value;
  38058. this.buttonB = this.browserGamepad.buttons[1].value;
  38059. this.buttonX = this.browserGamepad.buttons[2].value;
  38060. this.buttonY = this.browserGamepad.buttons[3].value;
  38061. this.buttonLB = this.browserGamepad.buttons[4].value;
  38062. this.buttonRB = this.browserGamepad.buttons[5].value;
  38063. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38064. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38065. this.buttonBack = this.browserGamepad.buttons[8].value;
  38066. this.buttonStart = this.browserGamepad.buttons[9].value;
  38067. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38068. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38069. this.dPadUp = this.browserGamepad.buttons[12].value;
  38070. this.dPadDown = this.browserGamepad.buttons[13].value;
  38071. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38072. this.dPadRight = this.browserGamepad.buttons[15].value;
  38073. };
  38074. return Xbox360Pad;
  38075. })(Gamepad);
  38076. BABYLON.Xbox360Pad = Xbox360Pad;
  38077. })(BABYLON || (BABYLON = {}));
  38078. var BABYLON;
  38079. (function (BABYLON) {
  38080. // We're mainly based on the logic defined into the FreeCamera code
  38081. var GamepadCamera = (function (_super) {
  38082. __extends(GamepadCamera, _super);
  38083. function GamepadCamera(name, position, scene) {
  38084. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38085. _super.call(this, name, position, scene);
  38086. }
  38087. return GamepadCamera;
  38088. })(BABYLON.UniversalCamera);
  38089. BABYLON.GamepadCamera = GamepadCamera;
  38090. })(BABYLON || (BABYLON = {}));
  38091. var BABYLON;
  38092. (function (BABYLON) {
  38093. var AnaglyphFreeCamera = (function (_super) {
  38094. __extends(AnaglyphFreeCamera, _super);
  38095. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38096. _super.call(this, name, position, scene);
  38097. this.interaxialDistance = interaxialDistance;
  38098. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38099. }
  38100. return AnaglyphFreeCamera;
  38101. })(BABYLON.FreeCamera);
  38102. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38103. var AnaglyphArcRotateCamera = (function (_super) {
  38104. __extends(AnaglyphArcRotateCamera, _super);
  38105. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38106. _super.call(this, name, alpha, beta, radius, target, scene);
  38107. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38108. }
  38109. return AnaglyphArcRotateCamera;
  38110. })(BABYLON.ArcRotateCamera);
  38111. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38112. var AnaglyphGamepadCamera = (function (_super) {
  38113. __extends(AnaglyphGamepadCamera, _super);
  38114. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38115. _super.call(this, name, position, scene);
  38116. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38117. }
  38118. return AnaglyphGamepadCamera;
  38119. })(BABYLON.GamepadCamera);
  38120. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38121. var StereoscopicFreeCamera = (function (_super) {
  38122. __extends(StereoscopicFreeCamera, _super);
  38123. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38124. _super.call(this, name, position, scene);
  38125. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38126. }
  38127. return StereoscopicFreeCamera;
  38128. })(BABYLON.FreeCamera);
  38129. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38130. var StereoscopicArcRotateCamera = (function (_super) {
  38131. __extends(StereoscopicArcRotateCamera, _super);
  38132. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  38133. _super.call(this, name, alpha, beta, radius, target, scene);
  38134. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38135. }
  38136. return StereoscopicArcRotateCamera;
  38137. })(BABYLON.ArcRotateCamera);
  38138. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38139. var StereoscopicGamepadCamera = (function (_super) {
  38140. __extends(StereoscopicGamepadCamera, _super);
  38141. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38142. _super.call(this, name, position, scene);
  38143. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38144. }
  38145. return StereoscopicGamepadCamera;
  38146. })(BABYLON.GamepadCamera);
  38147. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38148. })(BABYLON || (BABYLON = {}));
  38149. var BABYLON;
  38150. (function (BABYLON) {
  38151. var Internals;
  38152. (function (Internals) {
  38153. var FileFaceOrientation = (function () {
  38154. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38155. this.name = name;
  38156. this.worldAxisForNormal = worldAxisForNormal;
  38157. this.worldAxisForFileX = worldAxisForFileX;
  38158. this.worldAxisForFileY = worldAxisForFileY;
  38159. }
  38160. return FileFaceOrientation;
  38161. })();
  38162. ;
  38163. var CubeMapToSphericalPolynomialTools = (function () {
  38164. function CubeMapToSphericalPolynomialTools() {
  38165. }
  38166. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38167. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38168. var totalSolidAngle = 0.0;
  38169. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38170. var du = 2.0 / cubeInfo.size;
  38171. var dv = du;
  38172. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38173. var minUV = du * 0.5 - 1.0;
  38174. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38175. var fileFace = this.FileFaces[faceIndex];
  38176. var dataArray = cubeInfo[fileFace.name];
  38177. var v = minUV;
  38178. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38179. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38180. // Because SP is still linear, so summation is fine in that basis.
  38181. for (var y = 0; y < cubeInfo.size; y++) {
  38182. var u = minUV;
  38183. for (var x = 0; x < cubeInfo.size; x++) {
  38184. // World direction (not normalised)
  38185. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38186. worldDirection.normalize();
  38187. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38188. if (1) {
  38189. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38190. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38191. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38192. var color = new BABYLON.Color3(r, g, b);
  38193. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38194. }
  38195. else {
  38196. if (faceIndex == 0) {
  38197. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38198. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38199. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38200. }
  38201. else if (faceIndex == 1) {
  38202. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38203. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38204. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38205. }
  38206. else if (faceIndex == 2) {
  38207. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38208. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38209. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38210. }
  38211. else if (faceIndex == 3) {
  38212. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38213. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38214. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38215. }
  38216. else if (faceIndex == 4) {
  38217. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38218. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38219. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38220. }
  38221. else if (faceIndex == 5) {
  38222. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38223. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38224. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38225. }
  38226. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  38227. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38228. }
  38229. totalSolidAngle += deltaSolidAngle;
  38230. u += du;
  38231. }
  38232. v += dv;
  38233. }
  38234. }
  38235. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  38236. var correction = correctSolidAngle / totalSolidAngle;
  38237. sphericalHarmonics.scale(correction);
  38238. // Additionally scale by pi -- audit needed
  38239. sphericalHarmonics.scale(1.0 / Math.PI);
  38240. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  38241. };
  38242. CubeMapToSphericalPolynomialTools.FileFaces = [
  38243. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  38244. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  38245. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  38246. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  38247. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  38248. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  38249. ];
  38250. return CubeMapToSphericalPolynomialTools;
  38251. })();
  38252. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  38253. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38254. })(BABYLON || (BABYLON = {}));
  38255. var BABYLON;
  38256. (function (BABYLON) {
  38257. var Internals;
  38258. (function (Internals) {
  38259. var PanoramaToCubeMapTools = (function () {
  38260. function PanoramaToCubeMapTools() {
  38261. }
  38262. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  38263. if (!float32Array) {
  38264. throw "ConvertPanoramaToCubemap: input cannot be null";
  38265. }
  38266. if (float32Array.length != inputWidth * inputHeight * 3) {
  38267. throw "ConvertPanoramaToCubemap: input size is wrong";
  38268. }
  38269. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  38270. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  38271. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  38272. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  38273. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  38274. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  38275. return {
  38276. front: textureFront,
  38277. back: textureBack,
  38278. left: textureLeft,
  38279. right: textureRight,
  38280. up: textureUp,
  38281. down: textureDown,
  38282. size: size
  38283. };
  38284. };
  38285. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  38286. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  38287. var textureArray = new Float32Array(buffer);
  38288. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  38289. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  38290. var dy = 1 / texSize;
  38291. var fy = 0;
  38292. for (var y = 0; y < texSize; y++) {
  38293. var xv1 = faceData[0];
  38294. var xv2 = faceData[2];
  38295. for (var x = 0; x < texSize; x++) {
  38296. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  38297. v.normalize();
  38298. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  38299. // 3 channels per pixels
  38300. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  38301. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  38302. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  38303. xv1 = xv1.add(rotDX1);
  38304. xv2 = xv2.add(rotDX2);
  38305. }
  38306. fy += dy;
  38307. }
  38308. return textureArray;
  38309. };
  38310. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  38311. var theta = Math.atan2(vDir.z, vDir.x);
  38312. var phi = Math.acos(vDir.y);
  38313. while (theta < -Math.PI)
  38314. theta += 2 * Math.PI;
  38315. while (theta > Math.PI)
  38316. theta -= 2 * Math.PI;
  38317. var dx = theta / Math.PI;
  38318. var dy = phi / Math.PI;
  38319. // recenter.
  38320. dx = dx * 0.5 + 0.5;
  38321. var px = Math.round(dx * inputWidth);
  38322. if (px < 0)
  38323. px = 0;
  38324. else if (px >= inputWidth)
  38325. px = inputWidth - 1;
  38326. var py = Math.round(dy * inputHeight);
  38327. if (py < 0)
  38328. py = 0;
  38329. else if (py >= inputHeight)
  38330. py = inputHeight - 1;
  38331. var inputY = (inputHeight - py - 1);
  38332. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  38333. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  38334. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  38335. return {
  38336. r: r,
  38337. g: g,
  38338. b: b
  38339. };
  38340. };
  38341. PanoramaToCubeMapTools.FACE_FRONT = [
  38342. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38343. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38344. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38345. new BABYLON.Vector3(1.0, 1.0, -1.0)
  38346. ];
  38347. PanoramaToCubeMapTools.FACE_BACK = [
  38348. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38349. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38350. new BABYLON.Vector3(1.0, 1.0, 1.0),
  38351. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  38352. ];
  38353. PanoramaToCubeMapTools.FACE_LEFT = [
  38354. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38355. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38356. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38357. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38358. ];
  38359. PanoramaToCubeMapTools.FACE_RIGHT = [
  38360. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38361. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38362. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38363. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  38364. ];
  38365. PanoramaToCubeMapTools.FACE_UP = [
  38366. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38367. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38368. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38369. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38370. ];
  38371. PanoramaToCubeMapTools.FACE_DOWN = [
  38372. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38373. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38374. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38375. new BABYLON.Vector3(1.0, -1.0, -1.0)
  38376. ];
  38377. return PanoramaToCubeMapTools;
  38378. })();
  38379. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  38380. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38381. })(BABYLON || (BABYLON = {}));
  38382. var BABYLON;
  38383. (function (BABYLON) {
  38384. var Internals;
  38385. (function (Internals) {
  38386. ;
  38387. var HDRTools = (function () {
  38388. function HDRTools() {
  38389. }
  38390. HDRTools.Ldexp = function (mantissa, exponent) {
  38391. if (exponent > 1023) {
  38392. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  38393. }
  38394. if (exponent < -1074) {
  38395. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  38396. }
  38397. return mantissa * Math.pow(2, exponent);
  38398. };
  38399. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  38400. if (exponent > 0) {
  38401. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  38402. float32array[index + 0] = red * exponent;
  38403. float32array[index + 1] = green * exponent;
  38404. float32array[index + 2] = blue * exponent;
  38405. }
  38406. else {
  38407. float32array[index + 0] = 0;
  38408. float32array[index + 1] = 0;
  38409. float32array[index + 2] = 0;
  38410. }
  38411. };
  38412. HDRTools.readStringLine = function (uint8array, startIndex) {
  38413. var line = "";
  38414. var character = "";
  38415. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  38416. character = String.fromCharCode(uint8array[i]);
  38417. if (character == "\n") {
  38418. break;
  38419. }
  38420. line += character;
  38421. }
  38422. return line;
  38423. };
  38424. /* minimal header reading. modify if you want to parse more information */
  38425. HDRTools.RGBE_ReadHeader = function (uint8array) {
  38426. var height = 0;
  38427. var width = 0;
  38428. var line = this.readStringLine(uint8array, 0);
  38429. if (line[0] != '#' || line[1] != '?') {
  38430. throw "Bad HDR Format.";
  38431. }
  38432. var endOfHeader = false;
  38433. var findFormat = false;
  38434. var lineIndex = 0;
  38435. do {
  38436. lineIndex += (line.length + 1);
  38437. line = this.readStringLine(uint8array, lineIndex);
  38438. if (line == "FORMAT=32-bit_rle_rgbe") {
  38439. findFormat = true;
  38440. }
  38441. else if (line.length == 0) {
  38442. endOfHeader = true;
  38443. }
  38444. } while (!endOfHeader);
  38445. if (!findFormat) {
  38446. throw "HDR Bad header format, unsupported FORMAT";
  38447. }
  38448. lineIndex += (line.length + 1);
  38449. line = this.readStringLine(uint8array, lineIndex);
  38450. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  38451. var match = sizeRegexp.exec(line);
  38452. // TODO. Support +Y and -X if needed.
  38453. if (match.length < 3) {
  38454. throw "HDR Bad header format, no size";
  38455. }
  38456. width = parseInt(match[2]);
  38457. height = parseInt(match[1]);
  38458. if (width < 8 || width > 0x7fff) {
  38459. throw "HDR Bad header format, unsupported size";
  38460. }
  38461. lineIndex += (line.length + 1);
  38462. return {
  38463. height: height,
  38464. width: width,
  38465. dataPosition: lineIndex
  38466. };
  38467. };
  38468. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  38469. var uint8array = new Uint8Array(buffer);
  38470. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  38471. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38472. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  38473. return cubeMapData;
  38474. };
  38475. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  38476. // Keep for multi format supports.
  38477. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38478. };
  38479. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  38480. var num_scanlines = hdrInfo.height;
  38481. var scanline_width = hdrInfo.width;
  38482. var a, b, c, d, count;
  38483. var dataIndex = hdrInfo.dataPosition;
  38484. var index = 0, endIndex = 0, i = 0;
  38485. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  38486. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  38487. // 3 channels of 4 bytes per pixel in float.
  38488. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  38489. var resultArray = new Float32Array(resultBuffer);
  38490. // read in each successive scanline
  38491. while (num_scanlines > 0) {
  38492. a = uint8array[dataIndex++];
  38493. b = uint8array[dataIndex++];
  38494. c = uint8array[dataIndex++];
  38495. d = uint8array[dataIndex++];
  38496. if (a != 2 || b != 2 || (c & 0x80)) {
  38497. // this file is not run length encoded
  38498. throw "HDR Bad header format, not RLE";
  38499. }
  38500. if (((c << 8) | d) != scanline_width) {
  38501. throw "HDR Bad header format, wrong scan line width";
  38502. }
  38503. index = 0;
  38504. // read each of the four channels for the scanline into the buffer
  38505. for (i = 0; i < 4; i++) {
  38506. endIndex = (i + 1) * scanline_width;
  38507. while (index < endIndex) {
  38508. a = uint8array[dataIndex++];
  38509. b = uint8array[dataIndex++];
  38510. if (a > 128) {
  38511. // a run of the same value
  38512. count = a - 128;
  38513. if ((count == 0) || (count > endIndex - index)) {
  38514. throw "HDR Bad Format, bad scanline data (run)";
  38515. }
  38516. while (count-- > 0) {
  38517. scanLineArray[index++] = b;
  38518. }
  38519. }
  38520. else {
  38521. // a non-run
  38522. count = a;
  38523. if ((count == 0) || (count > endIndex - index)) {
  38524. throw "HDR Bad Format, bad scanline data (non-run)";
  38525. }
  38526. scanLineArray[index++] = b;
  38527. if (--count > 0) {
  38528. for (var j = 0; j < count; j++) {
  38529. scanLineArray[index++] = uint8array[dataIndex++];
  38530. }
  38531. }
  38532. }
  38533. }
  38534. }
  38535. // now convert data from buffer into floats
  38536. for (i = 0; i < scanline_width; i++) {
  38537. a = scanLineArray[i];
  38538. b = scanLineArray[i + scanline_width];
  38539. c = scanLineArray[i + 2 * scanline_width];
  38540. d = scanLineArray[i + 3 * scanline_width];
  38541. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  38542. }
  38543. num_scanlines--;
  38544. }
  38545. return resultArray;
  38546. };
  38547. return HDRTools;
  38548. })();
  38549. Internals.HDRTools = HDRTools;
  38550. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38551. })(BABYLON || (BABYLON = {}));
  38552. var BABYLON;
  38553. (function (BABYLON) {
  38554. var HDRCubeTexture = (function (_super) {
  38555. __extends(HDRCubeTexture, _super);
  38556. function HDRCubeTexture(url, scene, size, noMipmap) {
  38557. _super.call(this, scene);
  38558. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  38559. this.sphericalPolynomial = null;
  38560. this.name = url;
  38561. this.url = url;
  38562. this._noMipmap = noMipmap;
  38563. this.hasAlpha = false;
  38564. this._size = size;
  38565. if (!url) {
  38566. return;
  38567. }
  38568. this._texture = this._getFromCache(url, noMipmap);
  38569. if (!this._texture) {
  38570. if (!scene.useDelayedTextureLoading) {
  38571. this.loadTexture();
  38572. }
  38573. else {
  38574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38575. }
  38576. }
  38577. this.isCube = true;
  38578. this._textureMatrix = BABYLON.Matrix.Identity();
  38579. }
  38580. HDRCubeTexture.prototype.loadTexture = function () {
  38581. var _this = this;
  38582. var callback = function (buffer) {
  38583. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  38584. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  38585. var mapping = [
  38586. "left",
  38587. "down",
  38588. "front",
  38589. "right",
  38590. "up",
  38591. "back"
  38592. ];
  38593. var results = [];
  38594. for (var j = 0; j < 6; j++) {
  38595. var dataFace = data[mapping[j]];
  38596. // TODO. Support Int Textures...
  38597. // // 3 channels of 1 bytes per pixel in bytes.
  38598. // var byteBuffer = new ArrayBuffer(this._size * this._size * 3);
  38599. // var byteArray = new Uint8Array(byteBuffer);
  38600. //
  38601. // /* now convert data from buffer into bytes */
  38602. // for(var i = 0; i < this._size * this._size; i++) {
  38603. // byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  38604. // byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  38605. // byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  38606. // }
  38607. results.push(dataFace);
  38608. }
  38609. return results;
  38610. };
  38611. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  38612. };
  38613. HDRCubeTexture.prototype.clone = function () {
  38614. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap);
  38615. // Base texture
  38616. newTexture.level = this.level;
  38617. newTexture.wrapU = this.wrapU;
  38618. newTexture.wrapV = this.wrapV;
  38619. newTexture.coordinatesIndex = this.coordinatesIndex;
  38620. newTexture.coordinatesMode = this.coordinatesMode;
  38621. return newTexture;
  38622. };
  38623. // Methods
  38624. HDRCubeTexture.prototype.delayLoad = function () {
  38625. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38626. return;
  38627. }
  38628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38629. this._texture = this._getFromCache(this.url, this._noMipmap);
  38630. if (!this._texture) {
  38631. this.loadTexture();
  38632. }
  38633. };
  38634. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  38635. return this._textureMatrix;
  38636. };
  38637. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38638. var texture = null;
  38639. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38640. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size);
  38641. texture.name = parsedTexture.name;
  38642. texture.hasAlpha = parsedTexture.hasAlpha;
  38643. texture.level = parsedTexture.level;
  38644. texture.coordinatesMode = parsedTexture.coordinatesMode;
  38645. }
  38646. return texture;
  38647. };
  38648. HDRCubeTexture.prototype.serialize = function () {
  38649. if (!this.name) {
  38650. return null;
  38651. }
  38652. var serializationObject = {};
  38653. serializationObject.name = this.name;
  38654. serializationObject.hasAlpha = this.hasAlpha;
  38655. serializationObject.isCube = true;
  38656. serializationObject.level = this.level;
  38657. serializationObject.size = this._size;
  38658. serializationObject.coordinatesMode = this.coordinatesMode;
  38659. return serializationObject;
  38660. };
  38661. return HDRCubeTexture;
  38662. })(BABYLON.BaseTexture);
  38663. BABYLON.HDRCubeTexture = HDRCubeTexture;
  38664. })(BABYLON || (BABYLON = {}));
  38665. 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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// 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#include<fogFragmentDeclaration>\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\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#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#include<fogFragment>\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#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\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#include<fogVertex>\r\n#include<shadowsVertex>\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\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\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\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#include<fogFragment>\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#include<bonesDeclaration>\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#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n#include<fogVertex>\r\n#include<shadowsVertex>\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\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#include<fogVertexDeclaration>\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}"};
  38666. 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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,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),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},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),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,c=0,y=0,p=0,l=0,x=0,z=0,w=-1,v=0,d=b.Vector3[0],g=0,T=b.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),y=Math.acos(g)*w,i.Dot(T,a)<0&&(y=Math.PI+y,T=T.scaleInPlace(-1),v++);var R=b.Vector3[2],_=b.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=y},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/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),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*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],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,E=h*y-a*c,S=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-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*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*E-r*S+o*q)*b,t.m[7]=(i*E-r*D+o*V)*b,t.m[11]=-(i*S-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=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],d=t.m[1],g=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],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],E=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*E,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*E,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*E,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*E,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,c,y,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]=c,x.m[12]=y,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,c,y,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]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0;\n},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,c=new e(0,0,0);n.decompose(u,m,c);var y=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,c,r);return i.Compose(y,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,c=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(c)},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],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,c)},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,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*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 c=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=c;var y=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=y;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),c=m.subtract(u);return c.normalize(),new i(u,c)},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,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-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 d=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),c=m.angle.radians()/e;m.orientation===x.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var f=Math.cos(y)*m.radius+m.centerPoint.x,l=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(f,l),y+=c}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 c=u.normalize(),y=n-r;return new s(h.x+c.x*y,h.y+c.y*y)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=d;var g=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=g;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(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var _=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=_;var M=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=M;var F=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=F;var b=function(){function t(){}return t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=b}(BABYLON||(BABYLON={}));";
  38667. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#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","bonesVertex":"#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\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","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#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","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// 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\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","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\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\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  38668. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  38669. module.exports = BABYLON;
  38670. };